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
How to do calculation on pandas dataframe that require processing multiple rows?
39,919,672
<p>I have a dataframe from which I need to calculate a number of features from. The dataframe <code>df</code> looks something like this for a object and an event:</p> <pre><code>id event_id event_date age money_spent rank 1 100 2016-10-01 4 150 2 2 100 2016-09-30...
1
2016-10-07T14:28:29Z
39,922,162
<p>Sort the <code>event_date</code> column in ascending order and choose the first date which corresponds to the earliest date and compute the results(in days) after subtracting it with the other dates:</p> <pre><code>min_date = df.sort_values(by=['event_date'])['event_date'].iloc[0] df['days_last_event'] = (df['event...
0
2016-10-07T16:40:21Z
[ "python", "python-2.7", "pandas" ]
How can I use unittest.mock to remove side effects from code?
39,919,699
<p>I have a function with several points of failure:</p> <pre><code>def setup_foo(creds): """ Creates a foo instance with which we can leverage the Foo virtualization platform. :param creds: A dictionary containing the authorization url, username, password, and version associated wit...
3
2016-10-07T14:29:13Z
39,920,128
<p>Assuming your exceptions are being raised from <code>foo.authenticate()</code>, what you want to realize here is that it does not necessarily matter whether the data is in fact <em>really</em> valid in your tests. What you are trying to say really is this: </p> <p>When this external method raises with something, my...
2
2016-10-07T14:51:34Z
[ "python", "unit-testing", "python-3.x", "exception-handling", "python-unittest.mock" ]
How can I use unittest.mock to remove side effects from code?
39,919,699
<p>I have a function with several points of failure:</p> <pre><code>def setup_foo(creds): """ Creates a foo instance with which we can leverage the Foo virtualization platform. :param creds: A dictionary containing the authorization url, username, password, and version associated wit...
3
2016-10-07T14:29:13Z
39,920,186
<p>If you wish to mock out http servers from bogus urls, I suggest you check out <a href="https://github.com/gabrielfalcao/HTTPretty" rel="nofollow">HTTPretty</a>. It mocks out urls at a socket level so it can trick most Python HTTP libraries that it's a valid url.</p> <p>I suggest the following setup for your unittes...
0
2016-10-07T14:53:50Z
[ "python", "unit-testing", "python-3.x", "exception-handling", "python-unittest.mock" ]
UnicodeDecodeError Help: Data needs to be in ascii for seaborn but source code is in utf-8
39,919,704
<p>Context: I'm trying to build a seaborn heatmap in order to map the following type of data (in a dataframe):</p> <p><a href="http://i.stack.imgur.com/NFZAj.png" rel="nofollow"><img src="http://i.stack.imgur.com/NFZAj.png" alt="enter image description here"></a></p> <p>(This can be up to 50 fruits and 5500 stores)</...
2
2016-10-07T14:29:22Z
39,920,926
<p>Your configuration (Python 2.7, Pandas 0.18.1, Seaborn 0.7.1) should certainly be able to handle utf-8. Even if the font used in the plot doesn't support these unicode characters, the heatmap should still be displayed. Here is a test case:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd impo...
1
2016-10-07T15:31:42Z
[ "python", "pandas", "unicode", "encoding", "seaborn" ]
Click through pagination with Selenium in Python
39,919,744
<p>I'm working on building an automation framework using Selenium in Python where I am trying to loop through landing pages on HubSpot.com by clicking on the "Next" button.</p> <p>The Next button is located in the following HTML according to the Chrome Inspector:</p> <pre><code>&lt;a class="next" data-reactid=".0.1.0...
0
2016-10-07T14:30:57Z
39,922,786
<p>I have managed to find a workaround. Instead of trying to click the next button I click the relevant page-button. I define j=2 to begin with, and then use the following code:</p> <pre><code>if self.driver.find_elements(By.XPATH, """//a[@class="next" and not(@disabled)]""") != 0: xpathstring = """//d...
0
2016-10-07T17:21:44Z
[ "python", "selenium", "onclick", "click" ]
Pyside setData flags on QStandardItem
39,919,748
<p>I have two questions here.</p> <ol> <li><p>Where can I find a list of all the available flags/properties I can set using the setData method of a QstandardItem? I only know of the one below because i came across it online.</p></li> <li><p>How do I set the Font of my QStandardItem to be bold?</p></li> </ol> <p><stro...
0
2016-10-07T14:31:12Z
39,923,605
<ol> <li><p>The Qt Documentation lists the <a href="http://doc.qt.io/qt-4.8/qt.html#ItemDataRole-enum" rel="nofollow">item data roles</a>.</p></li> <li><p>The font can be changed like this:</p> <pre><code>font = item.font() font.setBold(True) item.setFont(font) </code></pre></li> </ol>
1
2016-10-07T18:21:22Z
[ "python", "pyside", "qstandarditem" ]
pyplot plot shows a window with no graph
39,919,761
<p>I have several arrays for which I calculate the Frobenius norm. Then I simply draw a graph of these calculated norms vs the index of their corresponding arrays. The problem is that when the plot window pops out, there is no graph on it. But, when I add a styling for my plot, it shows the graph. I also tried to use s...
0
2016-10-07T14:31:50Z
39,934,108
<p>I think I got it. I used squeeze and it works. So, the plot line should be changed like this:</p> <pre><code>plt.plot(np.squeeze(NumVec),np.squeeze(FrobNorm)) </code></pre> <p>I still don't understand why, but this is what I guess; I think somehow the format of the numpy arrays that were produced, was in the way t...
0
2016-10-08T15:26:53Z
[ "python", "matplotlib", "plot" ]
summation of values in pandas
39,919,828
<p>There is a pandas dataframe with two columns 'key' and 'value'. I want summation of values corresponding to the rows with key in range(key-3,key-1) to be put in a new column 'new_value' in the original dataframe. for eg:</p> <p>df:</p> <pre><code>key value 1 2 2 1 3 1 5 1 7 1 </code></pre> <p...
-2
2016-10-07T14:35:28Z
39,920,533
<p>You can take a look at this :</p> <pre><code>In [52]: df Out[52]: key value 0 1 2 1 2 1 2 3 1 3 5 1 4 7 1 In [53]: df['new_value'] = df.apply(lambda x: df[(df['key'] &gt;= x['key'] - 3) &amp; (df['key'] &lt;= x['key'] - 1)]['value'].sum(), axis=1) In [54]: df Out[54]: ...
0
2016-10-07T15:11:05Z
[ "python", "pandas" ]
Failed ndb transaction attempt not rolling back all changes?
39,919,928
<p>I have some trouble understanding a sequence of events causing a bug in my appplication which can only be seen <strong>intermittently</strong> in the app deployed on GAE, and never when running with the local <code>devserver.py</code>.</p> <p>All the related code snippets below (trimmed for MCV, hopefully I didn't ...
3
2016-10-07T14:40:01Z
40,059,476
<p>I found a workaround: specifying no retries to the <code>jobs_completed()</code> transaction:</p> <pre><code>@ndb.transactional(xg=True, retries=0) def jobs_completed(self, job): </code></pre> <p>This prevents the automatic repeated execution, instead causing an exception:</p> <blockquote> <p>TransactionFailedE...
0
2016-10-15T13:16:35Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
SQL query doesn't select the data that I need with 'where' conditions
39,919,990
<p>I am trying to get the records from my database where studentID, and lessonDate are equal to specific results. The StudentID seems to work fine, but lessonDate does not. Because of date formats, I have converted all dates to strings to be put into the database. I have set up database file so that the field is text ...
0
2016-10-07T14:43:44Z
39,920,079
<p>Your parameters are not being quoted correctly.</p> <p>This is why you should not use string interpolation to add data into your queries. You should use the db-api's parameter substitution instead:</p> <pre><code>self.cur.execute("""SELECT b.roadExerciseName, a.rating FROM lessonExercises a LEF...
2
2016-10-07T14:49:08Z
[ "python", "sqlite" ]
else-like clause when PIR motion sensors not sensing using Raspberry Pi
39,920,019
<p>I'm working on a Raspberry Pi project which displays a different video-loop depending on which of the 3 PIR motion sensors are "sensing motion". When no sensors are sensing anything, I want to display an additional video. So all in all there are 4 videos: left, middle, right, not-active.</p> <p>Using Python 3.4.2 ,...
0
2016-10-07T14:45:41Z
39,928,589
<p>I managed to solve the issue, and thought I'll post it in case someone wants to use it. Note that the code has been changed quite considerably. It still uses very low CPU. The only difference is that this code is more efficient at picking up motions, but at the cost of higher false readings. That may be fixed by adj...
0
2016-10-08T04:10:18Z
[ "python", "python-3.x", "raspberry-pi3" ]
HSM using label of key object in PKCS11
39,920,023
<p>This block of code is loading a cryptoki.so library and retrieving slot info. This is getting a list of objects in slot num. 0. I don't need to access all the keys to perform a few functions, just a specific key pair. Is there a way to get a single desired token by using the label name, object ID, or handle?</p> <p...
1
2016-10-07T14:45:57Z
39,954,836
<p>You can work only with one token by checking its label before use, e.g.:</p> <pre><code>tokenInfo = pkcs11.getTokenInfo(slot) if 'DesiredTokenLabel' == tokenInfo.label.decode('ascii').strip(): # Start working with this particular token session = pkcs11.openSession(s) </code></pre> <p>You can enumerate only...
1
2016-10-10T09:07:04Z
[ "python", "encryption", "cryptography", "pkcs#11", "hsm" ]
xml.etree.ElementTree search tag by variable
39,920,099
<p>I have a problem with the xml.etree.ElementTree Module in Python. I tried to search for a tag in the XML Tree using a variable:</p> <pre><code>i = "Http_Https" print(xmldoc_ports.findall(".//*application-set/[name=i]/application/")) </code></pre> <p>But it looks like that it did not resolve the variable <code>i</c...
0
2016-10-07T14:50:07Z
39,920,154
<p>The <code>.//*application-set/[name=i]/application/</code> is not valid. I think you meant:</p> <pre><code>xpath = ".//application-set[@name='%s']/application" % i print(xmldoc_ports.findall(xpath)) </code></pre> <p>Note that <code>@</code> before the name - this is how you show access the <code>name</code> attrib...
1
2016-10-07T14:52:37Z
[ "python", "xml-parsing" ]
Riak Search 2 not indexing bucket
39,920,110
<p>I'm using Riak as a key-value store backend for a graph database implemented in Python.</p> <p>I created a custom <a href="https://github.com/linkdd/link.graph/blob/master/etc/link/graph/schemas/node.xml" rel="nofollow">search schema</a> named <code>nodes</code>. I created and activated a bucket type <code>nodes</c...
1
2016-10-07T14:50:32Z
39,925,036
<p>First, you should take into account that Riak automatically adds suffix <code>_set</code>, so that you don't have to name yours <code>type_set</code> but <code>type</code>. Otherwise you will have to query for <code>type_set_set:*</code> instead of <code>type_set:*</code>.</p> <p>Second, according to <a href="https...
1
2016-10-07T20:09:07Z
[ "python", "solr", "riak" ]
Error MSVCP140.dll not found on python Geopandas installation
39,920,116
<p>I've installed Geopandas (a library that doesn't have a specific wheel for Windows). The pip install ran without problems but when I execute the script, it shows me an 'MSVCP140.dll not found' error.</p> <p>The dll seems to be there and the permission on the temp for full control is ok too (as another post suggests...
0
2016-10-07T14:50:57Z
39,981,177
<p>As <a href="http://stackoverflow.com/users/205580/eryksun">eryksun</a> said in his comment, </p> <blockquote> <p>then MSVCP140.dll needs to be installed to the System32 directory or a PATH directory. Installing <a href="https://www.microsoft.com/en-us/download/details.aspx?id=48145" rel="nofollow">vc_redist.x86...
0
2016-10-11T15:37:28Z
[ "python", "windows", "dll", "geopandas" ]
How to preprocess twitter text data using python
39,920,183
<p>I have text data after retrieval from a <code>mongoDB</code> in this format: </p> <p>**</p> <pre><code>[u'In', u'love', u'#Paralympics?\U0001f60d', u"We've", u'got', u'nine', u'different', u'sports', u'live', u'streams', u'https://not_a_real_link', u't_https://anotherLink'] [u't_https://somelink'] [u'RT', u'@spo...
0
2016-10-07T14:53:45Z
39,920,256
<p>This is wrong:</p> <pre><code>def clean_text(self, rawText): temp_raw = rawText for i, text in enumerate(temp_raw): temp = re.sub(r'https?:\/\/.*\/[a-zA-Z0-9]*', 'URL', text) return temp </code></pre> <p>you return the last substituted string instead of a list, that should replace your <code>ra...
0
2016-10-07T14:58:05Z
[ "python", "regex" ]
Pygame: Flipping horizontally
39,920,237
<p>I'm making a game for my program and I'm trying to flip the image horizontally when I press the left key or right key. I found out about the function </p> <pre><code>pygame.transform.flip </code></pre> <p>however I am unsure as to where to insert it in my code. It would be appreciated if someone could help me. Her...
0
2016-10-07T14:56:38Z
39,920,577
<p>I would do the image processing stuff when Player is instantiated like so:</p> <pre><code>class Player(object): def __init__(self): self.image = pygame.image.load("player1.png") self.image2 = pygame.transform.flip(self.image, True, False) self.flipped = False self.x = 0 ...
2
2016-10-07T15:12:52Z
[ "python", "python-2.7", "pygame" ]
knn with custom distance function in R
39,920,387
<p>I want to apply k nearest neighbour with a custom distance function. I have not found a way to pass this function using packages like FNN or class. Is there a way to pass a function or distance matrix to an existing knn algorithm in some R package or do I have to write it from scratch?</p> <h2>Background</h2> <p>T...
1
2016-10-07T15:03:45Z
39,963,292
<p>After searching a bit, I found a package called KODAMA that <strong>does cross validation</strong> 10 fold for instance and seems to have a knn prediction function <code>knn.predict</code> working with a distance matrix calculated separately by the <code>knn.dist</code> function.</p> <p>It appears that the output o...
1
2016-10-10T17:04:17Z
[ "python", "machine-learning", "distance", "knn" ]
Segmentation fault using python layer in caffe
39,920,438
<p>I'm trying to use python layer as described <a href="http://chrischoy.github.io/research/caffe-python-layer/" rel="nofollow">here</a>. But I am getting this exception:</p> <pre><code>I1007 17:48:31.366592 30357 layer_factory.hpp:77] Creating layer loss *** Aborted at 1475851711 (unix time) try "date -d @1475851711"...
0
2016-10-07T15:06:00Z
39,920,765
<p>From my experience, this is one of the most prevalent weaknesses in Caffe: this SegFault without an error message. I generally get this when I haven't connected the data layer properly. For instance, I haven't started the data server, or there's a severe mismatch in format.</p>
0
2016-10-07T15:22:58Z
[ "python", "caffe" ]
generate mouse velocity when only integer steps are allowed
39,920,445
<p>I write a simple program in python which includes moving my mouse (I do his with <a href="https://github.com/PyUserInput/PyUserInput" rel="nofollow">PyUserInput</a>). However: It is only allowed to move the mouse in integer steps (say pixels). So <code>mouse.move(250.3,300.2)</code> won't work.</p> <p>I call the mo...
1
2016-10-07T15:06:26Z
39,921,155
<p>What you need to do is keep track of the previous position and the desired current position, and hand out the rounded coordinate. You could track the previous position in a function but it's much easier to do it in a class.</p> <pre><code>class pwm: def __init__(self): self.desired_position = 0.0 ...
1
2016-10-07T15:44:15Z
[ "python" ]
When is a decorator (class) object destroyed?
39,920,525
<p>I am using a decorator to open and close a neo4j database session (and allow my decorated functions to run queries within that session). At first I used a decorator function :</p> <pre><code> from neo4j.v1 import GraphDatabase, basic_auth def session(func,url="bolt://localhost:7474", user="neo4j",pwd="neo4j", *arg...
0
2016-10-07T15:10:47Z
39,920,984
<h2>How to</h2> <p>Here is a template to create a decorator with parameters using a function:</p> <pre><code>def decorator_maker(param1, param2): print("The parameters of my decorator are: {0} and {1}".format(param1, param2)) def my_decorator(function_to_decorate): def wrapper(arg1, arg2): ...
1
2016-10-07T15:34:38Z
[ "python", "database-connection", "decorator", "python-decorators" ]
How does one create a dense vector from a sentence as input to a neural net?
39,920,528
<p>I'm having trouble figuring out how one converts a sentence into a dense vector as input to a neural network, specifically to test whether or not a sentence is '<strong><em>liked</em></strong>' or '<strong><em>not liked</em></strong>' given a training set. </p> <p>I've had some luck with Support Vector Machines. Us...
0
2016-10-07T15:10:55Z
39,925,634
<p>You might find this blog helpful:</p> <p><a href="http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/" rel="nofollow">http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/</a></p>
1
2016-10-07T20:52:53Z
[ "python", "nlp", "svm", "deep-learning" ]
How does one create a dense vector from a sentence as input to a neural net?
39,920,528
<p>I'm having trouble figuring out how one converts a sentence into a dense vector as input to a neural network, specifically to test whether or not a sentence is '<strong><em>liked</em></strong>' or '<strong><em>not liked</em></strong>' given a training set. </p> <p>I've had some luck with Support Vector Machines. Us...
0
2016-10-07T15:10:55Z
39,928,490
<p>There are many ways:</p> <p>1) Vector space model, after you have that dense vector, you can apply a SVD eg with 300 components , then you will have a vector in 300 dimensions. Do check out <a href="https://github.com/StevenLOL/aicyber_semeval_2016_ivector/blob/master/System_1/system_1_baseline.py#L32" rel="nofollo...
1
2016-10-08T03:50:56Z
[ "python", "nlp", "svm", "deep-learning" ]
Testing with a txt file
39,920,551
<p>I created a input.txt file. There several sets of testing input date in input.txt. Then I run in the terminal <code>python Filename.py &lt;input.txt &gt;output.txt</code>. After running I only get output of first set input date. How can I get all the output date automatically in output.txt? </p> <pre><code># GET a...
0
2016-10-07T15:11:41Z
39,923,403
<p>I feel that you have not added any loop in order to traverse all the inputs in txt file. This might help:</p> <p>Start with <code>fp = open('input.txt')</code>. Add a <code>for</code> loop like <code>for i, line in enumerate(fp.readlines()):</code> and then type the code you had added for getting the values and pri...
0
2016-10-07T18:06:17Z
[ "python" ]
Pythonanywhere Moviepy
39,920,663
<p>What is problem?</p> <p>I'm running on Pythonanywhere.com</p> <blockquote> <p>This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or.that the path you specified is incorrect<...
1
2016-10-07T15:17:09Z
39,979,774
<p>PythonAnywhere admin here. For anyone else that might come across the problem, it was due to the ImageMagick security vulnerability that was discovered a few weeks ago:</p> <p><a href="https://www.imagemagick.org/discourse-server/viewtopic.php?t=29588" rel="nofollow">https://www.imagemagick.org/discourse-server/vi...
2
2016-10-11T14:35:33Z
[ "python", "imagemagick", "moviepy" ]
Selenium With Python-Firefox always loading blank page
39,920,691
<p>I've got an issue setting up and running Selenium with Python at first. My system- Windows 8.1, Python 3.4.4 </p> <p>When I try to call a browser with python code inside console or even running py doc with this particular code all I get-nothing but a blank page in browser. After some time I have errors in console...
0
2016-10-07T15:18:44Z
39,921,840
<p>This is a problem with loading a Firefox profile. In order to avoid that, you should use a <strong>custom profile</strong> for your tests. </p> <p>Create a custom profile: Close all instances of Firefox and then start it from command line with <code>firefox -P</code>. Follow the steps to create a profile with some ...
0
2016-10-07T16:21:31Z
[ "python", "selenium" ]
Plot polar scatter plot with images as markers, matplotlib: cannot convert NaN to integer
39,920,705
<p>Given a pandas dataframe I have some code that will create a scatter plot and place a specified png at each point:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.image import BboxImage from matplotlib.transforms import Bbox, TransformedBbox threshold = 0.05 fig = plt.figure(figsize=(20,20)) ax = fi...
1
2016-10-07T15:19:45Z
39,922,273
<p>You need to pass positive angles to Bbox, apparently. This should work:</p> <pre><code>def cart2pol(x, y): rho = np.sqrt(x**2 + y**2) phi = np.arctan2(y, x) if phi &lt; 0: phi += 2 * np.pi return(rho, phi) </code></pre>
1
2016-10-07T16:46:52Z
[ "python", "matplotlib" ]
Python, connect menu to functions
39,920,727
<p>I have got a menu and a couple of functions to continue working with.My task is to add more functions. The menu code right now, looks like this.</p> <pre><code>def menu(): """ Display the menu with the options that The Goddamn Batman can do. """ print(chr(27) + "[2J" + chr(27) + "[;H") print(meImage()) print("Hi, ...
0
2016-10-07T15:21:17Z
39,921,738
<p>You are converting years to seconds?</p> <p>1) In python <code>int()</code> is a function that takes a parameter, it doesn't cast values like <code>(int)31 556 926</code><br> 2) integer values don't have spaces in them<br> 3) You can't put code after a <code>return</code> statement and expect it to run<br> 4) <code...
1
2016-10-07T16:15:32Z
[ "python" ]
unable to fetch updated variable from an active python module
39,920,833
<p>I am new to python and trying to create a module that would fetch a specific variable from an active module preferably as read only. I have tried importing the file in test2 but the print statement displays the length as 0. Cant understand why it is not able to get the current status of the variable and only reading...
1
2016-10-07T15:26:41Z
39,921,029
<p>When you wrap statements in:</p> <pre><code>if __name__ == "__main__" </code></pre> <p>The code within only gets executed when you execute that specific module from the Python interpreter. So your Main function won't get executed, and consequently your data variable won't be initialized, unless you run:</p> <pre>...
0
2016-10-07T15:37:06Z
[ "python" ]
model selection for GaussianMixture by using GridSearch
39,920,862
<p>I'd like to use the function GaussianMixture by scikit-learn, and I have to perform model selection. I want to do it by using GridSearchCV, and I would like to use for the selection the BIC and the AIC. Both these values are implemented into GaussianMixture(), but I don't know how to insert them into the definition ...
1
2016-10-07T15:28:02Z
39,921,941
<p>Using the BIC/AIC is an <em>alternative</em> to using cross validation. <code>GridSearchCV</code> selects models using cross validation. To perform model selection using the BIC/AIC we have to do something a little different. Let's take an example where we generate samples from two Gaussians, and then try to fit the...
0
2016-10-07T16:27:22Z
[ "python", "scikit-learn", "grid-search" ]
Writing a program that creates a particular pattern using the number sign
39,920,886
<p>How can this particular pattern be created using the number sign. <strong>Note</strong>, the first line must be indented.</p> <p><strong><em>Write a program that creates a pattern like the one below. Let the user input a nonnegative integer to determine the number of lines of the pattern.</em></strong></p> <p>I am...
-3
2016-10-07T15:29:47Z
39,921,636
<p>Print the first line before the loop.</p> <pre><code>print " # #" for row in range(4): print "# #" </code></pre> <p>Or use an <code>if</code> statement</p> <pre><code>for row in range(5): if row == 0: print " ", # trailing comma prints without a newline print "# " </code></pre>
0
2016-10-07T16:10:09Z
[ "python" ]
Python Function Return Statement is Confusing and Complex
39,920,930
<p>Could any body explain what do the 'and' and 'or' statements are doing in the return statement of the function below ? the function seems to be returning the largest common denominator of a and b. </p> <p> <code>def gcd(a,b): return b and gcd(b, a % b) or a</code></p> <p>Thank you !</p>
-1
2016-10-07T15:31:54Z
39,921,014
<p>The first thing we can do is put in some parenthesis:</p> <pre><code>((b and gcd(b, a % b)) or a) </code></pre> <p>Now lets take this piece by piece:</p> <pre><code>b and gcd(b, a % b) </code></pre> <p>This will give <code>b</code> if <code>b</code> is falsy. Otherwise it'll give you <code>gcd(b, a % b)</code>....
6
2016-10-07T15:36:19Z
[ "python", "python-2.7", "function", "python-3.x" ]
Python Function Return Statement is Confusing and Complex
39,920,930
<p>Could any body explain what do the 'and' and 'or' statements are doing in the return statement of the function below ? the function seems to be returning the largest common denominator of a and b. </p> <p> <code>def gcd(a,b): return b and gcd(b, a % b) or a</code></p> <p>Thank you !</p>
-1
2016-10-07T15:31:54Z
39,921,032
<p>The function continuously returns <code>gcd(b, a % b)</code> while <code>b</code> has a truthy value, i.e not equal to zero in this case. </p> <p>When <code>b</code> reaches <code>0</code> (after consecutively being assigned to the result of <code>a % b</code>), <code>b and gcd(b, a % b)</code> will be <code>False<...
0
2016-10-07T15:37:10Z
[ "python", "python-2.7", "function", "python-3.x" ]
referencing class members from child class
39,921,165
<p>Edit: sorry for the confusion about parent/child. I am new to OOP so confusing my terms. </p> <p>I would like to understand the appropriate strategy to reference class attributes which will be provided by an inherited (child class). </p> <p>I have a case where I have a common base class which will be used, and ...
2
2016-10-07T15:44:43Z
39,922,510
<p>Use a <code>BaseParent</code> class that defines <code>instance_id</code>, and have both <code>Parent</code> implementations inherit from it. This will shut up your IDE. As a side benefit, <code>Child</code> can extend either <code>Parent</code>, but will always be an instance of <code>BaseParent</code>.</p> <p>Tha...
1
2016-10-07T17:00:50Z
[ "python", "class", "python-3.x" ]
Django: Using get_form_kwarg to pass url pramater into form __init__ for ModelChoiceField selection filiter
39,921,273
<p>I am building a FAQ app.</p> <p>Model flow Topic -> Section -> Article.</p> <p>Article has a FK to Section which has a FK to Topic.</p> <p>In my create article from I want to take in the Topic_Pk so when the user selects a Section the choice selection is limited to just the Sections attached under the Topic.</p> ...
1
2016-10-07T15:50:44Z
39,921,451
<p>For your current <code>__init__</code> signature, you <strong>must</strong> pop <code>topic_pk</code> from kwargs before you call <code>super()</code>, otherwise you'll get the <code>TypeError</code>. </p> <p>In your question, you say that popping the value would 'invalidate the whole point', but I think you're mis...
3
2016-10-07T16:00:03Z
[ "python", "django" ]
Access XML element by name
39,921,344
<p><a href="http://i.stack.imgur.com/Yp0yd.png" rel="nofollow"><img src="http://i.stack.imgur.com/Yp0yd.png" alt="enter image description here"></a></p> <p>Im using <code>xml.etree.ElementTree</code> to parse my XML data. I'm trying to get the text value of <code>&lt;Name&gt;</code></p> <p>This is my code.</p> <pre>...
-1
2016-10-07T15:54:46Z
39,927,491
<p>Your XML is likely has default namespace -namespace declared with no prefix-. Notice that descendant elements without prefix inherits default namespace implicitly. You can handle default namespace the way you would <a href="http://stackoverflow.com/questions/14853243/parsing-xml-with-namespace-in-python-via-elementt...
0
2016-10-08T00:35:15Z
[ "python", "xml" ]
Parsing XML response with repeated tags
39,921,353
<p>This is my XML response - </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Dataset name="aggregations/g/ds083.2/2/TP" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xml.opendap.org/ns/DAP2" xsi:schemaLocation="http://xml.opendap.org/ns/DAP2 http://xml.opendap.org/dap/dap2.xsd" ...
0
2016-10-07T15:55:07Z
39,921,690
<p>Two small changes:</p> <pre><code>map = grid.findall("{http://xml.opendap.org/ns/DAP2}Map") for child in map: print(child.get('name')) </code></pre> <p><code>findall</code> gets all matches, and when you are looping over <code>child in map</code> you want to be sure that you are returning values relating to <co...
2
2016-10-07T16:12:40Z
[ "python", "xml", "xml-parsing", "httprequest", "python-3.5" ]
How to remove the border of a Tkinter OptionMenu Widget
39,921,360
<p>I have been looking through multiple websites, which only give me a half satisfactory answer, how would I colour each part of of a Tkinter OptionMenu Widget?</p> <p>Code Snippet:</p> <pre><code>from tkinter import * root = Tk() text = StringVar() fr = Frame (root,bg="yellow") fr.grid() menu = OptionMenu (fr, te...
-1
2016-10-07T15:55:16Z
39,941,732
<p>I don't understand your problem.</p> <p>menu["menu"] is a tkinter.Menu object, so you can set others options.</p> <p>Possible colors options are :</p> <ul> <li>activebackground -> that you want </li> <li>activeforeground -> that you want</li> <li>background</li> <li>bg</li> <li>disabledforeground</li> <li>fg</li>...
0
2016-10-09T08:53:23Z
[ "python", "python-3.x", "tkinter", "colors", "optionmenu" ]
How to remove the border of a Tkinter OptionMenu Widget
39,921,360
<p>I have been looking through multiple websites, which only give me a half satisfactory answer, how would I colour each part of of a Tkinter OptionMenu Widget?</p> <p>Code Snippet:</p> <pre><code>from tkinter import * root = Tk() text = StringVar() fr = Frame (root,bg="yellow") fr.grid() menu = OptionMenu (fr, te...
-1
2016-10-07T15:55:16Z
39,953,629
<p>All that I had to do was set the <code>highlightthickness</code> option to <code>0</code></p> <p><code>menu["highlightthickness"]=0</code></p> <p>This get's rid of the ugly border around the drop down menu.</p>
0
2016-10-10T07:55:17Z
[ "python", "python-3.x", "tkinter", "colors", "optionmenu" ]
I keep getting 'invalid character in identifier' when opening a file in python
39,921,432
<p>So I'm trying to open a file with the following code: </p> <pre><code>open(‘datapickle’, ‘rb’) as f: names, F, approximate = pickle.load(f) </code></pre> <p>However, I constantly get: <a href="http://i.stack.imgur.com/qPhR9.png" rel="nofollow"><img src="http://i.stack.imgur.com/qPhR9.png" alt="enter im...
1
2016-10-07T15:59:15Z
39,921,475
<p>Two problems:</p> <ol> <li><p>Those tick characters <code>‘</code> are not valid. Use single <code>'</code> or double <code>"</code> quotes.</p></li> <li><p>The correct syntax is <code>with open(...) as f</code>. You're missing the <code>with</code> statement.</p></li> </ol> <p>The editor you're using should be ...
4
2016-10-07T16:01:50Z
[ "python", "pickle" ]
Reading hdf5 file quickly with cython and h5py
39,921,433
<p>I'm trying to speed up a python3 function that takes some data, which is an array of indexes and saves them if they meet a certain criterion. I have tried to speed it up by using "cython -a script.py", but the bottle neck seems to be the h5py I/O slicing datasets.</p> <p>I'm relatively new to cython, so I was wonde...
0
2016-10-07T15:59:17Z
39,923,322
<p>As described here: <a href="http://api.h5py.org/" rel="nofollow">http://api.h5py.org/</a>, <code>h5py</code> uses <code>cython</code> code to interface with the <code>HDF5</code> <code>c</code> code. So your own <code>cython</code> code might be able to access that directly. But I suspect that will require a lot m...
0
2016-10-07T18:00:24Z
[ "python", "cython", "h5py" ]
Django 1.7 and PSQL: on_delete=models.SET_NULL not work
39,921,445
<p>My models.py:</p> <pre><code>class MyFile(models.Model): file = models.FileField(upload_to="myfiles", max_length=500, storage=OverwriteStorage()) slug = models.SlugField(max_length=500, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True,) date_created = model...
0
2016-10-07T15:59:46Z
39,922,893
<p>The default behavior of <code>on_delete</code> results in all related objects being deleted; in this case, the related object is MyFile.</p> <p>If you're trying to preserve the MyFile object, maybe consider adding a default via <code>on_delete=SET_DEFAULT</code> or using a callable passed to <code>on_default=SET(ca...
0
2016-10-07T17:28:42Z
[ "python", "django", "django-models" ]
Python Threading: Making the thread function return from an external signal
39,921,570
<p>Could anyone please point out whats wrong with this code. I am trying to return the thread through a variable flag, which I want to control in my main thread. </p> <h1>test27.py</h1> <pre><code>import threading import time lock = threading.Lock() def Read(x,y): flag = 1 while True: lock.acquire()...
0
2016-10-07T16:06:36Z
39,921,795
<p>Regular variables should not be tracked in threads. This is done to prevent race condition. You must use thread-safe constructs to communicate between threads. For a simple flag use <code>threading.Event</code>. Also you cannot access local variable <code>flag</code> via thread object. It is local, and is only visib...
0
2016-10-07T16:18:31Z
[ "python", "multithreading", "time" ]
Python Threading: Making the thread function return from an external signal
39,921,570
<p>Could anyone please point out whats wrong with this code. I am trying to return the thread through a variable flag, which I want to control in my main thread. </p> <h1>test27.py</h1> <pre><code>import threading import time lock = threading.Lock() def Read(x,y): flag = 1 while True: lock.acquire()...
0
2016-10-07T16:06:36Z
39,926,065
<p>The <code>Thread</code> class can be instantiated with the <code>target</code> argument. Then you just give it a function which should be raun in a new thread. It is a convenient way to start a simple thread, but for more control it is usualy easier to have a class inherited from <code>Thread</code>, which has addit...
0
2016-10-07T21:28:51Z
[ "python", "multithreading", "time" ]
Tensorflow: How to make a custom activation function with only python?
39,921,607
<p>So in Tensorflow it is possible to make your own activation function. But it is quite complicated, you have to write it in C++ and recompile the whole of tensorflow <a href="https://www.quora.com/Is-it-possible-to-add-new-activation-functions-to-TensorFlow-Theano-Torch-How" rel="nofollow">[1]</a> <a href="https://ww...
3
2016-10-07T16:08:19Z
39,921,608
<p><strong>Yes There is!</strong></p> <p><strong>Credit:</strong> It was hard to find the information and get it working but here is an example copying from the principles and code found <a href="https://github.com/tensorflow/tensorflow/issues/1095" rel="nofollow">here</a> and <a href="https://gist.github.com/harpone/...
4
2016-10-07T16:08:19Z
[ "python", "tensorflow", "custom-build", "activation-function" ]
autoit.pixel_search returning color is not found
39,921,610
<p>I'm trying to grab the coordinates for a specific pixel value on the screen, but I can't seem to get any results. The error I get is "autoit.autoit.AutoItError: color is not found".</p> <p>To verify my code I have the mouse move the the pixel that has the colour I want. This is not necessary, it was just part of a ...
0
2016-10-07T16:08:20Z
39,940,047
<p>So I figured out how to resolve my problem. I don't know why it works or what caused the problem, but for now here is the solution</p> <p>The correct formula for PixelSearch is PixelSearch(left, top, right, bottom). </p> <p>After playing around with the numbers it appears pyautoit is using (right, top, left, botto...
0
2016-10-09T04:34:03Z
[ "python", "autoit" ]
Checking the upper triangle matrix elements in python
39,921,627
<p>I have an upper triangle matrix, with many empty elements, however, I want to check which indices have empty elements but I want to check only those on upper, cause it's normal that the lower ones will be empty, so I don't want to check those. So I want to check the elements shown in the picture if they are empty or...
0
2016-10-07T16:09:32Z
39,921,811
<p>I think i got it, by simply adding when <code>j&gt; i</code></p>
0
2016-10-07T16:19:59Z
[ "python", "matrix" ]
Adding an integer and string to a list with new lines
39,921,654
<p>I have some code that generates a integer and a str and I can get them to append into a list but I would like them on a seperate line for each int and str. My code is as follows:</p> <pre><code>responses = [] responses.append(respTime) responses.append(category_repeated) responses = [0.11700010299682617 corr...
0
2016-10-07T16:11:03Z
39,923,778
<p>It is easier to process if you have a list of tuples:</p> <pre><code>responses = [] responses.append((respTime, category_repeated)) # &lt;--- slight difference responses == [(0.11700010299682617, 'correct'), (0.1000001431, 'correct')] # responses[0] == (0.11700010299682617, 'correct') </code></pre> <p>Here is an e...
2
2016-10-07T18:32:14Z
[ "python", "string", "list", "int", "rows" ]
Probabilistically Running Based On Hour
39,921,674
<p>I have a function that I want to run with increasing probability each hour until noon then decreasing probability until midnight. I can imagine a normal distribution centered on noon would do it (so the probability of running the function is 100% at noon but very low at midnight), however I cannot convert that into ...
0
2016-10-07T16:12:03Z
39,922,728
<p>Pure magic. I figured it out. No, just joking. When you asked that question, it immediately reminded me of sinus waves, they go up and then down again - just like your thing you're trying to do.</p> <p>According to <a href="http://jwilson.coe.uga.edu/emt668/EMT668.Folders.../sine/assmt1.html" rel="nofollow">this</a...
1
2016-10-07T17:16:49Z
[ "python" ]
Probabilistically Running Based On Hour
39,921,674
<p>I have a function that I want to run with increasing probability each hour until noon then decreasing probability until midnight. I can imagine a normal distribution centered on noon would do it (so the probability of running the function is 100% at noon but very low at midnight), however I cannot convert that into ...
0
2016-10-07T16:12:03Z
39,923,113
<p>Lots of options. Just make a function that returns a value between 0 and 1 based on the hour. Then, make a random float between 0 and 1. If the float is less than the probability, run the program.</p> <pre><code>import numpy as np def prob_sawtooth(hour): return 1. - abs((hour - 12.) / 12.) def prob_sin(hour)...
1
2016-10-07T17:44:59Z
[ "python" ]
Python cx_Oracle error
39,921,696
<p>I try to run a python scrapy crawler with crontab on Ubuntu, but i got this error message:</p> <pre><code>Traceback (most recent call last): File "/usr/bin/scrapy", line 9, in &lt;module&gt; load_entry_point('Scrapy==1.0.3', 'console_scripts', 'scrapy')() File "/usr/lib/python2.7/dist-packages/scrapy/cmdlin...
0
2016-10-07T16:13:06Z
39,934,020
<p>I have a few options you can try:</p> <p>1) Set the environment variables in listarunner.sh instead of ~/.bashrc</p> <p>2) Use a file in /etc/ld.so.conf.d to make the setting of LD_LIBRARY_PATH unnecessary</p> <p>3) Rebuild cx_Oracle, first setting the environment variable FORCE_RPATH to any value before building...
1
2016-10-08T15:16:30Z
[ "python", "ubuntu", "scrapy", "crontab", "cx-oracle" ]
Caeser Cipher Cracking Python
39,921,743
<p>I am running this using Python 2.7.12</p> <pre><code>charset="ABCDEFGHIJKLMNOPQRSTUVWXYZ" # The list of characters to be encrypted numchars=len(charset) # number of characters that are in the list for encryption def caesar_crack(crackme,i,newkey): print '[*] CRACKING - key: %d; ciphertext: %s' % (i,crackm...
0
2016-10-07T16:15:47Z
39,922,170
<p>just move the indentation of </p> <pre><code>return plaintext </code></pre> <p>one step to left</p> <p>that will resolve the looping issue and it will go through all 26 numbers</p> <p>didnt check the remaining of the program if it is good </p>
0
2016-10-07T16:40:37Z
[ "python", "python-2.7", "caesar-cipher" ]
How to calculate user input in python
39,921,791
<p>I am supposed to write a program in Python that asks for grades one at a time. When the user enters “done” , calculate the following: grade average.</p> <p>This is what I have so far:</p> <pre><code>def main(): user_input = input("Enter grade: ") number = user_input while True: user_input ...
-2
2016-10-07T16:18:09Z
39,921,903
<p>I am noticing some things which may solve the issue for you.</p> <ol> <li>You're feeding <code>number</code> to the <code>avg</code> function when really you want to give it a list of numbers.</li> <li>I think you should do something like this: make a list called numbers and append each user input to that list. The...
1
2016-10-07T16:25:09Z
[ "python", "input" ]
How to calculate user input in python
39,921,791
<p>I am supposed to write a program in Python that asks for grades one at a time. When the user enters “done” , calculate the following: grade average.</p> <p>This is what I have so far:</p> <pre><code>def main(): user_input = input("Enter grade: ") number = user_input while True: user_input ...
-2
2016-10-07T16:18:09Z
39,922,850
<p>There are a few flaws in your logic.</p> <ul> <li>Each time you ask for user input in <code>main()</code>, you override the value of <code>user_input</code>. What you should be doing, is gathering each numbers in a <code>list()</code>.</li> <li>What the errors Python raised are telling you, is that the builtin func...
0
2016-10-07T17:25:42Z
[ "python", "input" ]
Django Python, Form show the csrf token
39,921,797
<p>I'm trying to make a variable form in django but it seems not working properly, I hope you can help me because i show me the token instead of form values.</p> <p><a href="http://i.stack.imgur.com/ARP7l.png" rel="nofollow"><img src="http://i.stack.imgur.com/ARP7l.png" alt="enter image description here"></a></p> <p...
0
2016-10-07T16:18:40Z
39,922,180
<p>In order to obtain values from form you should retrieve them from your request object and return in form of context as a part of your rendered template. Here what your code accomplish currently: </p> <p>Check method of the request</p> <pre><code>if request.method == "POST": </code></pre> <p>Assign to variable res...
0
2016-10-07T16:41:20Z
[ "python", "django", "forms", "token" ]
Django Python, Form show the csrf token
39,921,797
<p>I'm trying to make a variable form in django but it seems not working properly, I hope you can help me because i show me the token instead of form values.</p> <p><a href="http://i.stack.imgur.com/ARP7l.png" rel="nofollow"><img src="http://i.stack.imgur.com/ARP7l.png" alt="enter image description here"></a></p> <p...
0
2016-10-07T16:18:40Z
39,922,199
<p>The <code>csrfmiddlewaretoken</code> <em>is</em> a form value. Each time you set <code>response</code> in your loop, it overwrites the previous value. In your case, <code>csrfmiddlewaretoken</code> is the final item in <code>request.POST.items()</code>, so this is the only result you see.</p> <pre><code> for key...
0
2016-10-07T16:42:21Z
[ "python", "django", "forms", "token" ]
Django Python, Form show the csrf token
39,921,797
<p>I'm trying to make a variable form in django but it seems not working properly, I hope you can help me because i show me the token instead of form values.</p> <p><a href="http://i.stack.imgur.com/ARP7l.png" rel="nofollow"><img src="http://i.stack.imgur.com/ARP7l.png" alt="enter image description here"></a></p> <p...
0
2016-10-07T16:18:40Z
39,925,712
<p>But it still showing the token :(</p> <pre><code>def test(request): if request.method == "POST": response = '' for key, value in request.POST.items(): response += '%s %s\n' % (key, value) return HttpResponse(response) return render(request, 'datos2.html') </code></pre>...
0
2016-10-07T20:58:30Z
[ "python", "django", "forms", "token" ]
How do I turn a string of numbers into a list on Python?
39,921,819
<p>I'm trying to figure out how many numbers in a text file are larger than 0.1. The text file has 1001 last names and numbers in the following format:</p> <pre><code>Doe 5 Anderson 0.3 Smith 6 </code></pre> <p>I figured out how to separate the numbers but i'm having trouble converting my string of numbers into a lis...
1
2016-10-07T16:20:26Z
39,921,878
<p>Supposing <code>lines</code> is a list of strings, and each of them consists of exactly one number and nothing more.</p> <pre><code>result = sum(1 if float(x) &gt; 0.1 else 0 for x in lines) </code></pre> <p>Another very similar way to do the same:</p> <pre><code>result = sum(float(x) &gt; 0.1 for x in lines) </c...
4
2016-10-07T16:23:35Z
[ "python" ]
How do I turn a string of numbers into a list on Python?
39,921,819
<p>I'm trying to figure out how many numbers in a text file are larger than 0.1. The text file has 1001 last names and numbers in the following format:</p> <pre><code>Doe 5 Anderson 0.3 Smith 6 </code></pre> <p>I figured out how to separate the numbers but i'm having trouble converting my string of numbers into a lis...
1
2016-10-07T16:20:26Z
39,922,283
<p>From your description, and code snippet, you seem to have a file that has a space separated name an number like so:</p> <pre><code>Name1 0.5 Name2 7 Name3 11 </code></pre> <p>In order to get a sum of how many number are greater than 0.1, you can do the following:</p> <pre><code>result = sum(float(line.split()[1])...
0
2016-10-07T16:47:21Z
[ "python" ]
How do I turn a string of numbers into a list on Python?
39,921,819
<p>I'm trying to figure out how many numbers in a text file are larger than 0.1. The text file has 1001 last names and numbers in the following format:</p> <pre><code>Doe 5 Anderson 0.3 Smith 6 </code></pre> <p>I figured out how to separate the numbers but i'm having trouble converting my string of numbers into a lis...
1
2016-10-07T16:20:26Z
39,958,072
<p>The other answers tell you how to count the occurrences which are greater than 0.1, but you may want to have the numbers in a list so that they can be used for other purposes. To do that, you need a small modification to your code:</p> <pre><code>with open('last.txt', 'r') as infile: lines = infile.readlines()...
0
2016-10-10T12:14:22Z
[ "python" ]
Managing multiple lists with multiple tuples
39,921,863
<p>I have approximately 2000 lines of data in the following format:</p> <pre><code>. . [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Ayiesha Woods'), (5, 10, 'DOB', 'July 2 , 1979'), (10, 13, 'LOC', 'Long Island'), (13, 16, 'LOC', 'New York')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Craig Rivera'), (7, 12, 'DOB', 'October 10 , ...
1
2016-10-07T16:22:45Z
39,922,218
<p>Break down the problem into simple steps:</p> <ol> <li>Loop through the list of records. </li> <li>Each record consists of a list of tuples in somewhat arbitrary order.</li> <li>Look through each tuple in the record (loop) looking for NAME and DOB.</li> <li>When found add the desired data from the tuple to result.<...
2
2016-10-07T16:43:33Z
[ "python", "list", "python-3.x" ]
Managing multiple lists with multiple tuples
39,921,863
<p>I have approximately 2000 lines of data in the following format:</p> <pre><code>. . [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Ayiesha Woods'), (5, 10, 'DOB', 'July 2 , 1979'), (10, 13, 'LOC', 'Long Island'), (13, 16, 'LOC', 'New York')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Craig Rivera'), (7, 12, 'DOB', 'October 10 , ...
1
2016-10-07T16:22:45Z
39,922,303
<p>I would recommend writing a helper function which retrieves the information from your data. I am also assuming that you are working with a list of lists of tuples.</p> <pre><code> test_list = [[(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Ayiesha Woods'), (5, 10, 'DOB', 'July 2 , 1979'), (10, 13, 'LOC', 'Long Island'...
1
2016-10-07T16:48:31Z
[ "python", "list", "python-3.x" ]
Managing multiple lists with multiple tuples
39,921,863
<p>I have approximately 2000 lines of data in the following format:</p> <pre><code>. . [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Ayiesha Woods'), (5, 10, 'DOB', 'July 2 , 1979'), (10, 13, 'LOC', 'Long Island'), (13, 16, 'LOC', 'New York')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Craig Rivera'), (7, 12, 'DOB', 'October 10 , ...
1
2016-10-07T16:22:45Z
39,922,606
<p>You can do this:</p> <pre><code>temp = "DateOFBirth" text = [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Vance Trimble'), (5, 7, 'LOC', 'Harrison'), (7, 9, 'LOC', 'Arkansas'), (9, 14, 'DOB', 'July 6 , 1913')] rel = [] for i in text: if 'NAME' in i: rel.append(i[i.index('NAME')+1]) rel.append(temp) ...
1
2016-10-07T17:07:43Z
[ "python", "list", "python-3.x" ]
Collapse / expand text in Text widget
39,921,864
<p>I have a Text widget with ALOT of information being printed to it. Id like to have sections of it minimizable so I can hide information until I need it. </p> <pre><code>from tkinter import * main = Tk() list1 = ['blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\n" 'blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\...
2
2016-10-07T16:22:56Z
39,922,936
<p>You can configure a text tag to hide a range of characters. You can then hide or show a range of characters by applying or removing this tag. If you want to insert a button into the text, you will need to use the <code>window_create</code> method of the text widget.</p> <p>You'll have to write the code to apply or ...
3
2016-10-07T17:32:08Z
[ "python", "python-3.x", "tkinter" ]
Using .asof and MultiIndex in Pandas
39,922,050
<p>I've seen this question asked a few times but with no answer. The short version:</p> <p>I have a pandas <code>DataFrame</code> with a two-level <code>MultiIndex</code> index; both levels are integers. How can I use <code>.asof()</code> on this <code>DataFrame</code>?</p> <p>Long version:</p> <p>I have a <code>D...
1
2016-10-07T16:34:07Z
39,923,806
<p>I read your post multiple times and I think I finally get what you are trying to achieve.</p> <p>try this:</p> <pre><code>df['weekday'] = df.index.weekday df['hour_of_day'] = df.index.hour weekly_model = df.groupby(['weekday', 'hour_of_day']).mean() dates = pd.date_range('2015/1/1', '2015/12/31 23:59', freq='H') <...
1
2016-10-07T18:34:06Z
[ "python", "pandas" ]
Delete entire node using lxml
39,922,132
<p>I have a an xml document like the following:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/...
1
2016-10-07T16:38:55Z
39,922,424
<p>First, grab the root node. Since it is <code>&lt;project ... &gt;</code> (vs <code>&lt;project .../&gt;</code>) the "parent" element of <code>dependencies</code> is <code>project</code>. Example from the documentation:</p> <blockquote> <p>import xml.etree.ElementTree as ET<br> tree = ET.parse('country_data.xm...
1
2016-10-07T16:56:02Z
[ "python", "xml", "lxml" ]
Delete entire node using lxml
39,922,132
<p>I have a an xml document like the following:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/...
1
2016-10-07T16:38:55Z
39,924,138
<p>You can create a dict mapping for your namespace(s), find the <em>node</em> then call <em>root.remove</em> passing the node, you don't call <em>.remove</em> on the node:</p> <pre><code>x = """&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xs...
1
2016-10-07T18:58:04Z
[ "python", "xml", "lxml" ]
Python selenium click element while displayed
39,922,247
<p>I'm scraping a dynamic page that requires the user to click a "Load More Results" button several times in order to get all data. Is there a better way to approach the task of clicking on an element while displayed? </p> <pre><code>def clickon(xpath): try: element = driver.find_element_by_xpath(xpath) ...
1
2016-10-07T16:45:29Z
39,922,345
<p>I suspect you are asking this question because the current solution is slow. This is mostly because you have these hardcoded <code>time.sleep()</code> delays which wait for more than they usually should. To tackle this problem I'd start using <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" ...
3
2016-10-07T16:51:13Z
[ "python", "selenium", "selenium-webdriver" ]
Python segmentation fault on Thread switch
39,922,369
<p>I'm developing an application that should check if the computer is able to ping google.com. To do that I use python subprocess module and issue a call as shown in the code below:</p> <pre><code>response = subprocess.call("ping -c 1 google.com -q", shell=True) </code></pre> <p>However, after running for some time,...
2
2016-10-07T16:52:23Z
39,922,946
<p>You're rearming the timer from within the timer itself, which may not be too good (recursive call with threads, argh). You don't really need <code>Timer</code> if you're not too demanding about ping delay accuracy: you could start a thread that loops and pings google periodically like this:</p> <pre><code>import th...
0
2016-10-07T17:33:03Z
[ "python", "multithreading", "segmentation-fault" ]
TraCI value doesn't tally with output
39,922,382
<p>When I do <code>traci.edge.getWaitingTime(str(-108542273))</code> at the last step of the simulation, I get a value of <code>0</code> from it. </p> <p>But when I went to verify on the edge-based state dump generated and found out that the value was <code>15</code>. Why does the traci value not reflect that? Do the...
0
2016-10-07T16:53:08Z
39,966,732
<p>The meandata output is aggregated over time, so it shows the sum of the waiting times in the interval. The TraCI call however only returns the waiting time on the given edge in the last simulation step (no aggregation over time).</p>
0
2016-10-10T21:04:23Z
[ "python", "sumo" ]
Missing levels in python contour plot
39,922,504
<p>I am trying to plot contours with specified levels of a simulated velocity field, my values are in the range of [75,150], and I specified my levels to be <code>levels=[75,95,115,135,150]</code>,but it's only giving me the 95,115,135 lines. I checked my 2d array and I do have points with values of 75 and 150 lying on...
3
2016-10-07T17:00:17Z
39,922,697
<p>You are missing the 75 and 150 contours because those values are never crossed in the array. The value 150 exists, and the value 75(.000000000000014) exist, but those are the min and max values. Contours describe a line/surface <strong>boundary</strong>.</p> <pre><code>#levels modified levels=[76,95,115,135,149] cs...
0
2016-10-07T17:14:38Z
[ "python", "matplotlib", "contour" ]
OOP : Trying to design a good class structure
39,922,553
<p>Follow up code snippet review question I posted: <a href="http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances">http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances</a></p> <p>This is homework so off the bat I am not asking to do it for me but to cla...
1
2016-10-07T17:03:57Z
39,922,895
<p>One of the big ideas of using inheritance is to be able to re-use code.. If you have a large body of functions that are the same for several classes, having one parent class that holds those functions allows you to only write them once, and to modify them all at the same time. for example, if you want to implement c...
1
2016-10-07T17:28:53Z
[ "python", "python-3.x", "oop", "inheritance" ]
OOP : Trying to design a good class structure
39,922,553
<p>Follow up code snippet review question I posted: <a href="http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances">http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances</a></p> <p>This is homework so off the bat I am not asking to do it for me but to cla...
1
2016-10-07T17:03:57Z
39,922,947
<p>Let's start with the Shapes class. In the __init__ , you have to set the attributes. First you need 2 parameters other than self. You can use the same names as the attributes or pick different names.</p> <pre><code>class Shapes(attributes): def __init__(self, length, width): self.length = length ...
1
2016-10-07T17:33:04Z
[ "python", "python-3.x", "oop", "inheritance" ]
OOP : Trying to design a good class structure
39,922,553
<p>Follow up code snippet review question I posted: <a href="http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances">http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances</a></p> <p>This is homework so off the bat I am not asking to do it for me but to cla...
1
2016-10-07T17:03:57Z
39,923,122
<p>I do not want to give answers that are too specific, because homework, but here is an example which I think might orient you in the right direction.</p> <p>In Object Oriented Programming, there is the concept of polymorphism: when instances of many different subclasses are related by some common superclass. You oft...
2
2016-10-07T17:45:43Z
[ "python", "python-3.x", "oop", "inheritance" ]
OOP : Trying to design a good class structure
39,922,553
<p>Follow up code snippet review question I posted: <a href="http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances">http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances</a></p> <p>This is homework so off the bat I am not asking to do it for me but to cla...
1
2016-10-07T17:03:57Z
39,923,323
<p>Be careful not to confuse "attributes" with "methods". There is an @property syntax which wraps attribute access within a method call, but you should ignore that for now.</p> <pre><code>class Shapes(attributes): def __init__(self): </code></pre> <p>For this part, just absorb the arguments here. e.g:</p> <pre...
1
2016-10-07T18:00:25Z
[ "python", "python-3.x", "oop", "inheritance" ]
OOP : Trying to design a good class structure
39,922,553
<p>Follow up code snippet review question I posted: <a href="http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances">http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances</a></p> <p>This is homework so off the bat I am not asking to do it for me but to cla...
1
2016-10-07T17:03:57Z
39,923,382
<pre><code>class Vehicle(object): #class variable shared between all instances of objects. number_of_vehicles = 0 def __init__(self,length,width,color,wheels): self.length = length self.width = width self.color = color self.wheels = wheels Vehicle.number_of_vehicle...
1
2016-10-07T18:04:28Z
[ "python", "python-3.x", "oop", "inheritance" ]
Python - creating directories after button click
39,922,632
<p>I'm a bit new to Python so forgive the ignorance.</p> <p>I am currently toying with a little app to create directories based on user input. I have made a bash script that does this perfectly but would like put a GUI on it.</p> <p>So far i have got this function that works:</p> <pre><code>def on_TextEntry_activate...
-1
2016-10-07T17:09:06Z
39,922,755
<p>For user interfaces in python, use TKInter to create that button you want. run -pip install TkInter as TK </p> <p>which version of python are you on?</p>
-1
2016-10-07T17:18:38Z
[ "python", "linux", "glade" ]
Python - creating directories after button click
39,922,632
<p>I'm a bit new to Python so forgive the ignorance.</p> <p>I am currently toying with a little app to create directories based on user input. I have made a bash script that does this perfectly but would like put a GUI on it.</p> <p>So far i have got this function that works:</p> <pre><code>def on_TextEntry_activate...
-1
2016-10-07T17:09:06Z
39,979,617
<p>Don't worry chaps, i've got the answer to my question now! (see below):</p> <pre><code>def on_createbutton_clicked(self, widget): ParentFolder = self.ui.ParentFolder.get_text() os.chdir("/home/user/folder/") if not os.path.exists(ParentFolder): os.makdirs(ParentFolder), 0755) os.chdir(Parent...
0
2016-10-11T14:28:28Z
[ "python", "linux", "glade" ]
Apply style map when writing a DataFrame to html with pandas
39,922,633
<p>I want to output a pandas DataFrame to .html and also apply a style. The documentation* gives this example which displays negative values as red.</p> <pre><code>import pandas as pd import numpy as np np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.rand...
1
2016-10-07T17:09:14Z
39,925,277
<p>I don't know if it is the best (or idiomatic) way to do that, but it should work:</p> <pre><code>with open('html.html', 'w') as html: html.write(s.render()) </code></pre>
2
2016-10-07T20:25:55Z
[ "python", "pandas" ]
tox tests, use setup.py extra_require as tox deps source
39,922,650
<p>I want to use setup.py as the authority on packages to install for testing, done with extra_requires like so:</p> <pre><code>setup( # ... extras_require={ 'test': ['pytest', ], }, ) </code></pre> <p>Tox only appears to be capable of <a href="https://testrun.org/tox/latest/example/basic.html#dep...
0
2016-10-07T17:10:30Z
39,922,651
<p>I've come up with a nasty hack that seems to work</p> <pre><code># tox.ini ... [testenv] ... install_command = pip install {opts} {packages} {env:PWD}[test] </code></pre> <p>The defualt <code>install_command</code> is <code>pip install {opts} {packages}</code>, unfortunately <code>{packages}</code> is a required a...
0
2016-10-07T17:10:30Z
[ "python", "testing", "setup.py", "tox" ]
Python : How to make a quiz and check if the answer is correct?
39,922,668
<p>I'm taking a computer science course and I recently took a test and there was a question whose answer I did not know and I want to know how to do it.</p> <p>The Question/problem was Ask the user 7 questions. Then check how many were correct and then give a percentage. I am familiar with input and operators and var...
-4
2016-10-07T17:12:13Z
39,922,818
<p>How about something like this (pseudo-code)?</p> <pre><code>qa = [ ('Q1', 'A1'), ('Q2', 'A2'), ] num_correct = 0 for q,a in qa: user_answer = raw_input(q) if user_answer == a: num_correct += 1 print 'Total questions:', len(qa) print 'Total correct:', num_correct </code></pre> <p>Y...
1
2016-10-07T17:23:48Z
[ "python", "input" ]
Python : How to make a quiz and check if the answer is correct?
39,922,668
<p>I'm taking a computer science course and I recently took a test and there was a question whose answer I did not know and I want to know how to do it.</p> <p>The Question/problem was Ask the user 7 questions. Then check how many were correct and then give a percentage. I am familiar with input and operators and var...
-4
2016-10-07T17:12:13Z
39,937,040
<p>Ive Done It, Code of What I Did Below:</p> <p>q1=int(input("What Is 5+1 ")) if q1==6: print ("Correct") corr1=int(1) else: print ("Wrong, The Answer Is: 6") corr1=int(0)</p> <p>q2=int(input("What Is 6+9 ")) if q2==15: print ("Correct") corr2=int(1) else: print ("Wrong, The Answer Is: 11...
0
2016-10-08T20:27:40Z
[ "python", "input" ]
python changes values of list
39,922,701
<p>I am fairly new to Python so please be patient, this is probably simple. I am trying to build an adjacency list representation of a graph. In this particular representation I decided to use list of lists where the first value of each sublist represents the tail node and all other values represent head nodes. For exa...
1
2016-10-07T17:14:53Z
39,925,753
<p>The problem is in the lines</p> <pre><code> if choice_flag_1: g_tmp.append(arc) </code></pre> <p>When you append arc, you are appending a shallow copy of the inner list. Replace with a new list like so</p> <pre><code> if choice_flag_1: g_tmp.append([arc[0],arc[1]]) </code></pre>
1
2016-10-07T21:01:37Z
[ "python", "list", "graph" ]
Is random.sample truly random?
39,922,724
<p>I have a list with <code>155k</code> files. When I <code>random.sample(list, 100)</code>, while the results are not the same from the previous sample, they look similar. </p> <p>Is there a better alternative to <code>random.sample</code> that returns a new list of random 100 files? </p> <pre><code>folders = get_al...
-2
2016-10-07T17:16:14Z
39,922,890
<p>You may need to seed the generator. See <a href="https://docs.python.org/2/library/random.html#random.seed" rel="nofollow">here</a> in the Documentation.</p> <p>Just call <code>random.seed()</code> before you get the samples.</p>
-1
2016-10-07T17:28:26Z
[ "python", "python-3.x", "random" ]
Is random.sample truly random?
39,922,724
<p>I have a list with <code>155k</code> files. When I <code>random.sample(list, 100)</code>, while the results are not the same from the previous sample, they look similar. </p> <p>Is there a better alternative to <code>random.sample</code> that returns a new list of random 100 files? </p> <pre><code>folders = get_al...
-2
2016-10-07T17:16:14Z
39,923,025
<p>For purposes like randomly selecting elements from a list, using <code>random.sample</code> suffices, true randomness isn't provided and I'm unaware if this is even theoretically possible. </p> <p><code>random</code> (by default) uses a <a href="https://en.wikipedia.org/wiki/Pseudorandom_number_generator" rel="nofo...
2
2016-10-07T17:38:52Z
[ "python", "python-3.x", "random" ]
Encountering an Error in Robot Framework after tests run
39,922,763
<p>I am new to using Robot Framework, and have run into a problem while running tests on a Jenkins server. The tests are passing, and after the tests run I get the following message:</p> <blockquote> <p>Output: /opt/bitnami/apps/jenkins/jenkins_home/jobs/Robot Test/workspace/robot/Results/output.xml</p> <p>[ E...
-1
2016-10-07T17:19:17Z
39,962,145
<p>In case it helps anyone who finds this, it appears that my issue was that some of the modules I installed using pip were not installed using "sudo". This led a few of them to install the module, but with errors. When I uninstalled them, and then reinstalled them with sudo, this error has not reappeared. </p>
0
2016-10-10T15:56:11Z
[ "python", "python-2.7", "selenium", "jenkins", "robotframework" ]
Python - Determine Tic-Tac-Toe Winner
39,922,967
<p>I am trying to write a code that determines the winner of a tic-tac-toe game. (This is for a college assignment)</p> <p>I have written the following function to do so:</p> <blockquote> <p>This code only checks for horizontal lines, I haven't added the rest. I feel that this is something that needs a bit of hardc...
0
2016-10-07T17:34:57Z
39,923,094
<p>You can just make a set of each row, and check its length. If it contains only one element, then the game has been won.</p> <pre><code>def returnWinner(board): for row in board: if len(set(row)) == 1: return row[0] return -1 </code></pre> <p>This will return "O" if there is a full line ...
2
2016-10-07T17:43:52Z
[ "python", "arrays", "loops", "boolean", "break" ]
Python - Determine Tic-Tac-Toe Winner
39,922,967
<p>I am trying to write a code that determines the winner of a tic-tac-toe game. (This is for a college assignment)</p> <p>I have written the following function to do so:</p> <blockquote> <p>This code only checks for horizontal lines, I haven't added the rest. I feel that this is something that needs a bit of hardc...
0
2016-10-07T17:34:57Z
39,923,218
<p>One way to do this would be to create a set (a generator function would be even better) of all the possible index combinations to check for the win. Then loop through those index combinations and check if they all contain the same value, if so, then it's a win.</p> <pre><code>def win_indexes(n): # Rows for...
1
2016-10-07T17:52:29Z
[ "python", "arrays", "loops", "boolean", "break" ]
Pandas group-by and sum
39,922,986
<p>I am using this data frame:</p> <pre><code>Fruit Date Name Number Apples 10/6/2016 Bob 7 Apples 10/6/2016 Bob 8 Apples 10/6/2016 Mike 9 Apples 10/7/2016 Steve 10 Apples 10/7/2016 Bob 1 Oranges 10/7/2016 Bob 2 Oranges 10/6/2016 Tom 15 Oranges 10/6/2016 Mike 57 Oranges 10/6/2016 ...
4
2016-10-07T17:36:25Z
39,923,012
<p>use the sum() method</p> <pre><code>df.groupby(['Name','Fruit']).sum() Out[31]: Number Fruit Name Apples Bob 16 Mike 9 Steve 10 Grapes Bob 35 Tom 87 Tony 15 Oranges Bob 67 Mike 57 Tom ...
3
2016-10-07T17:37:45Z
[ "python", "pandas", "dataframe", "group-by", "aggregate" ]
Pandas group-by and sum
39,922,986
<p>I am using this data frame:</p> <pre><code>Fruit Date Name Number Apples 10/6/2016 Bob 7 Apples 10/6/2016 Bob 8 Apples 10/6/2016 Mike 9 Apples 10/7/2016 Steve 10 Apples 10/7/2016 Bob 1 Oranges 10/7/2016 Bob 2 Oranges 10/6/2016 Tom 15 Oranges 10/6/2016 Mike 57 Oranges 10/6/2016 ...
4
2016-10-07T17:36:25Z
39,923,111
<p>You can use <code>groupby</code> and <code>sum</code>:</p> <pre><code>df.groupby(['Name', 'Fruit']).sum() Number Name Fruit Bob Apples 16 Grapes 35 Oranges 67 Mike Apples 9 Oranges 57 Steve Apples 10 Tom Grapes 87 Orang...
1
2016-10-07T17:44:57Z
[ "python", "pandas", "dataframe", "group-by", "aggregate" ]
Pandas group-by and sum
39,922,986
<p>I am using this data frame:</p> <pre><code>Fruit Date Name Number Apples 10/6/2016 Bob 7 Apples 10/6/2016 Bob 8 Apples 10/6/2016 Mike 9 Apples 10/7/2016 Steve 10 Apples 10/7/2016 Bob 1 Oranges 10/7/2016 Bob 2 Oranges 10/6/2016 Tom 15 Oranges 10/6/2016 Mike 57 Oranges 10/6/2016 ...
4
2016-10-07T17:36:25Z
39,923,815
<p>Both the other answers accomplish what you want. </p> <p>You can use the <code>pivot</code> functionality to arrange the data in a nice table</p> <pre><code>df.groupby(['Fruit','Name'],as_index = False).sum().pivot('Fruit','Name').fillna(0) Name Bob Mike Steve Tom Tony Fruit A...
1
2016-10-07T18:35:14Z
[ "python", "pandas", "dataframe", "group-by", "aggregate" ]
Pandas group-by and sum
39,922,986
<p>I am using this data frame:</p> <pre><code>Fruit Date Name Number Apples 10/6/2016 Bob 7 Apples 10/6/2016 Bob 8 Apples 10/6/2016 Mike 9 Apples 10/7/2016 Steve 10 Apples 10/7/2016 Bob 1 Oranges 10/7/2016 Bob 2 Oranges 10/6/2016 Tom 15 Oranges 10/6/2016 Mike 57 Oranges 10/6/2016 ...
4
2016-10-07T17:36:25Z
39,931,909
<p>Also you can use agg function,</p> <pre><code>df.groupby(['Name', 'Fruit'])['Number'].agg('sum') </code></pre>
0
2016-10-08T11:40:26Z
[ "python", "pandas", "dataframe", "group-by", "aggregate" ]
Obtain difference between two lists of objects in Python using hash
39,923,021
<p>My objective is to get the difference between two lists containing objects.</p> <p>I have implemented a class named Branch and overwritten its <code>__eq__</code> and <code>__ne__</code> methods as follows:</p> <pre><code>class Branch(object): def __str__(self): return self.name def __eq__(self, o...
2
2016-10-07T17:38:25Z
39,923,304
<p>You would need to implement <em>hash</em>, what you choose to is up to you but the following would work:</p> <pre><code>def __hash__(self): return hash((self.valueFrom , self.valueTo , self.inService)) </code></pre> <p>All you need to implement is hash and eq:</p> <pre><code>class Branch(object): def __i...
4
2016-10-07T17:58:41Z
[ "python", "list", "object", "set", "difference" ]
Pygame: Adding a background
39,923,023
<p>I'm making a project for my senior year. Its a game where i can move a user. I would like to add a background that goes behind all the pictures i've blitted. I've searched everywhere but i can't seem to find the solution. Could anybody help?</p> <pre><code>import pygame import os class Player(object): def __...
0
2016-10-07T17:38:33Z
39,923,273
<p>A background image is no different from any other image. Just .blit it first.</p>
1
2016-10-07T17:55:50Z
[ "python", "python-2.7" ]
How to sum up each element in array list?
39,923,028
<p>Having a bit of writing out the code. </p> <p>For example, if I have an array of: </p> <pre><code>a = ([0, 0, 1, 2], [0, 1, 1, 0], [0, 0, 1, 0], [1, 0, 1, 3], [0, 1, 1, 3]) </code></pre> <p>if I want to add first element of each item, </p> <p>as in to return a list of 0 + 0 + 0 + 1 + 0, 0 + 1 + 0, 0 + 0 ... </p>...
-2
2016-10-07T17:39:12Z
39,923,137
<pre><code>sum(zip(*a)[0]) </code></pre> <p><code>zip</code> is a function that takes any number of n-length sequences and returns n tuples (among other things). The first of these tuples has the elements that came first in the tuples passed to <code>zip</code>. <code>sum</code> adds them together.</p> <p>EDIT:</p>...
6
2016-10-07T17:46:48Z
[ "python", "arrays", "list" ]
How to sum up each element in array list?
39,923,028
<p>Having a bit of writing out the code. </p> <p>For example, if I have an array of: </p> <pre><code>a = ([0, 0, 1, 2], [0, 1, 1, 0], [0, 0, 1, 0], [1, 0, 1, 3], [0, 1, 1, 3]) </code></pre> <p>if I want to add first element of each item, </p> <p>as in to return a list of 0 + 0 + 0 + 1 + 0, 0 + 1 + 0, 0 + 0 ... </p>...
-2
2016-10-07T17:39:12Z
39,923,149
<pre><code>a = ([0, 0, 1, 2], [0, 1, 1, 0], [0, 0, 1, 0], [1, 0, 1, 3], [0, 1, 1, 3]) </code></pre> <p>Try using list comprehensions:</p> <pre><code>sum([item[0] for item in a]) </code></pre> <p>The line above takes the first element of each list in the tuple, then puts it into a temporary list. We then call sum on ...
0
2016-10-07T17:47:28Z
[ "python", "arrays", "list" ]
Speed up numpy summation between big arrays
39,923,085
<p>I have a code running operations on <code>numpy</code> arrays. While linear algebra operations seem fast, I now am finding a bottleneck in a different issue: the summation of two distinct arrays. In the example below <code>WE3</code> and <code>T1</code> are two <code>1000X1000X1000</code> arrays. First I calculate ...
0
2016-10-07T17:42:54Z
39,923,433
<p>That <code>np.einsum('i,j,k-&gt;ijk', wE, wE, wE)</code> part isn't doing any sum-reduction and is essentially just broadcasted elementwise multiplication. So, we can replace that with something like this -</p> <pre><code>wE[:,None,None] * wE[:,None] * wE </code></pre> <p>Runtime test -</p> <pre><code>In [9]: # S...
1
2016-10-07T18:08:45Z
[ "python", "arrays", "numpy" ]
Speed up numpy summation between big arrays
39,923,085
<p>I have a code running operations on <code>numpy</code> arrays. While linear algebra operations seem fast, I now am finding a bottleneck in a different issue: the summation of two distinct arrays. In the example below <code>WE3</code> and <code>T1</code> are two <code>1000X1000X1000</code> arrays. First I calculate ...
0
2016-10-07T17:42:54Z
39,923,660
<blockquote> <p>Is there any known reason why the summation of those arrays is such slower than the calculation of WE3?</p> </blockquote> <p>The arrays <code>wE3</code>, <code>T1</code> and <code>a</code> each require 8 gigabytes of memory. You are probably running out of physical memory, and <a href="http://server...
1
2016-10-07T18:24:19Z
[ "python", "arrays", "numpy" ]
Speed up numpy summation between big arrays
39,923,085
<p>I have a code running operations on <code>numpy</code> arrays. While linear algebra operations seem fast, I now am finding a bottleneck in a different issue: the summation of two distinct arrays. In the example below <code>WE3</code> and <code>T1</code> are two <code>1000X1000X1000</code> arrays. First I calculate ...
0
2016-10-07T17:42:54Z
39,927,739
<p>You should really use Numba's Jit (just in time compiler) for this. It is a purely numpy pipeline, which is perfect for Numba.</p> <p>All you have to do is throw that above code into a function, and put an @jit decorater on top. It gets speedups close to Cython. </p> <p>However, as others have pointed out, it ap...
0
2016-10-08T01:19:10Z
[ "python", "arrays", "numpy" ]
Python3, nested dict comparison (recursive?)
39,923,152
<p>I'm writing a program to take a .csv file and create 'metrics' for ticket closure data. Each ticket has one or more time entries; the goal is to grab the 'delta' (ie - time difference) for <code>open</code> -> <code>close</code> and <code>time_start</code> -> <code>time_end</code> on a PER TICKET basis; these are no...
0
2016-10-07T17:47:33Z
39,925,585
<p>The problem here is that with a nested loop like the one you implemented you double-examine the same ticket. Let me explain it better:</p> <pre><code>ticket_list = [111111, 111111, 666666, 777777] # lets simplify considering the ids only # I'm trying to keep the same variable names for i, key1 in enumerate(ticket_...
2
2016-10-07T20:48:44Z
[ "python", "list", "csv", "dictionary", "recursion" ]