title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Log into Google account using Python?
39,540,479
<p>I want to Sign into my Google account using Python but when I print the html results it doesn't show my username. That's how I know it isn't logged in.</p> <p>How do I sign into google using Python? I have seen two popular modules so far for this urllib.request or Requests but none have helped me with logging into ...
2
2016-09-16T21:42:16Z
39,540,549
<p>Except by using <a href="http://stackoverflow.com/q/10271110/1658617">oAuth</a> or their API, google has things like captcha and so to prevent bots from brute-forcing and guessing passwords.</p> <p>You can try and trick the user-agent but I still believe it's to vein.</p>
0
2016-09-16T21:48:34Z
[ "python", "python-3.x" ]
Log into Google account using Python?
39,540,479
<p>I want to Sign into my Google account using Python but when I print the html results it doesn't show my username. That's how I know it isn't logged in.</p> <p>How do I sign into google using Python? I have seen two popular modules so far for this urllib.request or Requests but none have helped me with logging into ...
2
2016-09-16T21:42:16Z
39,541,371
<p>This will get you logged in:</p> <pre><code>from bs4 import BeautifulSoup import requests form_data={'Email': '[email protected]', 'Passwd': 'your_password'} post = "https://accounts.google.com/signin/challenge/sl/password" with requests.Session() as s: soup = BeautifulSoup(s.get("https://mail.google.com").text)...
1
2016-09-16T23:27:31Z
[ "python", "python-3.x" ]
How to return result from a function in Django html form?
39,540,522
<p>Basically I have this form right here</p> <pre><code>&lt;form method="POST" action="."&gt; &lt;input type="text" name="fcal" value="{{F}}" /&gt; &lt;p&gt; &lt;input type="submit" name="fibo" value="Fibonacci" /&gt; &lt;/p&gt; &lt;/form&gt; </code></pre> <p>I would like the user to input a number and after th...
0
2016-09-16T21:46:34Z
39,540,582
<p>your html file</p> <pre><code> &lt;form method="POST" action="."&gt; &lt;input type="text" name="fcal" value="{{F}}" /&gt; &lt;p&gt; &lt;input type="submit" name="fibo" value="Fibonacci" /&gt; &lt;/p&gt; &lt;/form&gt; {% if cal %} Your Fibonacci answer is {{cal}} {% endif %} </c...
0
2016-09-16T21:51:31Z
[ "python", "django" ]
Self delete page in wx.Notebook
39,540,563
<p>I want to dynamically create and delete pages in a notebook. In the main class I successfully create and add pages with a button. The pages are a separate class of course, and have a button inside. I know I can put the button outside the notebook and delete them from the main class but I want to use page's own butto...
0
2016-09-16T21:49:48Z
39,541,649
<p>As you've guessed, care needs to be taken when destroying UI objects from their own event handlers. Not only is the current event handler still active, but there may be other pending events that are still in the queue, and if the target object has been destroyed when they are delivered then you can get a crash.</p>...
0
2016-09-17T00:14:34Z
[ "python", "wxpython", "wxnotebook" ]
Django get info in the same web without showing pk in url
39,540,566
<p>I'm trying to get info from a model but without moving the url, let me explain by myself when I access to for example:</p> <p>/list It shows the info and if I just make a click in there i can access to the complete info of this user, or book or something and the url change to detail/8/</p> <p>Is there any way to g...
0
2016-09-16T21:50:04Z
39,541,831
<p>If you are trying to create an 'unguessable' url for each book or other item in your database to stop unauthorized access, you are on the wrong track. Unguessable URLs can and will be guessed and people who shouldn't see or edit them, will edit them.</p> <p>At the very least you should check if the user is authenti...
2
2016-09-17T00:46:43Z
[ "python", "django", "django-views" ]
Rename CSV File Headers using Dynamic String in Python
39,540,579
<p>Below is the CSV file structure that I have,</p> <pre><code>ITEM | ID | SET | COUNT | ------ | ------ |------ | ------ | Value | 44000001005 | 0 | 24 | Value | 10000000019659 | 0 | 29 | Value | 10000000019659 | 1 | 5 | </code></pre> <p>I want to Dynamically t...
0
2016-09-16T21:51:22Z
39,540,835
<p>Use the csv module to read and edit the header then write all the rows back to the new file</p> <pre><code>import csv with open("input.csv") as f, open("output.csv", "wb") as o: ui = raw_input("Enter user input: ") reader = csv.reader(f) header = reader.next() writer = csv.writer(o) new_hea...
0
2016-09-16T22:16:19Z
[ "python", "csv" ]
How to apply decorators to Cython cpdef functions
39,540,599
<p>I've been playing around with Cython lately and I came across this error when applying a decorator to a Cython function</p> <p><code>Cdef functions/classes cannot take arbitrary decorators</code></p> <p>Here is the code I was tinkering with:</p> <pre><code>import functools def memoize(f): computed = {} @...
3
2016-09-16T21:53:14Z
39,544,561
<p><strong>No</strong> - you can't easily write decorators for <code>cdef</code> functions. The decorators <code>cdef</code> functions take are things like <code>cython.boundscheck</code> which control the Cython code generation rather than user generated functions.</p> <p>The main difference between a <code>cdef</cod...
2
2016-09-17T08:18:31Z
[ "python", "cython", "cythonize" ]
Python sqlite3 'executemany' not successfully updating my database
39,540,600
<p>I'm trying to extract a column from my database, apply a transformation, and create a new column with the results. </p> <p>I ultimately want to save the local variable 'new_proba' (which has a length of 740, the same length as my database) as a new column called 'predict_proba_tplus1'. From reading <a href="http://...
0
2016-09-16T21:53:33Z
39,598,087
<p>Those values aren't plain <code>float</code>; they're <code>numpy.float64</code>, which the database can't handle.</p> <p>Convert your values to plain <code>float</code> and <code>int</code> like this:</p> <pre><code>new_proba = list(float(z) for z in clf.predict_proba(X)[:,1]) IDs = list(int(zz) for zz in np.aran...
0
2016-09-20T15:26:48Z
[ "python", "sqlite3", "sql-update", "executemany" ]
Django - TypeError: 'genre' is an invalid keyword argument for this function
39,540,634
<p>I’m using Django and I'm having a problem running a Python script that uses Django models</p> <p>The script that I'm using takes data from an api and loads it into my database, however, I'm getting a TypeError while trying to run it:</p> <pre><code>&gt;&gt;&gt; exec(open('load_from_api.py').read()) Traceback (mo...
0
2016-09-16T21:56:55Z
39,541,140
<p>try this:</p> <pre><code>for movie in results: obj, data = Movie.objects.get_or_create(title=movie['title'], tmdb_id=movie['id'], release=movie['release_date'], description=movie['overview'], ...
0
2016-09-16T22:56:22Z
[ "python", "django" ]
Django - TypeError: 'genre' is an invalid keyword argument for this function
39,540,634
<p>I’m using Django and I'm having a problem running a Python script that uses Django models</p> <p>The script that I'm using takes data from an api and loads it into my database, however, I'm getting a TypeError while trying to run it:</p> <pre><code>&gt;&gt;&gt; exec(open('load_from_api.py').read()) Traceback (mo...
0
2016-09-16T21:56:55Z
39,541,172
<blockquote> <p>get_or_create()</p> <p>Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.</p> </blockquote> <p>so instead of:</p> <pre><code>data = Movie.objects.get_or_create(title=movie['title'], ...
0
2016-09-16T22:59:33Z
[ "python", "django" ]
Remove edges from a graph using networkx
39,540,705
<p>I am trying to convert a <code>DiGraph</code> into n-ary tree and displaying the nodes in level order or BFS. My tree is similar to this, but much larger, for simplicity using this example: </p> <pre><code>G = networkx.DiGraph() G.add_edges_from([('n', 'n1'), ('n', 'n2'), ('n', 'n3')]) G.add_edges_from([('n4', 'n41...
1
2016-09-16T22:02:28Z
39,541,027
<p>Looks like you want to find the minimum spanning tree of the graph G, you can use Prim's or Kruskal's algorithm's implementation: here is one from scipy: <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree.html" rel="nofollow">http://docs.scipy.org/doc/scipy...
0
2016-09-16T22:42:14Z
[ "python", "algorithm", "networkx" ]
How to make xticks evenly spaced despite their value?
39,540,730
<p>I am trying to generate a plot with x-axis being a geometric sequence while the y axis is a number between 0.0 and 1.0. My code looks like this:</p> <pre><code>form matplotlib import pyplot as plt plt.xticks(X) plt.plot(X,Y) plt.show() </code></pre> <p>which generates a plot like this:</p> <p><a href="http://i.st...
0
2016-09-16T22:04:50Z
39,545,860
<p>You can do it by plotting your variable as a function of the "natural" variable that parametrizes your curve. For example:</p> <pre><code>n = 12 a = np.arange(n) x = 2**a y = np.random.rand(n) fig = plt.figure(1, figsize=(7,7)) ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) ax1.plot(x,y) ax1.xaxis.set_ti...
0
2016-09-17T10:41:20Z
[ "python", "matplotlib", "plot" ]
How do I use JWT with grpc?
39,540,731
<p>I am trying to get my head wrapped around <a href="http://www.grpc.io/docs/guides/auth.html#using-client-side-ssltls" rel="nofollow">grpc authentication</a>. From the looks of the examples, it looks like grpc supports ssl/tls and google tokens...</p> <p>I've also looked at <a href="https://jwt.io/" rel="nofollow">j...
0
2016-09-16T22:04:55Z
39,541,040
<p>The normal JWT approach uses service account credentials which are provided by the environment in a well-known location. This is what "Google Default Credentials" are in the examples. These are by far the easiest to get working, and have the best security and performance characteristics.</p> <p>OAuth2 is also suppo...
1
2016-09-16T22:44:06Z
[ "python", "authentication", "token", "jwt", "grpc" ]
Google Cloud Vision - Numbers and Numerals OCR
39,540,741
<p>I've been trying to implement an OCR program with Python that reads numbers with a specific format, XXX-XXX. I used Google's Cloud Vision API Text Recognition, but the results were unreliable. Out of 30 high-contrast 1280 x 1024 bmp images, only a handful resulted in the correct output, or at least included the corr...
11
2016-09-16T22:06:03Z
39,680,724
<p>At this moment it is not possible to add constraints or to give a specific expected number format to Vision API requests, as mentioned <a href="http://stackoverflow.com/questions/36125830/google-cloud-vision-text-detection-only-on-digits">here</a> (by the Project Manager of Cloud Vision API).</p> <p>You can also ch...
3
2016-09-24T20:33:40Z
[ "python", "ocr", "google-cloud-platform", "google-cloud-vision", "text-recognition" ]
Google Cloud Vision - Numbers and Numerals OCR
39,540,741
<p>I've been trying to implement an OCR program with Python that reads numbers with a specific format, XXX-XXX. I used Google's Cloud Vision API Text Recognition, but the results were unreliable. Out of 30 high-contrast 1280 x 1024 bmp images, only a handful resulted in the correct output, or at least included the corr...
11
2016-09-16T22:06:03Z
39,809,660
<p>I am unable to tell you why this works, perhaps it has to do with how the language is read, o vs 0, l vs 1, etc. But whenever I use OCR and I am specifically looking for numbers, I have read to set the detection language to "Korean". It works exceptionally well for me and has influenced the accuracy greatly. </p>
1
2016-10-01T17:43:03Z
[ "python", "ocr", "google-cloud-platform", "google-cloud-vision", "text-recognition" ]
How to rename the sheet name in the spread-sheet using Python?
39,540,789
<p>Have a scenario where I wanted to change the name of the "Sheet" in the spread-sheet.</p> <p>a. I tried created a spread-sheet saying <code>ss = Workbook()</code>. Think, this is creating the spread-sheet with a sheet named "Sheet"</p> <p>b. I tried changing the name of the sheet using the below format, </p> <pre...
1
2016-09-16T22:10:44Z
39,552,011
<p>You can do this by doing the following:</p> <pre><code>import openpyxl ss=openpyxl.load_workbook("file.xlsx") #printing the sheet names ss_sheet = ss.get_sheet_by_name('Sheet') ss_sheet.title = 'Fruit' ss.save("file.xlsx") </code></pre> <p>This works for me. Hope this helps.</p>
0
2016-09-17T21:40:49Z
[ "python", "python-2.7" ]
I am trying to make a lcd program so that all the numbers are printed side by side and its not working
39,540,902
<p>I am trying to print out ascii numbers side by side in python after the previous number is printed. If I put a comma after the last line in the function only the top part of the next number is printed.</p> <pre><code>def zero(): print " __ " print "| |" print "|__|" def one(): print " " pri...
1
2016-09-16T22:24:27Z
39,540,967
<p>This code prints three lines of output:</p> <pre><code>print " __ " print "|__|" print " |" </code></pre> <p>One that is printed, there is no good way to go back up and print the next number. </p> <p>The solution is to print the first line of each character, then the second line of each character etc...</p> <p...
1
2016-09-16T22:33:06Z
[ "python", "python-2.7" ]
I am trying to make a lcd program so that all the numbers are printed side by side and its not working
39,540,902
<p>I am trying to print out ascii numbers side by side in python after the previous number is printed. If I put a comma after the last line in the function only the top part of the next number is printed.</p> <pre><code>def zero(): print " __ " print "| |" print "|__|" def one(): print " " pri...
1
2016-09-16T22:24:27Z
39,541,178
<p>funny exercice :)</p> <p>following the comments of @zvone perhaps something like this:</p> <pre><code>def zero(): chars = [" __ "] chars += ["| |"] chars += ["|__|"] return chars def one(): chars = [" "] chars += [" |"] chars += [" |"] return chars def two(): chars ...
0
2016-09-16T23:00:20Z
[ "python", "python-2.7" ]
I am trying to make a lcd program so that all the numbers are printed side by side and its not working
39,540,902
<p>I am trying to print out ascii numbers side by side in python after the previous number is printed. If I put a comma after the last line in the function only the top part of the next number is printed.</p> <pre><code>def zero(): print " __ " print "| |" print "|__|" def one(): print " " pri...
1
2016-09-16T22:24:27Z
39,541,372
<p>As said before, your approach was a bit off. I implemented one that takes your list numbers and then builds the result line by line (i.e., top, middle, then bottom).</p> <pre><code>class zero: top = " __ " mid = "| |" bot = "|__|" class one: top = " " mid = " |" bot = " |" class t...
0
2016-09-16T23:27:46Z
[ "python", "python-2.7" ]
Extracting Adam update rates in Tensorflow
39,540,977
<p>I want to find out and keep track of Adam update rate of</p> <pre><code>lr_t &lt;- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t) </code></pre> <p>I followed another post and got the nodes of a graph by </p> <pre><code>[n.name for n in tf.get_default_graph().as_graph_def().node] </code></pre> <p>In which I fo...
1
2016-09-16T22:34:30Z
39,550,537
<p>Suppose you've defined an optimizer:</p> <pre><code>optm = tf.train.AdamOptimizer(learning_rate = 0.01) train_step = optm.minimize(L) </code></pre> <p>Now you could reach v_t and m_t with the following code:</p> <pre><code>optm.get_slot(W, 'v') optm.get_slot(W, 'm') </code></pre> <p>These values are tensors so t...
-1
2016-09-17T18:50:47Z
[ "python", "machine-learning", "tensorflow", "deep-learning" ]
How to set a variable to the result of command function of a tkinter Button?
39,540,999
<p>So here is my problem that I just can't figure out and can't seem to find information to help me understand what is happening. So I set <code>source</code> equal to the button that calls a function called <code>openDirectory</code> which is really just a short-cut to call <code>os.path.join()</code> and <code>os.pat...
0
2016-09-16T22:38:43Z
39,541,092
<p>Buttons do not work that way. When a function serves as a button's callback and the function is called by using the button, there's nowhere to return to. There isn't really a sensible way to make that work. If it worked the way you are guessing it does, you would lose the reference to the button! You don't want that...
1
2016-09-16T22:50:48Z
[ "python", "python-3.x", "button", "tkinter" ]
requests.exceptions.MissingSchema: Invalid URL (with bs4)
39,541,071
<p>I am getting this error: requests.exceptions.MissingSchema: Invalid URL 'http:/1525/bg.png': No schema supplied. Perhaps you meant <a href="http://http:/1525/bg.png" rel="nofollow">http://http:/1525/bg.png</a>?</p> <p>I don't really care why the error happened, I want to be able to capture any Invalid URL errors, i...
0
2016-09-16T22:47:21Z
39,541,226
<p>if you don't care about the error (which i see as bad programming), just use a blank except statement that catches all exceptions.</p> <pre><code>#download the image print('Downloading image... %s' % (comicUrl)) try: res = requests.get(comicUrl) # moved inside the try block res.raise_for_status() except: ...
0
2016-09-16T23:09:10Z
[ "python" ]
How to check if multiple items from a list appear in a string?
39,541,076
<p>Let's say I have a list of keywords:</p> <pre><code>keywords = ["history terms","history words","history vocab","history words terms","history vocab words","science list","science terms vocab","math terms words vocab"] </code></pre> <p>And a list of main terms:</p> <pre><code>`main_terms = ["terms","words","vocab...
2
2016-09-16T22:47:38Z
39,541,224
<p>I'm sure there's a more elegant solution, but this seems to be the solution for which you're looking, at least for part 1):</p> <pre><code>&gt;&gt;&gt; def remove_main_terms(keyword): words = keyword.split() count = 0 to_keep = [] for word in words: if word in main_terms:...
0
2016-09-16T23:09:00Z
[ "python" ]
How to check if multiple items from a list appear in a string?
39,541,076
<p>Let's say I have a list of keywords:</p> <pre><code>keywords = ["history terms","history words","history vocab","history words terms","history vocab words","science list","science terms vocab","math terms words vocab"] </code></pre> <p>And a list of main terms:</p> <pre><code>`main_terms = ["terms","words","vocab...
2
2016-09-16T22:47:38Z
39,541,246
<p>EDIT: I'm increasingly thinking you're asking an <a href="http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem">XY Question</a> and you want unique subjects.</p> <p>If that is the case, the following works even better:</p> <pre><code>result = [] found = [] for word in keywords: for term in main...
0
2016-09-16T23:11:17Z
[ "python" ]
How to check if multiple items from a list appear in a string?
39,541,076
<p>Let's say I have a list of keywords:</p> <pre><code>keywords = ["history terms","history words","history vocab","history words terms","history vocab words","science list","science terms vocab","math terms words vocab"] </code></pre> <p>And a list of main terms:</p> <pre><code>`main_terms = ["terms","words","vocab...
2
2016-09-16T22:47:38Z
39,541,251
<p>Loop through the <code>keywords</code> and check each one against the <code>main_terms</code>:</p> <pre><code>keywords = ["history terms", "history words", "history vocab", "history words terms", "history vocab words", "science list", "science ...
1
2016-09-16T23:11:52Z
[ "python" ]
Need a way to test SSH with a timeout
39,541,080
<p>This is my current code to test if a host is SSH-able. It works just fine when the host is up with or without SSH service running. However, it seems to just hang when the host crashes, which is the unique usecase that I need to depend on it giving me a quick True/False response. Due to OS and other dependencies, we ...
0
2016-09-16T22:48:46Z
39,541,189
<p>You need to determine if it is actually a connect timeout, or if it can connect, but the server is accepting the connection and doesn't send anything.</p> <p>If you were to use telnet to manually test, telnet 22 and see if you get a response from the server at all, you should see something like this if it connects...
0
2016-09-16T23:03:12Z
[ "python", "ssh" ]
Need a way to test SSH with a timeout
39,541,080
<p>This is my current code to test if a host is SSH-able. It works just fine when the host is up with or without SSH service running. However, it seems to just hang when the host crashes, which is the unique usecase that I need to depend on it giving me a quick True/False response. Due to OS and other dependencies, we ...
0
2016-09-16T22:48:46Z
39,543,654
<p>If you want to be sure that an SSH connection (including authentication) can be established correctly, the best way probably is to connect in batch mode with a small timeout (<code>-o BatchMode=yes -o ConnectTimeout=2</code>).</p>
0
2016-09-17T06:39:18Z
[ "python", "ssh" ]
Need a way to test SSH with a timeout
39,541,080
<p>This is my current code to test if a host is SSH-able. It works just fine when the host is up with or without SSH service running. However, it seems to just hang when the host crashes, which is the unique usecase that I need to depend on it giving me a quick True/False response. Due to OS and other dependencies, we ...
0
2016-09-16T22:48:46Z
39,561,302
<p>you could wrap your call to <code>ssh</code> into <code>timelimit</code> so it gets cancelled after a certain timeout if it does not finish on time.</p> <ul> <li>homepage: <a href="http://devel.ringlet.net/sysutils/timelimit/" rel="nofollow">http://devel.ringlet.net/sysutils/timelimit/</a></li> <li>manpage: <a href...
0
2016-09-18T18:40:58Z
[ "python", "ssh" ]
Package for multiple correlation?
39,541,144
<p>Is there any easy to use python package that helps in calculating multiple correlation? Its definition is as follows:</p> <p><a href="https://en.wikipedia.org/wiki/Multiple_correlation" rel="nofollow">https://en.wikipedia.org/wiki/Multiple_correlation</a></p>
0
2016-09-16T22:56:47Z
39,541,336
<p>Very similar question here: <a href="http://stackoverflow.com/questions/13452353/multiple-correlation-in-python">multiple correlation in python</a></p> <p>The answer given is an implementation using pandas. </p> <p>Alternatively you could look at Numpy/Scipy, they likely have something you could use. <a href="h...
0
2016-09-16T23:21:57Z
[ "python", "correlation" ]
Understanding threading synchronization
39,541,212
<p>The Fredrik Lundh article titled <a href="http://effbot.org/zone/thread-synchronization.htm" rel="nofollow"><em>Thread Synchronization Mechanisms in Python</em></a> gives the example below to show that multiple threads operating can result in an inaccurate value.</p> <pre><code>counter = 0 def process_item(item): ...
0
2016-09-16T23:06:28Z
39,541,254
<p>In Python the code:</p> <pre><code>counter += 1 </code></pre> <p>is the same as saying:</p> <pre><code>counter = counter + 1 </code></pre> <p>Thus the lookup of the value is separate to the update.</p>
3
2016-09-16T23:12:03Z
[ "python", "multithreading" ]
I need to make py to exe. I'm using python 3.5.2
39,541,220
<p>I need to make py to exe. I'm using python 3.5.2. Try to install pyinstaller for it. But didnt understand how it install it properly or how to use it? I'm a beginner of python. Could someone please explaine in in very basic manner? Thank you for your time.</p>
-2
2016-09-16T23:08:03Z
39,761,244
<p>First install pyinstaller with pip: <strong>pip install pyinstaller</strong></p> <p>If the installation is successful, try to create an exe with the following command:</p> <pre><code>pyinstaller --onefile [your_script].py </code></pre> <p>Update your question with the errors, if you get any.</p>
0
2016-09-29T04:07:58Z
[ "python", "python-3.x", "exe", "pyinstaller" ]
How to write a recursive function to print a string a certain number of times?
39,541,240
<p>I have been trying to write a python function which will receive two arguments: <code>x</code> which is the number of times to repeat and <code>y</code> which is the number or string to be repeated.</p> <p>So far this is what I have been able to come up with, but I can't seem to be able to determine how to do it re...
0
2016-09-16T23:10:24Z
39,541,314
<p>True functional recursion should have <em>no</em> assignments (i.e. state). This can be achieved using what's called an <em>accumulator</em>, i.e. an array that is built up successively and passed to each recursive step, until the base case occurs, causing the accumulator's final form to be returned directely, and i...
1
2016-09-16T23:19:30Z
[ "python", "recursion" ]
How to write a recursive function to print a string a certain number of times?
39,541,240
<p>I have been trying to write a python function which will receive two arguments: <code>x</code> which is the number of times to repeat and <code>y</code> which is the number or string to be repeated.</p> <p>So far this is what I have been able to come up with, but I can't seem to be able to determine how to do it re...
0
2016-09-16T23:10:24Z
39,541,319
<pre><code>def recurse(x, y): final = [] if times == 0: </code></pre> <p>You can't just reference "times" as if it's some kind of magic floaty variable available anywhere and everywhere. The first time in here, <code>times</code> will have no value. And the next time through, you're hoping you can just pick th...
0
2016-09-16T23:19:47Z
[ "python", "recursion" ]
Unable to successfully call a class string in a for loop
39,541,260
<p>I have a class</p> <pre><code>class zero: top = " __ " mid = "| |" bot = "|__|" </code></pre> <p>And I want to use a loop to call the different sections. E.g.:</p> <pre><code>def printnum(list): chunks = ['top','mid','bot'] print section # prints "top" print zero.top # prints " __...
0
2016-09-16T23:12:42Z
39,541,340
<p>Your <code>zero</code> class doesn't have an attribute called <code>section</code>, what you can do instead is to use <code>getattr</code> which accepts a string (second argument) as the object property to get, like this:</p> <pre><code>class zero: top = " __ " mid = "| |" bot = "|__|" chunks = ['top','mid'...
1
2016-09-16T23:22:20Z
[ "python" ]
Take Unique of numpy array according to 2 column values.
39,541,276
<p>I have Numpy array in python with two columns as follows : </p> <pre><code>time,id 1,a 2,b 3,a 1,a 5,c 6,b 3,a </code></pre> <p>i want to take unique time of each user. For above data i want below output. </p> <pre><code>time,id 1,a 2,b 3,a 5,c 6,b </code></pre> <p>That is, I want to take only unique rows. so, ...
0
2016-09-16T23:14:19Z
39,541,480
<p>Given:</p> <pre><code>&gt;&gt;&gt; b [['1' 'a'] ['2' 'b'] ['3' 'a'] ['1' 'a'] ['5' 'c'] ['6' 'b'] ['3' 'a']] </code></pre> <p>You can do:</p> <pre><code>&gt;&gt;&gt; np.vstack({tuple(e) for e in b}) [['3' 'a'] ['1' 'a'] ['2' 'b'] ['6' 'b'] ['5' 'c']] </code></pre> <p>Since that is a set comprehension, ...
1
2016-09-16T23:45:41Z
[ "python", "arrays", "numpy" ]
Take Unique of numpy array according to 2 column values.
39,541,276
<p>I have Numpy array in python with two columns as follows : </p> <pre><code>time,id 1,a 2,b 3,a 1,a 5,c 6,b 3,a </code></pre> <p>i want to take unique time of each user. For above data i want below output. </p> <pre><code>time,id 1,a 2,b 3,a 5,c 6,b </code></pre> <p>That is, I want to take only unique rows. so, ...
0
2016-09-16T23:14:19Z
39,541,690
<p>If you go back to your original list format data and create a structured array, then determining the unique values is much easier.</p> <pre><code>a = [['1', 'a'], ['2', 'b'], ['3', 'a'],['1', 'a'],['5', 'c'], ['6', 'b'], ['3', 'a']] tup = [tuple(i) for i in a] # you need a list of tuples, a kludge for now dt = [...
0
2016-09-17T00:23:32Z
[ "python", "arrays", "numpy" ]
Which kind of of data handling, internal or external, is commonly used?
39,541,277
<p>I'm writing a program in Python3.5 that reads a data set and does some stuff (it's DICOM data if you are familiar with it). It uses:</p> <ul> <li>Large arrays of size (512,512,141) or bigger.</li> <li>Alot of small metadata (many single data entries).</li> </ul> <p>Now my program has many different components that...
1
2016-09-16T23:14:34Z
39,542,069
<p>Seems like you're actually asking multiple questions here. Let me try to tease them apart:</p> <h3>Should I store all my data in-memory?</h3> <p>Can you? Do you have enough memory to do so comfortably? Then do it. Load it once and pass it around, or pass around some interface to the data, as necessary. How you int...
1
2016-09-17T01:35:12Z
[ "python", "external", "dicom", "internal", "datahandler" ]
No module named "xxx" in my project root folder
39,541,295
<p>My project is organized this way:</p> <pre><code>ezrename/ ├── base/ ├── Images/ └── shell </code></pre> <p>There are empties <strong>init</strong>.py files in ezrename, base and shell folders. Images is just a resource folder and don't have anything.</p> <p>I have a module named ezrename/base/c...
1
2016-09-16T23:16:05Z
39,541,353
<p>Python imports will work form the root of your project, so any imports in modules in subdirectories should import relative to that</p> <p>So if you're running from a main module in ezrename/ then the import in baseshell.py should be:</p> <p><code>from base import colors</code></p>
0
2016-09-16T23:25:01Z
[ "python", "python-3.x", "import" ]
No module named "xxx" in my project root folder
39,541,295
<p>My project is organized this way:</p> <pre><code>ezrename/ ├── base/ ├── Images/ └── shell </code></pre> <p>There are empties <strong>init</strong>.py files in ezrename, base and shell folders. Images is just a resource folder and don't have anything.</p> <p>I have a module named ezrename/base/c...
1
2016-09-16T23:16:05Z
39,541,400
<p>You can add ezrename/base to the python path and then just import Colors </p> <p>e.g. from ezrename/shell/baseshell.py</p> <pre><code>import os import sys shell_dir = os.path.dirname(os.path.realpath(__file__)) ezrename_dir = os.path.dirname(shell_dir) base_dir = os.path.join(ezrename_dir, "base") sys.path.append(...
0
2016-09-16T23:32:11Z
[ "python", "python-3.x", "import" ]
No module named "xxx" in my project root folder
39,541,295
<p>My project is organized this way:</p> <pre><code>ezrename/ ├── base/ ├── Images/ └── shell </code></pre> <p>There are empties <strong>init</strong>.py files in ezrename, base and shell folders. Images is just a resource folder and don't have anything.</p> <p>I have a module named ezrename/base/c...
1
2016-09-16T23:16:05Z
39,571,780
<p>By the pythonic way, I think my idea was wrong. You can't import from two modules as I wanted to because imports will only work if the module itself was not imported do what I wanted is not possible.</p> <p>The pythonic way would be create an application folder without an <strong>init</strong>.py file, import the p...
0
2016-09-19T11:11:07Z
[ "python", "python-3.x", "import" ]
How to do type verification in python?
39,541,393
<p>(Maybe b/c I'm from a C++ world) I want to verify some python variable is</p> <p><code>list(string)</code> or <code>list(dict(int, string))</code> or <code>SomethingIterable(string)</code></p> <p>Is there a simple and unified way to do it? (Instead of writing customized code to iterate and verify each instance..)<...
2
2016-09-16T23:31:35Z
39,541,428
<p>In Python lists can be composed of mixed types, there is no way to do something like setting the "type" of a list. Also, even if you could, this "type" is not enforced and could change at any time.</p>
4
2016-09-16T23:38:00Z
[ "python" ]
How to do type verification in python?
39,541,393
<p>(Maybe b/c I'm from a C++ world) I want to verify some python variable is</p> <p><code>list(string)</code> or <code>list(dict(int, string))</code> or <code>SomethingIterable(string)</code></p> <p>Is there a simple and unified way to do it? (Instead of writing customized code to iterate and verify each instance..)<...
2
2016-09-16T23:31:35Z
39,541,442
<p>Use the <a href="https://docs.python.org/3/library/typing.html" rel="nofollow">typing</a> module</p> <p>Typically: </p> <pre><code>from typing import List def method(value: List[str]): pass </code></pre>
-3
2016-09-16T23:40:24Z
[ "python" ]
How to do type verification in python?
39,541,393
<p>(Maybe b/c I'm from a C++ world) I want to verify some python variable is</p> <p><code>list(string)</code> or <code>list(dict(int, string))</code> or <code>SomethingIterable(string)</code></p> <p>Is there a simple and unified way to do it? (Instead of writing customized code to iterate and verify each instance..)<...
2
2016-09-16T23:31:35Z
39,541,470
<p>It seems that you are looking for an array (<a href="https://docs.python.org/3/library/array.html" rel="nofollow"><code>array.array</code></a>), not a list:</p> <pre><code>&gt;&gt;&gt; l = [1] &gt;&gt;&gt; l.append('a') &gt;&gt;&gt; import array &gt;&gt;&gt; a = array.array('l') &gt;&gt;&gt; a.append(3) &gt;&gt;&gt...
1
2016-09-16T23:44:56Z
[ "python" ]
Why am I getting the error: No module named 'email.MIMEMultipart'?
39,541,394
<p>I'm trying to experiment with simple code to send an email from a Python script. I keep getting an error that the module 'email.MIMEMultipart' does not exist. To simplify the question/answer process, I can narrow it down even further. From the Python environment prompt I can enter</p> <h1>>>>import email</h1> <h1>...
0
2016-09-16T23:31:36Z
39,541,559
<p>According to the examples in <a href="https://docs.python.org/3/library/email-examples.html" rel="nofollow">the documentation</a>, you need:</p> <pre><code>from email.mime.multipart import MIMEMultipar </code></pre>
0
2016-09-16T23:59:18Z
[ "python", "email", "module" ]
why does MaxAbsScaler() not set the column range to [-1,1]?
39,541,476
<p>From scikit learn documentation (<a href="http://scikit-learn.org/stable/modules/preprocessing.html" rel="nofollow">http://scikit-learn.org/stable/modules/preprocessing.html</a>), I understand that MaxAbsScaler works by dividing each column by its maximum value. This should set the maximum to be exactly one, i.e equ...
1
2016-09-16T23:45:33Z
39,557,133
<p>The missing part lies in the fact that the transformer finds the maximum of the absolute values of your dataframe. As a result, if the absolute value is a negative in your original dataframe, you notice the "inconsistency" you pointed. In other words, in your random dataframe, the maximum absolute values of your fir...
1
2016-09-18T11:26:13Z
[ "python", "scikit-learn" ]
strange result from timeit
39,541,528
<p>I tried to repeat the functionality of IPython %time, but for some strange reason, results of testing of some function are horrific.</p> <p>IPython:</p> <pre><code>In [11]: from random import shuffle ....: import numpy as np ....: def numpy_seq_el_rank(seq, el): ....: return sum(seq &lt; el) ....: ...
0
2016-09-16T23:54:07Z
39,541,639
<p>There could be any number of reasons this code is running slower in one implementation of python than another. One may be optimized differently than another, one may pre-compile certain parts while the other is fully interpreted. The only way to figure out why is to profile your code.</p> <p><a href="https://docs.p...
1
2016-09-17T00:11:59Z
[ "python", "debugging", "time", "ipython" ]
strange result from timeit
39,541,528
<p>I tried to repeat the functionality of IPython %time, but for some strange reason, results of testing of some function are horrific.</p> <p>IPython:</p> <pre><code>In [11]: from random import shuffle ....: import numpy as np ....: def numpy_seq_el_rank(seq, el): ....: return sum(seq &lt; el) ....: ...
0
2016-09-16T23:54:07Z
39,541,771
<p>Well, one issue is that you're misreading the results. <code>ipython</code> is telling you how long it took each of the 10,000 iterations for the set of 10,000 iterations with the lowest total time. The <code>timeit.repeat</code> module is reporting how long the whole round of 100 iterations took (again, for the sho...
3
2016-09-17T00:38:25Z
[ "python", "debugging", "time", "ipython" ]
Creating points subsets in django-models
39,541,554
<p>I am looking for a scalable way to create new user points subsets without migrating each time a new subset is created.</p> <p>For example, say I have a <code>users</code> app with a model where <code>total_points</code> is the sum of <code>pts_1</code>, <code>pts_2</code>, and <code>pts_3</code> for each user.</p> ...
0
2016-09-16T23:58:28Z
39,542,693
<p>The easiest solution would be to create a UserPoints model where you record the awarding of points.</p> <pre><code>class UserPoints(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) points_amount = models.IntegerField(default=1)...
0
2016-09-17T03:55:16Z
[ "python", "django", "django-models", "architecture", "scalability" ]
pyspark: convert RDD[DenseVector] to dataframe
39,541,568
<p>I have the following rdd:</p> <p>rdd.take(5) gives me:</p> <pre><code>[DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699]), DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699]), DenseVector([5.0, 20.0, 0.3444, 0.3295, 54.3122, 4.0, 4.0, 9.0]), DenseVector([9.2463...
0
2016-09-17T00:00:30Z
39,548,128
<p>Map to <code>tuples</code> first:</p> <pre><code>rdd.map(lambda x: (x, )).toDF(["features"]) </code></pre> <p>Just keep in mind that as of Spark 2.0 there are two different <code>Vector</code> implementation an <code>ml</code> algorithms require <code>pyspark.ml.Vector</code>.</p>
1
2016-09-17T14:48:37Z
[ "python", "pyspark", "spark-dataframe", "apache-spark-ml" ]
faster and more 'pythonic' list of dictionaries
39,541,577
<p>For simplicity, I've provided 2 lists in a list, but I'm actually dealing with a hundred of lists in a list, each containing a sizable amount of dictionaries. I only want to get the value of 'status' key in the 1st dictionary without checking any other dictionaries in that list (since I know they all contain the sam...
3
2016-09-17T00:02:13Z
39,541,622
<pre><code>from itertools import groupby result = groupby(sum(nested,[]), lambda x: x['status']) </code></pre> <p>How it works:</p> <p><code>sum(nested,[])</code> concatenates all your outer lists together into one big list of dictionaries</p> <p><code>groupby(, lambda x: x['status'])</code> groups all your obje...
2
2016-09-17T00:09:16Z
[ "python", "dictionary" ]
faster and more 'pythonic' list of dictionaries
39,541,577
<p>For simplicity, I've provided 2 lists in a list, but I'm actually dealing with a hundred of lists in a list, each containing a sizable amount of dictionaries. I only want to get the value of 'status' key in the 1st dictionary without checking any other dictionaries in that list (since I know they all contain the sam...
3
2016-09-17T00:02:13Z
39,541,667
<p>You could make a <code>defaultdict</code> for each nested list:</p> <pre><code>import collections nested = [ [{'id': 287, 'title': 'hungry badger', 'status': 'High'}, {'id': 437, 'title': 'roadtrip to Kansas','status': 'High'}], [{'id': 456, 'title': 'happy title here','status': 'Medium'}, {'id': 342,'title':...
2
2016-09-17T00:20:18Z
[ "python", "dictionary" ]
Use assert in normal code
39,541,590
<p>I'm writing a python function to validate a token from an email. In the email, there is a url with the endpoint of it. I have two url parameters, the token and email address. In my endpoint I have to check : </p> <ul> <li>if the parameters are in the URL</li> <li>if there is a associate token in the database</li> <...
0
2016-09-17T00:04:31Z
39,541,698
<p>No, using <code>assert</code> for control flow rather than debugging is poor practice, because assertions can be turned off. Just use an ordinary <code>if</code> statement.</p> <pre><code># pull from url email = request.GET['email'] value_token = request.GET['token'] # test if valid token = EmailValidationToken.obj...
5
2016-09-17T00:25:19Z
[ "python", "assert" ]
Setting default histtype in matplotlib?
39,541,655
<p>Is there a way to configure the default argument for <code>histtype</code> of matplotlib's <code>hist()</code> function? The default behavior is to make bar-chart type histograms, which I basically <em>never</em> want to look at, since it is horrible for comparing multiple distributions that have significant overlap...
2
2016-09-17T00:17:10Z
39,543,370
<p>Thank you for prompting me to look at this, as I much prefer <code>'step'</code> style histograms too! I solved this problem by going into the matplotlib source code. I use anaconda, so it was located in <code>anaconda/lib/site-packages/python2.7/matplotlib</code>.</p> <p>To change the histogram style I edited two ...
1
2016-09-17T06:01:26Z
[ "python", "matplotlib", "data-analysis" ]
Calculate directory path in Python module distribution
39,541,678
<p>I have a Python module distribution (it's an egg) that contains some additional files &amp; directories that I would like to copy during my program's runtime. </p> <pre><code>├── mypkg │ ├── extra_files │ │ ├── layouts/ │ │ ├── scripts/ │ │ └── conf...
0
2016-09-17T00:22:21Z
39,682,573
<p>I was able to actually do this with <code>__file__</code>, which returns the pathname from which the module was first loaded. I can get the full path to my static directory like this:</p> <pre><code>import os directory = os.path.join(os.path.dirname(__file__), 'templates/index.html') </code></pre>
0
2016-09-25T01:28:59Z
[ "python", "module", "pkg-resources" ]
basic understanding of simple socket server
39,541,706
<p>I am new to socket programming and am trying to understand how sockets work. Presently I am trying to play with python socket library to see how it works. </p> <p>Now there are a few things that I am not able to wrap my head around. Let's take an example as shown <a href="http://www.bogotobogo.com/python/python_ne...
1
2016-09-17T00:27:01Z
39,541,752
<blockquote> <p>Now what happens when another client also connects to this server? Does the conn and addr variables get overwritten with the new values? Or how is it handled?</p> </blockquote> <p>In your example, nothing interesting will happen. The attempt to connect will hang. Each client call to <code>connect()</...
0
2016-09-17T00:35:14Z
[ "python", "sockets", "networking", "tcp-ip" ]
basic understanding of simple socket server
39,541,706
<p>I am new to socket programming and am trying to understand how sockets work. Presently I am trying to play with python socket library to see how it works. </p> <p>Now there are a few things that I am not able to wrap my head around. Let's take an example as shown <a href="http://www.bogotobogo.com/python/python_ne...
1
2016-09-17T00:27:01Z
39,546,051
<blockquote> <blockquote> <p>Now what happens when another client also connects to this server? Does the conn and addr variables get overwritten with the new values? Or how is it handled?</p> </blockquote> </blockquote> <p>As pointed out by Rob in another answer, your code will accept only one client. The <cod...
0
2016-09-17T11:03:24Z
[ "python", "sockets", "networking", "tcp-ip" ]
Django: "cannot import name import_string" while using "rest_framework_docs"
39,541,722
<p>I installed <code>drfdocs</code> by following the steps as mentioned <a href="http://drfdocs.com/installation/" rel="nofollow">here</a>. But I am getting <code>cannot import name import_string</code>.</p> <p>Below is the stacktrace:</p> <pre><code>ImportError at / cannot import name import_string Request Method: G...
0
2016-09-17T00:31:35Z
39,542,379
<p>It was due to the conflict in the version of <code>drfdocs</code> with <code>django-rest-framework</code>. Downgrading my version from <code>drfdocs==0.0.11</code> to <code>drfdocs==0.0.6</code> fixed the issue.</p>
0
2016-09-17T02:40:31Z
[ "python", "django", "python-2.7", "django-rest-framework", "django-1.6" ]
Do all models in Django basically have init constructors that assign to object variables
39,541,728
<p>Suppose I have something like this</p> <pre><code>class Album(models.Model): artist = models.CharField(max_length=128, unique=True) title = models.CharField(max_length=128, unique=True) </code></pre> <p>Now I can do this</p> <pre><code>inst = Album(artist="Shania Twain",title="blah") </code></pre> <p>Sin...
0
2016-09-17T00:31:58Z
39,541,748
<p>Yes it has, but is not recommend to override it.</p> <p>You can do it like this. But It's not recommended.</p> <pre><code> def __init__(self, name, email, password, *args, **kwargs): super(models.Model, self).__init__(*args, **kwargs) self.name = name self.email = email # or what...
1
2016-09-17T00:34:53Z
[ "python", "django" ]
Why isn't my Model Query set working properly?
39,541,791
<p>I'm building a Q&amp;A style community with categories containing forums which contain Topics and each topic has posts. On the landing page, I want popular Topics across all categories and when inside a category, I want all popular Topics within that category. I've defined template filters to do this but they aren't...
0
2016-09-17T00:41:12Z
39,542,079
<p>I'm not sure what exactly the issue was but I kinda got it to work by changing the template filters to do just on queryset each and using more for loops in my templates while calling the filters. I guess filters have some constraints in this area. I'll try finding more specific points that will clarify this issue an...
0
2016-09-17T01:36:27Z
[ "python", "django", "django-models", "django-templates", "django-template-filters" ]
opening and manipulating text files with python
39,541,809
<p>So I've done a lot of browsing, but I cant seem to open my text file so I can begin to manipulate it. </p> <p>I saved my program in with the same file: and my first line returns no errors:</p> <pre><code>fpath= r'/Users/veggiepunk1363/Desktop/geoproccessing/file_list.txt' with open(fpath) as f_in: dates= f_in...
0
2016-09-17T00:43:15Z
39,541,882
<p>You need not use a context manager. This is much simpler and does not require you to explicitly close the file descriptor:</p> <pre><code>for file_name in open(fpath).readlines(): print file_name # 3B43.20000101.7.tif... </code></pre>
-1
2016-09-17T00:56:16Z
[ "python", "file", "text" ]
opening and manipulating text files with python
39,541,809
<p>So I've done a lot of browsing, but I cant seem to open my text file so I can begin to manipulate it. </p> <p>I saved my program in with the same file: and my first line returns no errors:</p> <pre><code>fpath= r'/Users/veggiepunk1363/Desktop/geoproccessing/file_list.txt' with open(fpath) as f_in: dates= f_in...
0
2016-09-17T00:43:15Z
39,542,595
<p>Try this way. "veggiepunk1363" is not the name of your hard drive is the folder in which your User files resides on Windows.</p> <pre><code>fpath= r'/Users/veggiepunk1363/Desktop/geoproccessing/file_list.txt' with open(fpath, 'r') as f_in: #opens the file with read mode dates = f_in.readlines() #returns a l...
-2
2016-09-17T03:33:53Z
[ "python", "file", "text" ]
Plotting a histogram
39,541,811
<p>I am trying to plot a histogram with mu and sigma. </p> <p>Im trying to use the ec_scores values on the y axis, its supposed to show me 0.1 to 1.0 It gives me 1, 2, 3, 4, 5, 6 on the y axis instead. Im not getting any errors but this is throwing off the graph completely. Please assist me and tell me what I am doin...
2
2016-09-17T00:43:48Z
39,727,268
<p>As mentioned by @benton in the comments, you can plot the ec_scores as a <a href="http://matplotlib.org/examples/api/barchart_demo.html" rel="nofollow">barchart</a>:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) ec_scores = np.arr...
0
2016-09-27T14:23:53Z
[ "python", "matplotlib", "graph", "histogram" ]
Best way to add a form to multiple pages?
39,541,891
<p>I'm working on a project, that has a bunch of views with corresponding templates and forms. Every template contains a link to a login page (inherits it from the main template):</p> <pre><code>&lt;ul class="options"&gt; ... &lt;li id="login"&gt; &lt;a class="button" href="{% url 'forum:login' %}?next={{ request.p...
0
2016-09-17T00:58:26Z
39,541,990
<p>you can put your form in it's own template loginform.html and then use "include" where you want it with:</p> <pre><code>{% include './path-to/loginform.html' %} </code></pre> <p>edit: This is also a great way to handle things like your css and javascript areas, nav-menu, etc. <a href="https://docs.djangoproject.co...
2
2016-09-17T01:19:31Z
[ "jquery", "python", "ajax", "django" ]
Convert Cocoa timestamp in Python
39,541,908
<p>I have a Cocoa timestamp (zero time of January 1st, 2001 00:00:00 UTC) that I need to convert in Python. When I use the following code it assumes a Unix timestamp input. Besides adding 31 years in seconds (Just under a billion seconds...) what's the best way to convert the time?</p> <pre><code>import datetime pri...
1
2016-09-17T01:01:03Z
39,542,440
<p>Would something like this work for you:</p> <pre><code>from datetime import datetime unix = datetime(1970, 1, 1) # UTC cocoa = datetime(2001, 1, 1) # UTC delta = cocoa - unix # timedelta instance timestamp = datetime.fromtimestamp(int("495759456")) + delta print(timestamp.strftime('%Y-%m-%d %H:%M:%S')) </cod...
1
2016-09-17T02:56:45Z
[ "python", "cocoa", "timestamp" ]
Extract netcdf4 variable slice by dimension name
39,541,950
<p>I have a netCDF file with 4 dimensions. I want to extract a slice from the netCDF file by giving the name of one of the dimensions </p> <p>I know how to do this by position. E.g.</p> <pre><code>from netCDF4 import Dataset hndl_nc = Dataset(path_to_nc) # Access by slice hndl_nc.variables['name_variable'][:,5,:,:] ...
0
2016-09-17T01:09:25Z
39,548,112
<p>You can use <a href="http://xarray.pydata.org/en/stable/indexing.html#indexing-with-labeled-dimensions" rel="nofollow">xarray</a>'s indexing capabilities to access netcdf data by dimension name. </p> <pre><code>import xarray as xr ds = xr.open_dataset('./foo.nc') var = ds['name_variable'] # Slice var by Dimension "...
1
2016-09-17T14:47:25Z
[ "python", "netcdf" ]
Python: Performing Mathematical Functions between IP Address Octets
39,541,973
<p>I'm trying to perform the following:</p> <pre><code>firstoctet * 256 + secondoctet = * 256 + thirdoctet = * 256 + fourthoctet = x </code></pre> <p>When I use this as an example :</p> <pre><code>64.233.187.99 (google.com) 64 * 256 + 233 = * 256 + 187 = * 256 + 99 = http://1089059683/ </code></pre> <p>Can someone ...
0
2016-09-17T01:14:42Z
39,542,090
<p>Convert an IP address string to a list of integers like this:</p> <pre><code>ip_as_string = "64.233.187.99" ip_as_ints = [int(a) for a in ip_as_string.split('.')] </code></pre> <p><code>ip_as_ints</code> will be [64, 233, 187, 99].</p> <p>I will guess that the mathematical expression that you intend to perform is...
0
2016-09-17T01:39:17Z
[ "python", "python-2.7", "python-3.x" ]
Python: Performing Mathematical Functions between IP Address Octets
39,541,973
<p>I'm trying to perform the following:</p> <pre><code>firstoctet * 256 + secondoctet = * 256 + thirdoctet = * 256 + fourthoctet = x </code></pre> <p>When I use this as an example :</p> <pre><code>64.233.187.99 (google.com) 64 * 256 + 233 = * 256 + 187 = * 256 + 99 = http://1089059683/ </code></pre> <p>Can someone ...
0
2016-09-17T01:14:42Z
39,542,125
<p>If you're on Python 3.3 or higher, you can leverage <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow">the <code>ipaddress</code> module</a> to avoid reinventing the wheel, and it even provides a useful view as <code>bytes</code> that <code>int.from_bytes</code> can efficiently convert to a re...
1
2016-09-17T01:46:45Z
[ "python", "python-2.7", "python-3.x" ]
Why does an empty list become NoneType on return?
39,541,976
<p>I'm working on some path finding algorithms, and the snippet below is supposed to make an array of nodes in the path from the goal to the start. It works fine when there is a path from the goal to the start. But when there is no path from start to goal, the while loop never runs, and result gets returned as <code>[]...
1
2016-09-17T01:15:10Z
39,542,018
<p>That's not what is happening. The problem is that on <code>line 46</code> you assign start_path the result of calling reverse() on the list that <code>path()</code> returns. That's OK, but since <code>[].reverse()</code> always returns <code>None</code>, I'm certain it's not what you intended.</p> <p>What I think ...
3
2016-09-17T01:24:28Z
[ "python", "list", "python-2.7", "return", "nonetype" ]
Why does an empty list become NoneType on return?
39,541,976
<p>I'm working on some path finding algorithms, and the snippet below is supposed to make an array of nodes in the path from the goal to the start. It works fine when there is a path from the goal to the start. But when there is no path from start to goal, the while loop never runs, and result gets returned as <code>[]...
1
2016-09-17T01:15:10Z
39,542,019
<p>Because reverse is an inplace operation with a None return type. </p> <pre><code>x = [1, 2] print(x) [1, 2] a = x.reverse() print(a) None print(x) [2, 1] </code></pre> <p>Don't assign <code>start_path</code> to the result of reverse. Assign it to start_path = path(center, pathBack_start) and then call start_path....
1
2016-09-17T01:24:28Z
[ "python", "list", "python-2.7", "return", "nonetype" ]
Why does an empty list become NoneType on return?
39,541,976
<p>I'm working on some path finding algorithms, and the snippet below is supposed to make an array of nodes in the path from the goal to the start. It works fine when there is a path from the goal to the start. But when there is no path from start to goal, the while loop never runs, and result gets returned as <code>[]...
1
2016-09-17T01:15:10Z
39,542,021
<p><code>[].reverse()</code> returns <code>None</code>, you should not assign the return value, because it modifies the list in-place.</p> <p>See below:</p> <pre><code>Python 2.7.11 (default, Dec 5 2015, 14:44:53) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.1.76)] on darwin Type "help", "copyright", "credits"...
0
2016-09-17T01:24:38Z
[ "python", "list", "python-2.7", "return", "nonetype" ]
Scipy's RectBivariateSpline returns wrong value?
39,541,991
<p>Trying to interpolate data from a regular input grid, and came across this in the documentation for <code>scipy.interpolate.interp2d</code>:</p> <blockquote> <p>See also RectBivariateSpline Much faster 2D interpolation if your input data is on a grid</p> </blockquote> <p>So I tried using <code>scipy.interpolat...
1
2016-09-17T01:19:35Z
39,541,992
<p>Right, just before submitting this I thought I should try calling <code>bivar_fun(y, x)</code> instead of <code>bivar_fun(x, y)</code> and things suddenly work:</p> <pre><code>data[250, 60] # 76.1451873779 interp_fun(60, 250) # 76.14518738 bivar_fun(250, 60, grid=False) # [ 76.14518738] </code></pre> <p>Still n...
1
2016-09-17T01:19:35Z
[ "python", "numpy", "scipy" ]
what does socket.connect() do internally?
39,542,026
<p>So I am trying to understand networking in general and especially sockets at this point in time. I am using the Python socket library to play with things. </p> <p>I came across many examples on the internet that demonstrate TCP and UDP sockets via simple ECHO servers as examples. </p> <p>For the TCP counterparts t...
2
2016-09-17T01:25:21Z
39,542,109
<blockquote> <p>Please help me understand what does it actually mean to say connection oriented implementation wise?</p> </blockquote> <p>It means that the TCP protocol relies on an open connection to work. In other words, there <em>must</em> be an open connection through which the packages of a message sent via soc...
1
2016-09-17T01:42:48Z
[ "python", "sockets", "tcp", "udp" ]
Adding returned tuples to a list of lists
39,542,060
<p>I am trying to add the returned tuples to a list of lists or list of arrays.</p> <pre><code> dim = 10 for key, figure in sorted(problem.figures.iteritems(), reverse=True): dim -= 1 # print key, dim (img_arr[dim], images[dim]) = vectorize(figure) </code></pre> <p>The function returns...
1
2016-09-17T01:33:11Z
39,542,210
<pre><code>img_arr[dim], images[dim] = vectorize(figure) </code></pre>
0
2016-09-17T02:01:36Z
[ "python", "list" ]
Adding returned tuples to a list of lists
39,542,060
<p>I am trying to add the returned tuples to a list of lists or list of arrays.</p> <pre><code> dim = 10 for key, figure in sorted(problem.figures.iteritems(), reverse=True): dim -= 1 # print key, dim (img_arr[dim], images[dim]) = vectorize(figure) </code></pre> <p>The function returns...
1
2016-09-17T01:33:11Z
39,543,274
<p>Try using <code>append()</code> attribute of list like this:</p> <pre><code>img_arr, images = [],[] # assuming you already declared the list for key, figure in sorted(problem.figures.iteritems(), reverse=True): tup = vectorize(figure) img_arr.append(tup[0]) images.append(tup[1]) </code></pre> <bloc...
0
2016-09-17T05:44:43Z
[ "python", "list" ]
Pillow does not seem to work inside a function, but works fine on interpreter
39,542,061
<p>The function below, part of a bigger class works fine on all the images except this one -> <a href="http://www.worldbank.org/content/dam/wbr/About/Pres/jyk-hs-offical.png" rel="nofollow">http://www.worldbank.org/content/dam/wbr/About/Pres/jyk-hs-offical.png</a></p> <pre><code>def _fetch_image_size(self, image_url):...
0
2016-09-17T01:33:22Z
39,551,025
<p>sorry to bother you all. it appears that i need to sanitize my url in my class and look for blankspaces. Nothing wrong with PIL here.</p> <p>here is how i pin pointed the faulty code, if anybody is interested.</p> <p>thankyou for your response. I have diagnosed the problem. pasting the problematic code from my cla...
0
2016-09-17T19:44:45Z
[ "python", "pillow" ]
Intermittent "ORA-01458: invalid length inside variable character string" error when inserting data into Oracle DB using SQLAlchemy
39,542,204
<p>I am working on a Python 3.5 server project and using SQLAlchemy 1.0.12 with cx_Oracle 5.2.1 to insert data into Oracle 11g. I noticed that many of my multi-row table insertions are failing intermittently with "ORA-01458: invalid length inside variable character string" error. </p> <p>I generally insert a few thous...
1
2016-09-17T01:59:49Z
39,668,650
<p>We found out that if we replace all the float.nan objects with None before we do the insertion the error disappears completely. Very weird indeed!</p>
0
2016-09-23T19:59:05Z
[ "python", "oracle", "oracle11g", "sqlalchemy", "cx-oracle" ]
Why isn't this element visible (Selenium + Python/Django 1.9)
39,542,380
<p>I am using webdriver to fill out a form in Django. The first field, name, is found and filled out. But the second field is somehow not being found. Here's the script I'm using...</p> <pre><code>name = browser.find_element_by_id("name") value = browser.find_element_by_id("value") submit = browser.find_element_by_...
2
2016-09-17T02:40:43Z
39,542,433
<p>In my experience, <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains" rel="nofollow"><code>ActionChains</code></a> are often the answer when I have an issue like this in selenium. It is worth a try in this case:</p> <pre><code>from selenium.webdriver.common.action...
1
2016-09-17T02:54:26Z
[ "python", "django", "selenium", "webdriver" ]
Kivy Update Widget
39,542,463
<p>I read in a text file called data.txt containing the usernames and passwords. The format of the text file is:</p> <p>username1<br> password1<br> username2<br> password2<br> username3<br> username3<br> etc.</p> <p>I read in the usernames and make a corresponding button for each username. When I first start the prog...
0
2016-09-17T03:01:32Z
39,544,988
<p>Either you can define a function which adds the appropriate widgets to the layout or you can "clean" the layout and read every user from the database again. If you have many users this might take a while.</p> <p>To add users via a function:</p> <pre><code>class MainWindow(Screen): def __init__(self,**kwargs):...
0
2016-09-17T09:09:05Z
[ "python", "kivy" ]
Backend architecture for SaaS product in django
39,542,509
<p>I'm writing the backend for a SaaS application in django. Need some guidance on the architecture. So the product will have 2 offerings: a general one where all users will share the same database and a premium one with a dedicated database. How I'm planning to translate this to django is the following:</p> <ul> <li...
0
2016-09-17T03:13:03Z
39,542,583
<p>If the functionality of the free and premium offerings will be exactly the same you shouldn't need any code duplication. This is of course a big IF, because it's very conceivable that you'll add extra features to the premium offering.</p> <p>If the functionality will be exactly the same then all you need to do is a...
0
2016-09-17T03:31:27Z
[ "python", "django", "saas" ]
Run Kivy app as root user with touch screen on raspberry pi
39,542,539
<p>I want to make a kivy app for the raspberry pi that can use a touch screen. I was able to get the demos to work with the touchscreen with just "python ~/kivy/examples/demo/showcase/main.py". The issue comes when I need to start the app with "sudo python main.py", the touchscreen then ceases to work. </p> <p>The app...
0
2016-09-17T03:22:23Z
39,542,558
<p>Well apparently I didn't look hard enough. The solution is to copy "~/.kivy/config.ini" to "/root/.kivy/config.ini"</p> <p>So the commands are </p> <p>"sudo cp ~/.kivy/config.ini /root/.kivy/config.ini"</p> <p>And then everything works happily together! </p>
0
2016-09-17T03:26:26Z
[ "python", "raspberry-pi", "kivy", "led" ]
Programatically changing docstring of a class object
39,542,552
<p>I have a function and class decorator that changes them to singletons but the docstrings are kind of dropped. Transforming function returns a class object that has its own docstring which should be overwritten. How can I work around this?</p> <pre><code>def singleton(cls): return cls() def singletonfunction(fu...
3
2016-09-17T03:25:11Z
39,542,655
<p>Lets assume the original version is something like this:</p> <pre><code>class BitsInteger: """BitsInteger docstring""" def __init__(self, num): pass def singleton(cls): return cls() def singletonfunction(func): return func() @singletonfunction def Bit(): """A 1-bit BitField; must be e...
1
2016-09-17T03:48:00Z
[ "python", "decorator", "python-decorators", "docstring" ]
Selenium Auto Submits Form with Send_keys?
39,542,586
<p>I'm using Selenium 2.53 with python 3.4 firefox 47 to do automation testing. When using .send_keys (sendKeys in Java) it will auto submit the form when I dont want it to.</p> <p>The form input that I'm sending keys to is:</p> <pre><code>&lt;input tabindex="1" type="text" name="PostingTitle" ...
1
2016-09-17T03:32:06Z
39,543,218
<blockquote> <p>When using .send_keys (sendKeys in Java) it will auto submit the form when I dont want it to.</p> </blockquote> <p>It might be possible your desired text box is capturing key events during sendKeys which may be call any JavaScript function to submit the form, because <code>sendKeys</code> working nor...
1
2016-09-17T05:35:39Z
[ "python", "selenium", "selenium-webdriver" ]
While statement and expressions
39,542,616
<p><code>while</code> loop statement gets executed as long as the expression is true. </p> <p>After the 10th time, the pop() throws an IndexError back because there are 10 elements in the list. But, the below code executes fine without any error. Why is it so?</p> <pre><code>a = [x*x for x in range(10)] while a.pop()...
1
2016-09-17T03:37:59Z
39,542,668
<p>It is unclear what your issue is. If I execute your code, it does (what I think) you expect. It is likely the <code>0</code> that is causing unexpected behavior:</p> <pre><code>&gt;&gt;&gt; a = [x*x for x in range(10)] &gt;&gt;&gt; while a.pop(): ... print a ... [0, 1, 4, 9, 16, 25, 36, 49, 64] [0, 1, 4, 9, 16,...
2
2016-09-17T03:49:31Z
[ "python", "while-loop" ]
While statement and expressions
39,542,616
<p><code>while</code> loop statement gets executed as long as the expression is true. </p> <p>After the 10th time, the pop() throws an IndexError back because there are 10 elements in the list. But, the below code executes fine without any error. Why is it so?</p> <pre><code>a = [x*x for x in range(10)] while a.pop()...
1
2016-09-17T03:37:59Z
39,542,686
<blockquote> <p>After the 10th time, the pop() throws an IndexError back because there are 10 elements in the list.</p> </blockquote> <p>No, the code never tries to do any <code>pop</code>s after the 10th, because the 10th <code>pop</code> returns <code>0</code>. <code>0</code> is considered false in a boolean conte...
3
2016-09-17T03:53:53Z
[ "python", "while-loop" ]
Python os.walk() method
39,542,635
<p>I am new to stackoverflow. I have taken lot of help from this forum in writing the following code. The code below searches all directories/sub directories on the system drives but while looking into 'D' drive, it looks only those directories and sub directories that are after the folder in which i run this program. ...
1
2016-09-17T03:42:45Z
39,543,046
<p>In Windows <a href="http://superuser.com/questions/135214/using-cd-command-in-windows-command-line-cant-navigate-to-d">each process may set a current working directory on each <em>drive</em> separately</a>. <code>D:</code> means the <em>current working directory</em> on drive D. Here the behaviour occurs, because on...
2
2016-09-17T05:09:03Z
[ "python" ]
Reshaping pandas dataframe: New row for every 76 entries
39,542,642
<p>I'm new to Python and Pandas and am playing around with a heart disease data set via UCI. <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data" rel="nofollow">https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data</a></p> <p>There are 76 att...
1
2016-09-17T03:44:28Z
39,544,990
<p>As <a href="http://stackoverflow.com/questions/39542642/reshaping-pandas-dataframe-new-row-for-every-76-entries#comment66400235_39542642">@Boud has already said</a> it's much easier to pre-process your data instead of massaging "incorrectly built" DF:</p> <pre><code>import io import requests import pandas as pd ur...
1
2016-09-17T09:09:15Z
[ "python", "pandas" ]
Error displaying a matplotlib in ipython notebook
39,542,703
<p>I'm going though a ipython notebook tutorial and it says to run this in a cell. import numpy as np import math import matplotlib.pyplot as plt</p> <pre><code>x = np.linspace(0, 2*math.pi) plt.plot(x, np.sin(x), label=r'$\sin(x)$') plt.plot(x, np.cos(x), 'ro', label=r'$\cos(x)$') plt.title(r'Two plots...
0
2016-09-17T03:56:26Z
39,543,637
<p>Try to add this statement earlier in your notebook, which indicates to matplotlib where to render the plot (i.e. as an html element embedded in the notebook):</p> <p><code> %matplotlib inline </code></p> <p>The story behind that is simply that matplotlib is old enough to be existing since before jupyter and ipytho...
1
2016-09-17T06:37:43Z
[ "python", "matplotlib", "ipython" ]
DFS path finding with obstacles
39,542,810
<p>I have the following grid and i'm trying to get to the 1's in that grid, the obstacle is shown by 2. The robot has prioritized movement in this order: up, right, down, left. The starting position has a * next to it.</p> <pre><code> 0 0* 0 0 2 0 1 1 0 </code></pre> <p>What i have done so far is to put ...
-1
2016-09-17T04:19:13Z
39,543,291
<p>Try this:</p> <pre><code>def dfs2(grid,pos,curr,height,width): x = pos[0] y = pos[1] if grid[x][y]==1: print str(curr) return None elif grid[x][y] ==2: return None last = curr[-1] if x-1 &gt;= 0 and last != 'DOWN': curr.append('UP') ...
0
2016-09-17T05:47:41Z
[ "python", "artificial-intelligence", "depth-first-search" ]
Returning a real-valued, phase-scrambled timeseries using Python
39,543,002
<p>I'm trying to implement "phase scrambling" of a timeseries in Python using Scipy/Numpy. Briefly, I'd like to:</p> <ol> <li>Take a timeseries.</li> <li>Measure the power and phase in the frequency domain using FFT.</li> <li>Scramble the existing phase, randomly reassigning phase to frequency.</li> <li>Return a real...
2
2016-09-17T04:58:25Z
39,543,314
<p><strong>A property of Fourier transform</strong>: a real valued time domain signal has a conjugate symmetric frequency domain signal. See <a href="https://en.wikipedia.org/wiki/Fourier_transform#Functional_relationships" rel="nofollow">110 of Functional relationships of Fourier transform</a>.</p> <h1>Solution (may ...
1
2016-09-17T05:51:28Z
[ "python", "numpy", "scipy", "signal-processing", "ifft" ]
Returning a real-valued, phase-scrambled timeseries using Python
39,543,002
<p>I'm trying to implement "phase scrambling" of a timeseries in Python using Scipy/Numpy. Briefly, I'd like to:</p> <ol> <li>Take a timeseries.</li> <li>Measure the power and phase in the frequency domain using FFT.</li> <li>Scramble the existing phase, randomly reassigning phase to frequency.</li> <li>Return a real...
2
2016-09-17T04:58:25Z
39,544,572
<p>Scipy has <code>rfft</code> and <code>irfft</code> routines to do Fourier transforms of real signals (the <code>r</code> is for real). The function below returns a properly scrambled signal. I should note that the routine as written will only work for even length signals, but fixing it for odd length signals shouldn...
1
2016-09-17T08:19:59Z
[ "python", "numpy", "scipy", "signal-processing", "ifft" ]
How can I code a sample of random numbers from a list, so that each number generated follows some condition depending on the preceding number?
39,543,027
<p>Example: If the first number in the sample is 1, then the next number can only be 2, 4 or 5, and if the second number is 2, then the next number can only be 1, 3, 4, 5 or 6. This continues for all the numbers in the list.</p> <p>I tried using this:</p> <pre><code>import random num_list = [1,2,3,4,5,6,7,8,9] new_s...
-1
2016-09-17T05:04:36Z
39,543,777
<p>I think this will work (in Python 3): </p> <pre><code>import random x_arr=[] y_arr=[] def addTolist(m,n): x_arr.append(m) y_arr.append(n) grid = [[1,2,3],[4,5,6],[7,8,9]] new_sample = random.sample(range(1,10), 5) # to generate random list of 5 numbers current = random.choice(new_sample) # take r...
0
2016-09-17T06:54:39Z
[ "python" ]
How can I know in Python how many times a line of code is executed per minute?
39,543,081
<p>For example if I have: </p> <pre><code> something=something+1 </code></pre> <p>I want to know how many times in a minute, this line is executed in order to create another variable with this result? </p>
0
2016-09-17T05:13:52Z
39,543,135
<p>I suppose you are trying to do some basic benchmarking, in this case it would go like this:</p> <pre><code>import time start = int(round(time.time() * 1000)) something = 0 while something &lt; 1000000: something = something + 1 delta = int(round(time.time() * 1000)) - start print "loop ran 1000000 times in ...
0
2016-09-17T05:24:26Z
[ "python", "loops", "time" ]
How can I know in Python how many times a line of code is executed per minute?
39,543,081
<p>For example if I have: </p> <pre><code> something=something+1 </code></pre> <p>I want to know how many times in a minute, this line is executed in order to create another variable with this result? </p>
0
2016-09-17T05:13:52Z
39,543,324
<p>If you are willing to wait a full minute (which usually is not the case) you could do something like</p> <pre><code>import time start = time.time() operationsPerMinute = 0 while (time.time() - start &lt; 60): operationsPerMinute = operationsPerMinute + 1 print(operationsPerMinute) </code></pre> <p>In which ...
0
2016-09-17T05:53:01Z
[ "python", "loops", "time" ]
How can I know in Python how many times a line of code is executed per minute?
39,543,081
<p>For example if I have: </p> <pre><code> something=something+1 </code></pre> <p>I want to know how many times in a minute, this line is executed in order to create another variable with this result? </p>
0
2016-09-17T05:13:52Z
39,543,813
<p>For benchmarking you would probably ask for per second timings.</p> <p>To count events in the last minute, here is a class remembering event timestamps for a given period:</p> <pre><code>import bisect import time class TimedCounter: def __init__(self, period=60.0): self._timestamps = [] self._...
0
2016-09-17T06:58:30Z
[ "python", "loops", "time" ]
PyCharm not detecting interpreter
39,543,093
<p>I am trying to code something in PyCharm (by JetBrains), and it is asking for an interpreter, however, there are no interpreters on the list. I am running 64-bit windows with 64-bit python installed. How can I fix this?</p>
0
2016-09-17T05:16:31Z
39,543,333
<p>Open PyCharm, Open Settings, Go To "Project: YourProjectName" -> Project Interpreter, click the Gear right to the Project Interpreter Field, Click "Add Local", search for your python.exe and click OK.</p>
0
2016-09-17T05:54:47Z
[ "python", "pycharm", "interpreter" ]
Big Binary Code into File in Python
39,543,117
<p>I have been working on a program and I have been trying to convert a big binary file (As a string) and pack it into a file. I have tried for days to make such thing possible. Here is the code I had written to pack the large binary string. </p> <pre><code>binaryRecieved="11001010101....(Shortened)" f=open(fileName,'...
0
2016-09-17T05:21:55Z
39,543,228
<p>In <code>struct.pack</code> you have used 'i' which represents an integer number, which is limited. As your code states, you have a long output; thus, you may want to use 'd' in stead of 'i', to pack your data up as double. It should work. <br /> <br /> See <a href="https://docs.python.org/2/library/struct.html" rel...
0
2016-09-17T05:37:18Z
[ "python", "file", "binary" ]
Big Binary Code into File in Python
39,543,117
<p>I have been working on a program and I have been trying to convert a big binary file (As a string) and pack it into a file. I have tried for days to make such thing possible. Here is the code I had written to pack the large binary string. </p> <pre><code>binaryRecieved="11001010101....(Shortened)" f=open(fileName,'...
0
2016-09-17T05:21:55Z
39,543,388
<p>Convert your bit string to a byte string: see for example this question <a href="http://stackoverflow.com/questions/28370991/converting-bits-to-bytes-in-python">Converting bits to bytes in Python</a>. Then pack the bytes with <code>struct.pack('c', bytestring)</code></p>
1
2016-09-17T06:05:03Z
[ "python", "file", "binary" ]
Big Binary Code into File in Python
39,543,117
<p>I have been working on a program and I have been trying to convert a big binary file (As a string) and pack it into a file. I have tried for days to make such thing possible. Here is the code I had written to pack the large binary string. </p> <pre><code>binaryRecieved="11001010101....(Shortened)" f=open(fileName,'...
0
2016-09-17T05:21:55Z
39,543,990
<p>For encoding m in big-endian order (like "ten" being written as "10" in normal decimal use) use:</p> <pre><code>def as_big_endian_bytes(i): out=bytearray() while i: out.append(i&amp;0xff) i=i&gt;&gt;8 out.reverse() return out </code></pre> <p>For encoding <code>m</code> in little-en...
1
2016-09-17T07:16:56Z
[ "python", "file", "binary" ]
pyplot and python. saving multiple graphs
39,543,196
<p>Well, we were recently given a project to make a natural selection simulator that tracks down the frequency of alleles through generations given particular particular viability of each allele pair. I made a program in python to print the graphs and it's working quite fine.</p> <p>Here it is.</p> <pre><code>#!/usr/...
0
2016-09-17T05:33:04Z
39,554,241
<p>I may not be fully sure what you are trying, and it might have been a good idea to change user inputs against fixed values in your program, since nobody knows the vaules for your input parameters.</p> <p>Nevertheless I think your error is related to not initializing genp and genq properly for each loop cycle.</p> ...
0
2016-09-18T04:52:40Z
[ "python", "matplotlib", "graph" ]
Apply shift for comparison on multiple columns over groupby pandas
39,543,230
<p>I have a dataframe(raw_data) containing multiple columns:</p> <pre><code>raw_data = {'one': ['A', 'B', 'A', 'C', 'B', 'B', 'A', 'C', 'A', 'B', 'C', 'B'],'two' : [3,4,5,6,2,7,9,12,1,10,11,8],'three': ['bcd','qpv', 'cba','klm','zfv','klm','abc','abc','abc','lmf','fly','zdb'],'four':['cba','klm','tcf','fly','zfb','zdb...
0
2016-09-17T05:38:08Z
39,544,657
<p>You could perform those steps as follows:</p> <pre><code># Groupby column one and sort values by column two df_grouped = df.groupby('one').apply(lambda x: x.sort_values('two')) # Shift by one level up and compare comparison_1 = df_grouped['five']==df_grouped['five'].shift(-1) comparison_2 = df_grouped['four']==df...
0
2016-09-17T08:32:47Z
[ "python", "pandas", "lambda" ]