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
pyinstaller with matplotlib backend_wxagg and hashlib md5
38,534,398
<p>A colleague of mine is having an issue building a python app we're working on together. We've been able to isolate the issue and replicate with the following code:</p> <pre><code>print "before import" from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg print "after import" </code></pre> <p>We're both ...
0
2016-07-22T19:58:12Z
39,252,650
<p>I had the same error when trying to build a frozen binary with cx_Freeze. After trying a lot of desperate hacks, like patching <code>hashlib.py</code>, I finally got rid of the error message by excluding <code>hashlib</code> altogether. </p> <p>In cx_Freeze it looks like:</p> <pre><code>… excludes = ["collection...
0
2016-08-31T14:41:37Z
[ "python", "matplotlib", "pyinstaller" ]
Python Inheritance suitability of using subclass to produce plot after setting plot properties in parent
38,534,400
<p>I am trying to write a simple Python matplotlib plotting Class that will set up formatting of the plot as I would like. To do this, I am using a class and a subclass. The parent generates an axis and figure, then sets all axis properties that I would like. Then the <code>child</code> generates the plot itself - scat...
0
2016-07-22T19:58:28Z
38,534,702
<p>I think the main issue is that your subclass violates the <a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow">Liskov Substitution Principle</a>. Also see <a href="https://lostechies.com/derickbailey/2009/02/11/solid-development-principles-in-motivational-pictures/" rel="nofollow">he...
1
2016-07-22T20:21:20Z
[ "python", "class", "matplotlib", "plot" ]
Python Inheritance suitability of using subclass to produce plot after setting plot properties in parent
38,534,400
<p>I am trying to write a simple Python matplotlib plotting Class that will set up formatting of the plot as I would like. To do this, I am using a class and a subclass. The parent generates an axis and figure, then sets all axis properties that I would like. Then the <code>child</code> generates the plot itself - scat...
0
2016-07-22T19:58:28Z
38,573,613
<p>You should prefer composition to inheritance wherever possible. I would make a function that creates the plot and another that draws on it.</p> <pre><code>def create_plot(dims, pad): fig = plt.figure(figsize=(8.5, 11)) ax = fig.add_axes(dims) ax.set_axisbelow(True) ax.tick_params(axis='x', pad=pad, ...
1
2016-07-25T17:02:17Z
[ "python", "class", "matplotlib", "plot" ]
Can't figure out how to multiply aliens in my pygame?
38,534,458
<p>So I've just been writing a dodger game for practice using pygame and python. I've read a lot of tutorials and looked at other similar games to help me. Basically, aliens come down from the top of the screen (they're supposed to be random sizes and speeds and their location is supposed to be random as well) and the...
1
2016-07-22T20:03:17Z
38,534,539
<p>You have a typo in <code>aliendAdd = 0</code>, it should be <code>alienAdd = 0</code>. This is causing you to keep incrementing <code>alienAdd</code> more and more and not hit your if statement of <code>alienAdd == 6</code> again.</p>
3
2016-07-22T20:09:46Z
[ "python", "pygame" ]
TVML catlog using TVML Templet Server installation
38,534,486
<p>To make a TVML App I got TVML Sample Catlog from Apple <a href="https://developer.apple.com/library/tvos/samplecode/TVMLCatalog/Introduction/Intro.html#//apple_ref/doc/uid/TP40016505-Intro-DontLinkElementID_2" rel="nofollow">https://developer.apple.com/library/tvos/samplecode/TVMLCatalog/Introduction/Intro.html#//ap...
0
2016-07-22T20:06:03Z
38,588,405
<p>I'm using http-server from npm. It's really easy to use, only need to write:<code>http-serve -p 9001</code></p> <p>You can find more here: <a href="https://www.npmjs.com/package/http-server" rel="nofollow">https://www.npmjs.com/package/http-server</a></p>
0
2016-07-26T11:16:33Z
[ "python", "xcode", "tvos", "tvml" ]
How can I debug a connection issue within VOLTTRON?
38,534,520
<p>I am connecting to an external VOLTTRON instance. I am not getting a response from the connection. What's the issue?</p> <p>I am writing a simple python script to connect to an external platform and retrieve the peers. If I get the serverkey, clientkey, and/or publickey incorrect I don't know how to determine wh...
0
2016-07-22T20:08:07Z
38,596,085
<p>The short answer: no, the client cannot determine why its connection to the server failed. The client will attempt to connect until it times out.</p> <p>Logs and debug messages on the <em>server side</em> can help troubleshoot a connection problem. There are three distinct messages related to key errors:</p> <ol> ...
1
2016-07-26T17:12:26Z
[ "python", "volttron" ]
csv value modification for certain cells on odd rows on a particular column
38,534,527
<p>Hi I'm trying to finish this small piece of code for modifying csv files, I've got this far with some help:</p> <p>edit... some more info.</p> <blockquote> <p>Basically what I’m looking to do is make some small changes to the csv file depending on the project and parent issue in JIRA. Python will then make the...
0
2016-07-22T20:08:48Z
38,535,353
<p>You want to use the row's index when comparing to <code>0</code>. Use <a href="https://docs.python.org/3/library/functions.html?highlight=enumerate#enumerate" rel="nofollow"><code>enumerate()</code></a>:</p> <pre><code>with open('out.csv', 'r') as infile, open('out1.csv', 'w') as outfile: for rowidx,row in enum...
0
2016-07-22T21:15:49Z
[ "python", "csv" ]
csv value modification for certain cells on odd rows on a particular column
38,534,527
<p>Hi I'm trying to finish this small piece of code for modifying csv files, I've got this far with some help:</p> <p>edit... some more info.</p> <blockquote> <p>Basically what I’m looking to do is make some small changes to the csv file depending on the project and parent issue in JIRA. Python will then make the...
0
2016-07-22T20:08:48Z
38,540,755
<p>A friend helped me last night and this is what they came up with:</p> <pre><code>with open(filepath, 'r') as infile, open('out.csv', 'w') as outfile: outfile.write(infile.readline()) # write out the 1st line for line in infile: cols = line.strip().split(',') cols[16] = project outfi...
0
2016-07-23T10:29:38Z
[ "python", "csv" ]
Selenium fails to select element by id
38,534,611
<p>Here is the HTML code of the element:</p> <pre><code>&lt;input maxlength="64" name="pskSecret" class="text" id="pskSecret" value="" size="32" type="text"&gt; </code></pre> <p>And here is my python code, which tries to select it:</p> <pre><code>self.driver.find_element_by_id("pskSecret").clear() self.driver.find_e...
1
2016-07-22T20:14:55Z
38,534,725
<p>May be when you are going to find element, it could not be load on the DOM due to timing issues. You should try using <code>WebDriverWait</code> to wait until element is visible as below :-</p> <pre><code>from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from seleni...
0
2016-07-22T20:23:10Z
[ "python", "selenium" ]
How to upload to Nexus using Maven in python
38,534,659
<p>I want to upload an artifact to Nexus using maven in a python script. I looked it up here: <a href="https://gist.github.com/adamv/705292" rel="nofollow">https://gist.github.com/adamv/705292</a></p> <p>and am doing the following way:</p> <pre><code>def local2(command, print_command=False): from subprocess impor...
1
2016-07-22T20:17:52Z
38,534,735
<p>(Linux) Search for the binary file for mvn:</p> <pre><code>$ which mvn /c/Maven/apache-maven-3.0.5-bin/apache-maven-3.0.5/bin/mvn </code></pre> <p>and set this in your script:</p> <pre><code>MAVEN_BINARY ='/c/Maven/apache-maven-3.0.5-bin/apache-maven-3.0.5/bin/mvn' </code></pre>
0
2016-07-22T20:24:09Z
[ "python", "maven", "nexus" ]
Add legend to networks plot to explain colouring of nodes
38,534,730
<p>I have a plot of a networkx graph in which edge-color depends on the weights assigned to the respective edges using the following code (with <code>a_netw</code> the nx.Graph):</p> <pre><code>a_netw_edges = a_netw.edges() a_netw_weights = [a_netw[source][dest]['weight'] for source, dest in a_netw_edges] a_netw_color...
3
2016-07-22T20:23:37Z
38,630,883
<p>I suggest you use the colorbar() command as shown below. I am providing an example Graph, see if it makes sense?</p> <p><a href="http://i.stack.imgur.com/dcFI1.png" rel="nofollow"><img src="http://i.stack.imgur.com/dcFI1.png" alt="enter image description here"></a></p> <pre><code>import networkx as nx import matpl...
2
2016-07-28T08:24:44Z
[ "python", "matplotlib", "networkx" ]
Why does returning this lamda expression result in a string?
38,534,799
<p>Good afternoon,</p> <p>I recently started learning Python 3.5.1, and am currently experimenting with <code>lambda</code> expressions. I tried setting up the simple method below.</p> <pre><code>def sum_double(a, b): return lambda a, b: a+b if a != b else (a+b)*2, a, b </code></pre> <p>All it is supposed to do is...
2
2016-07-22T20:29:30Z
38,534,822
<pre><code>sum_double = lambda a, b: a+b if a != b else (a+b)*2 </code></pre> <p><code>lambda</code> itself defines a function. A <code>def</code> is not required.</p> <p>In your case, a tuple consisting of the returned function, <code>a</code> and <code>b</code> is printed.</p>
2
2016-07-22T20:32:10Z
[ "python", "python-3.x", "lambda" ]
Why does returning this lamda expression result in a string?
38,534,799
<p>Good afternoon,</p> <p>I recently started learning Python 3.5.1, and am currently experimenting with <code>lambda</code> expressions. I tried setting up the simple method below.</p> <pre><code>def sum_double(a, b): return lambda a, b: a+b if a != b else (a+b)*2, a, b </code></pre> <p>All it is supposed to do is...
2
2016-07-22T20:29:30Z
38,534,825
<p>Well, you're not calling the <code>lambda</code> function and as such the return value is a tuple of the defined <code>lambda</code> function and the values of <code>a</code> and <code>b</code>.</p> <p>Change it to call the lambda before returning while supplying the arguments to it:</p> <pre><code>return (lambda ...
1
2016-07-22T20:32:27Z
[ "python", "python-3.x", "lambda" ]
Python random card dealer - face card counter doesn't count correctly
38,534,815
<p>I'm practicing writing this program for class. I have to deal cards until four aces are dealt and at the end, I also have to count how many face cards (jack, queen, king cards) were dealt. I didn't make a dictionary for the card names because my teacher specifically told us to do the random integer command. However,...
0
2016-07-22T20:31:49Z
38,535,142
<p>I think I found it. Consider the case where you have roll a face card. </p> <blockquote> <p>Let r = 11. </p> <p>rank -> 'Jack'</p> <p>suit -> anything</p> <p>print('Jack of whatever')</p> <p>increment f_counter</p> <p>// next iteration</p> <p>Let r = 1</p> <p>Fall through the if...
0
2016-07-22T20:59:37Z
[ "python" ]
Python random card dealer - face card counter doesn't count correctly
38,534,815
<p>I'm practicing writing this program for class. I have to deal cards until four aces are dealt and at the end, I also have to count how many face cards (jack, queen, king cards) were dealt. I didn't make a dictionary for the card names because my teacher specifically told us to do the random integer command. However,...
0
2016-07-22T20:31:49Z
38,535,146
<p>I made a few changes to your program. Let me know if this gives your desired output and I can explain the main changes. </p> <pre><code>rank = '' while a_counter &lt; 4: # This counts and tells the user of each card dealt that isn't an ace. r = random.randint(1,13) s = random.randint(1,4) t_counte...
0
2016-07-22T20:59:46Z
[ "python" ]
Diagonal Sprite Movement in Pygame, Python 3
38,534,817
<p>I'm currently making a game using Pygame, Python 3 and one of the bugs I have in it is they way shots move. The game is a 2D top-down shooter, and the code for the player shooting mechanic is below:</p> <p>(<code>player_rect</code> is the Rect for the player, bullet_speed is a pre-defined <code>int</code>)</p> <pr...
0
2016-07-22T20:31:55Z
38,535,036
<p>I don't know a whole lot about Pygame, but have you thought of storing your positions as non-integer values, only converting to integers on display? The internal representation can be more precise than what is displayed to the user.</p>
1
2016-07-22T20:51:16Z
[ "python", "python-3.x", "pygame", "sprite", "pygame-surface" ]
Sklearn Spectral Clustering error for inf or NaNs in matrix
38,535,008
<p>I'm using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralClustering.html" rel="nofollow">Spectral Clustering Library</a> and similarity matrix is its main argument. My matrix looks like:</p> <pre><code>[[ 1.00000000e+00 8.47085137e-01 8.49644498e-01 8.49746438e-01 2.9647345...
-1
2016-07-22T20:48:03Z
38,539,257
<p>NaN values arise <em>because</em> your matrix is not a similarity matrix: <strong>your data contains negative similarities</strong>! When taking the <code>sqrt</code> of these values you get <code>NaN</code>, hence the error.</p> <p>The warnings are not just for fun - matrix decomposition techniques have somre requ...
0
2016-07-23T07:21:37Z
[ "python", "numpy", "scikit-learn", "cluster-analysis" ]
Beautiful Soup 4 finding text within table
38,535,161
<p>I have been trying to use BS4 to scrape from <a href="http://www.nfl.com/draft/2012/tracker#dt-tabs:dt-by-position/dt-by-position-input:cb" rel="nofollow">this</a> web page. I cannot find the data I want (player names in the table, ie, "Claiborne, Morris").</p> <p>When I use:</p> <pre><code>soup = BeautifulSoup(r....
1
2016-07-22T21:01:08Z
38,536,863
<p>The table you're looking for is dynamically filled by JavaScript when the page is rendered. When you retrieve the page using e.g. <code>requests</code>, it only retrieves the original, unmodified page. This means that some elements that you see in your browser will be missing.</p> <p>The fact that you can find the ...
0
2016-07-23T00:09:10Z
[ "python", "html", "web-scraping", "python-requests", "bs4" ]
How/when to close a file in an object?
38,535,165
<p>I'm trying to design a class to manage video devices in Linux (<code>/dev/video*</code>).</p> <p>Because of my C++ background I naturally thought I could open the file in the constructor and close it in the destructor.</p> <p>Then later I learned python does not guarantee when/if the destructor is called.</p> <p>...
1
2016-07-22T21:01:31Z
38,535,845
<p>Go ahead and open the file in the constructor, it won't hurt anything.</p> <p>Python provides the <a href="https://www.python.org/dev/peps/pep-0343/" rel="nofollow"><code>with</code> statement</a> to allow setup and teardown of an object beyond construction/destruction. Your object must include an <code>__enter__</...
0
2016-07-22T22:00:10Z
[ "python" ]
Converting a generator expression (<genexpr>) to list?
38,535,171
<p>I'm doing some topic modeling and am looking to store some of the results of my analysis.</p> <pre><code>import pandas as pd, numpy as np, scipy import sklearn.feature_extraction.text as text from sklearn import decomposition descs = ["You should not go there", "We may go home later", "Why should we do your chores...
0
2016-07-22T21:02:01Z
38,535,302
<p>You're appending generator expressions to your list <code>topic_words</code>, so the first time you printed, the generator expressions are already exhausted. You can instead do:</p> <pre><code>topic_words = [] for t in nmf.components_: word_idx = np.argsort(t)[::-1][:20] topic_words.append([vocab[i] for i ...
3
2016-07-22T21:11:38Z
[ "python", "generator" ]
scikit-learn add training data
38,535,216
<p>I was looking at the training data available in <code>sklearn</code> at <a href="http://scikit-learn.org/stable/datasets/twenty_newsgroups.html" rel="nofollow">here</a>. As per documentation, it contains 20 classes of documents, based on some newsgroup collection. It does a fairly good job of classifying documents b...
0
2016-07-22T21:05:42Z
38,607,789
<p>Supposing your additional data has the following directory structure (if not, then this should be your first step, because it will make your life a lot easier as you can use the <code>sklearn</code> API to fetch the data, see <a href="http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_files.html"...
1
2016-07-27T08:32:46Z
[ "python", "machine-learning", "scipy", "scikit-learn" ]
Python formatting CSV with string and float and write
38,535,227
<p>How do you format a float to 2 decimal points with mixed data type? I'm fetching a table and writing rows to csv file. My data is (string, string, float, float, float...)</p> <pre><code> sql = 'select * from testTable' c.execute(sql) columnNames = list(map(lambda x: x[0], c.description)) result = c...
0
2016-07-22T21:06:17Z
38,535,833
<p>You need to change the 'result' list using list comprehension and ternary if-else in Python.</p> <p><code>result = [x if type(x) is str else format(x,'.2f') for x in result]</code></p>
1
2016-07-22T21:59:22Z
[ "python", "csv" ]
Python formatting CSV with string and float and write
38,535,227
<p>How do you format a float to 2 decimal points with mixed data type? I'm fetching a table and writing rows to csv file. My data is (string, string, float, float, float...)</p> <pre><code> sql = 'select * from testTable' c.execute(sql) columnNames = list(map(lambda x: x[0], c.description)) result = c...
0
2016-07-22T21:06:17Z
38,535,859
<p>You can iterate the result in order to parse only the floats values, and then you can use <code>writer.writerows(row)</code> to write row by row. Take a look <a href="http://stackoverflow.com/questions/17861152/cursor-fetchall-vs-listcursor-in-python">here</a> to know the different ways to iterate your <code>results...
1
2016-07-22T22:01:16Z
[ "python", "csv" ]
Can't import matplotlib even if it's installad
38,535,241
<p>I am running a sample python program on my Mac (El Capitan, 10.11.5)<br> I have a the default version of python installed (2.6) and on top of that I installed python 2.7 and 3.5. I need matplotlib on my 2.7 version. </p> <p>I installed it with pip (not pip3) and I don't know why it got installed on python 3.5. </p...
3
2016-07-22T21:07:08Z
38,543,032
<blockquote> <p>I have a the default version of python installed (2.6) and on top of that I installed python 2.7 and 3.5. I need matplotlib on my 2.7 version. </p> </blockquote> <p>that's genereally not a problem, however you need to make sure the python environments are not mixed up. </p> <blockquote> <p>I think...
1
2016-07-23T14:48:27Z
[ "python", "osx", "matplotlib", "pip" ]
Rendering Large Image in PyGame Causing Low Framerate
38,535,283
<p>I am trying to make a 'Runner' style game in PyGame (like Geometry Dash) where the background is constantly moving. So far everything works fine, but the rendering of the background images restricts the frame rate from exceeding 35 frames per second. Before I added the infinite/repeating background element, it could...
1
2016-07-22T21:10:18Z
38,536,196
<p>Have you tried using <code>convert()</code>? </p> <pre class="lang-py prettyprint-override"><code> bg = pygame.image.load('background.png').convert() </code></pre> <p>From the <a href="http://www.pygame.org/docs/ref/image.html#pygame.image.load" rel="nofollow">documentation</a>:</p> <blockquote> <p>You will ...
1
2016-07-22T22:38:34Z
[ "python", "pygame" ]
Can't get ngrok, and my python script to use the same port
38,535,332
<p>I imported flask into my python script, and I'm using ngrok to make it accessible. </p> <pre><code>The ASK_APPLICATION_ID has not been set. Application ID verification disabled. * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat The ASK_APPLICATION_ID has not been set. Application ID ...
0
2016-07-22T21:13:42Z
38,539,671
<p>start the flask application at 5000 port and then start ngrok</p> <pre><code>./ngrok http 5000 </code></pre> <p>ngrok will provide the url which then forwards requests to your app running at 5000</p>
0
2016-07-23T08:16:04Z
[ "python", "flask", "ngrok" ]
graphs from Altair are not displaying
38,535,357
<p>On Ubuntu x64, I just freshly installed Anaconda 3.</p> <p>I then installed <code>altair</code> via <code>conda</code> per <a href="https://github.com/ellisonbg/altair" rel="nofollow">these directions</a>. Then I run the example code:</p> <pre><code>from altair import * population = load_dataset('population') Cha...
0
2016-07-22T21:16:28Z
38,535,977
<p>Thanks to @cel, I found out the code cannot be run in the iPython console from Anaconda - it needs to be run from a Jupyter notebook.</p> <p>You have to run <code>jupyter notebook</code> in the terminal, then create a new iPython Notebook. Once the notebook is created, you can run your code interactively from the n...
1
2016-07-22T22:13:40Z
[ "python", "anaconda", "jupyter" ]
MongDB - queries a large collection
38,535,434
<p>I have 40 MM documents in my MongoDB collection (e.g. db.large_collection)</p> <p>I want to get all the distinct User_ID. </p> <p>I have created an Index on the field user_id but when I try to execute, it returns an error. </p> <pre><code>&gt; db.large_collection.count() 39894523 &gt; db.clean_tweets4.getIndexes...
0
2016-07-22T21:22:16Z
38,535,476
<p>find({}); means it returns everything. This is what you want. </p> <pre><code>db.collection.find({user_id:1}); </code></pre>
-1
2016-07-22T21:25:41Z
[ "python", "mongodb", "bigdata" ]
Numpy: operations on columns (or rows) of NxM array
38,535,444
<p>This may be a silly question, but I've just started using <em>numpy</em> and I have to figure out how to perform some simple operations.</p> <p>Suppose that I have the 2x3 array</p> <pre><code>array([[1, 3, 5], [2, 4, 6]]) </code></pre> <p>And that I want to perform some operation on the first column, for exam...
0
2016-07-22T21:23:03Z
38,535,502
<pre><code>arr # array([[1, 3, 5], # [2, 4, 6]]) arr[:,0] = arr[:,0] - 1 # choose the first column here, subtract one and # assign it back to the same column arr # array([[0, 3, 5], # [1, 4, 6]]) </code></pre>
0
2016-07-22T21:28:21Z
[ "python", "arrays", "numpy" ]
urllib—expressing what piece of JSON Data I desire
38,535,456
<p>Here is a big piece of JSON data that I fetch in my code below:</p> <pre><code>{ "status": 200, "offset": 0, "limit": 10, "count": 8, "total": 8, "url": "/v2/dictionaries/ldoce5/entries?headword=extra", "results": [ { "datasets": [ "ldoce5", "dictionary" ], "headw...
1
2016-07-22T21:24:11Z
38,535,564
<p><code>sense</code> is actually a list with a single element, a dictionary. The contained dictionary has your desired key-value pair.</p> <p>For example:</p> <pre><code>for item in data: sense = data['senses'][0] print(sense['definition']) </code></pre>
0
2016-07-22T21:33:12Z
[ "python", "json", "api", "python-3.x", "urlfetch" ]
Matplotlib stores .svg different than what is show on screen
38,535,459
<p>Here is an example. The next is what get's stored as a .png and this is how it displays on the screen and it is correct</p> <p><a href="http://i.stack.imgur.com/mmxiY.png" rel="nofollow"><img src="http://i.stack.imgur.com/mmxiY.png" alt="this is the image that looks right"></a></p> <p>and the next is the .svg whic...
0
2016-07-22T21:24:22Z
38,535,663
<p>Based on <a href="http://matplotlib.org/examples/images_contours_and_fields/interpolation_none_vs_nearest.html" rel="nofollow">http://matplotlib.org/examples/images_contours_and_fields/interpolation_none_vs_nearest.html</a> </p> <p><a href="http://stackoverflow.com/questions/12473511/what-does-matplotlib-imshowinte...
0
2016-07-22T21:42:39Z
[ "python", "svg", "matplotlib" ]
TfIdfVectorizer divides words to single characters?
38,535,475
<p>I am trying to find nearest neighbors in a set of descriptions. Descriptions usually contain 1-15 words that I am tokenizing using the scikit's TfIdfVectorizer. Then, with the same vectorizer, I am fitting the base description. However, it seems that the vectorizer divides this one to separate characters, rather tha...
0
2016-07-22T21:25:40Z
38,535,789
<p>Right, the answer was pretty simple for the amount of time I spent on it. I wrapped the <code>description</code> in a list and got the expected 10 results:</p> <pre><code>input_matrix = vectorizer.transform([description]) </code></pre>
0
2016-07-22T21:55:31Z
[ "python", "scikit-learn" ]
Call a class Object with Python(Tkinter)
38,535,498
<p>Currently I'm looking for a way to call a class object within Tkinter. Here is a sample code to which can be used. From this how could I call this within Tkinter?</p> <pre><code>root=Tk() root.geometry=(root, width=x, height=y) root.title("Let's do this!") class MyApp(): def Do_Good(): py_game=Label(ro...
-2
2016-07-22T21:27:49Z
38,535,598
<p>You call it like you do any other method on any other object: you create an instance, and call the method.</p> <pre><code>app = MyApp() ... app.Do_Good() </code></pre> <p>If you're asking how to call it from a callback, it's the same answer:</p> <pre><code>app = MyApp() ... button = Button(root, text="Do good!", ...
1
2016-07-22T21:35:59Z
[ "python", "python-2.7", "tkinter" ]
How to setup Emacs to use a given Python virtualenv?
38,535,499
<p>I use Emacs for a number of tasks and as I am starting to work with Python I would like to keep using Emacs to code in Python.</p> <p>I have set up a virtualenv for Python3, and it is working as desired. I also have Emacs 24.5 installed with the latest version of <a href="http://batsov.com/prelude/" rel="nofollow">...
0
2016-07-22T21:27:54Z
39,158,058
<p><a href="https://github.com/jorgenschaefer/elpy" rel="nofollow">Elpy</a> has support for virtual environments built in via <a href="https://github.com/jorgenschaefer/pyvenv" rel="nofollow">Pyenv</a>. Pyenv can also be installed as a standalone package. Pyenv <a href="https://github.com/jorgenschaefer/pyvenv/issues/6...
1
2016-08-26T03:58:12Z
[ "python", "emacs", "virtualenv", "emacs-prelude" ]
Stacked Bar Chart in Matplotlib; Series Are Overlaying Instead Of Stacking
38,535,520
<p>Struggling to figure this one out. I have a stacked bar chart that I'm trying to create with Python / Matplotlib and it seems to be overlaying the data instead of stacking resulting in different colors (i.e. red+yellow = orange instead of stacking red and yellow). Can anyone see what I'm doing wrong?</p> <p>Here's ...
1
2016-07-22T21:29:55Z
38,535,971
<p>You have to manually calculate position from which your <em>cats</em> bar will start (look at the <code>bottom</code> variable in my code when <em>cats</em> are plotting). You have to propose your own method to calculate position of <em>cats</em> bars depending on data in your dataframe.</p> <p>Your colors are mix...
0
2016-07-22T22:12:22Z
[ "python", "pandas", "matplotlib" ]
Making a combat system using classes
38,535,620
<p>I've been trying to implement a combat system in my text game. I thought I could just create instances in each of my scenes that have different <code>int</code> values to minimize hard-coding that the exercise from the book I have I think is trying to teach me. When I access the <code>TestRoom</code> class by dict i...
0
2016-07-22T21:38:22Z
38,535,651
<p>I'm not sure why you've made TestRoom inherit from those other three classes. That doesn't make sense; inheritance means an "is-a" relationship, but while a room might <em>contain</em> those things, it isn't actually any of those things itself.</p> <p>This is the source of your problem, as TestRoom has now inherite...
3
2016-07-22T21:41:47Z
[ "python", "python-2.7", "syntax", "typeerror" ]
Check if field exists in DNS record using scapy
38,535,638
<p>I am parsing DNS packets using scapy. Not all of the DNS Answer Records have all of the fields. For example, some Answers don't have rdata so </p> <pre><code>answer = packet.an[0].rdata </code></pre> <p>results in the error:</p> <pre><code>AttributeError: rdata </code></pre> <p>Is there a way of testing to see...
1
2016-07-22T21:40:47Z
38,535,743
<p>You could always do a try-except. Might not be as slick as what you're looking for, though.</p> <pre><code>try: answer = packet.an[0].rdata except AttributeError: # do something </code></pre>
1
2016-07-22T21:50:17Z
[ "python", "dns", "scapy" ]
Streaming with Tweepy: randomly getting 'TypeError: unsupported operand type(s) for +: 'int' and 'str'
38,535,687
<p>I'm using the Tweepy library to track a hashtag (I'm using the streaming API) and I save to a file on my hard drive after a certain number of records. My code works and I leave it running. After some time, I randomly get the following error</p> <pre><code>Exception in thread Thread-1: Traceback (most recent call la...
0
2016-07-22T21:45:08Z
38,536,383
<p>Can you add a minimal code on how you are passing your hashtag? This can be either related to the way you are feeding hashtag or an open issue in tweepy.</p> <p>This particular issue regarding streaming is very similar to what you are experiencing: <a href="https://github.com/tweepy/tweepy/issues/748" rel="nofollow...
0
2016-07-22T23:01:14Z
[ "python", "tweepy" ]
Parsing multi-level json file into Python dict
38,535,698
<p>I'm trying to parse a json file into a python dict (to make it copy-ready for Redshift).</p> <p>My intended output format is: </p> <pre><code>{col1:val1, col2:val2,..} {col1:val1, col2:val2,..} </code></pre> <p>The current format of the file is:</p> <pre><code>{"val0": {"col1":"val1", "col2":"val2",..}, "val0":...
-1
2016-07-22T21:46:02Z
39,253,947
<p>It sounds like you need a json array.</p> <pre><code>import json with open('example.json', 'r') as f: data = json.load(f) array_data = list(data.values()) print(array_data) # [{'col1': 'val1', 'col2': 'val2'}, # {'col1': 'val1', 'col2': 'val2'}] with open('array_result.json', 'w') as f...
1
2016-08-31T15:46:59Z
[ "python", "json", "parsing" ]
Add double quotes to string in python
38,535,707
<p>If my input text is</p> <pre><code>a b c d e f g </code></pre> <p>and I want my output text to be: (with the double quotes)</p> <pre><code>"a b c d e f g" </code></pre> <p>Where do I go after this step:</p> <pre><code>" ".join([a.strip() for a in b.split("\n") if a]) </code></pre>
-1
2016-07-22T21:46:39Z
38,535,752
<pre><code>'"%s"' % " ".join([a.strip() for a in s.split("\n") if a]) </code></pre>
2
2016-07-22T21:51:37Z
[ "python", "string" ]
Add double quotes to string in python
38,535,707
<p>If my input text is</p> <pre><code>a b c d e f g </code></pre> <p>and I want my output text to be: (with the double quotes)</p> <pre><code>"a b c d e f g" </code></pre> <p>Where do I go after this step:</p> <pre><code>" ".join([a.strip() for a in b.split("\n") if a]) </code></pre>
-1
2016-07-22T21:46:39Z
38,535,817
<p>You have successfully constructed a string without the quotes. So you need to add the double quotes. There are a few different ways to do this in Python:</p> <pre><code>&gt;&gt;&gt; my_str = " ".join([a.strip() for a in b.split("\n") if a]) &gt;&gt;&gt; print '"' + my_str + '"' #Use single quotes to surround the do...
5
2016-07-22T21:58:11Z
[ "python", "string" ]
Adding generated PDF to FileField fails; adding local PDF works
38,535,726
<p>I'm trying to generate a PDF file and to add it to a Django <code>FileField</code>. Nothing fancy, but I can't seem to get i</p> <p>When using a local file on my hard drive, everything works fine:</p> <pre><code>&gt;&gt;&gt; invoice = Invoice.objects.get(pk=153) &gt;&gt;&gt; local_file = open('my.pdf') &gt;&gt;&gt...
0
2016-07-22T21:48:22Z
38,535,865
<p><code>File()</code> is only a wrapper around Python's file object. It won't work with strings like your generated PDF. For that, you need the <a href="https://docs.djangoproject.com/en/1.9/ref/files/file/#the-contentfile-class" rel="nofollow">ContentFile class</a>. Try:</p> <pre><code>(...) djangofile = ContentFile...
1
2016-07-22T22:01:52Z
[ "python", "django" ]
subraction error
38,535,794
<p>I have a certain error in a speed testing program I have built in Python. My program works by taking a variable of 0, adding 1 and printing its value. It repeats this 10,000 times, and records how long this all takes. After the time is taken every 1,000 cycle, it is arranged into a graph, with the columns, "Cycles",...
0
2016-07-22T21:56:19Z
38,535,887
<p>In your second elif statement in your code snippet, it looks like you have a minus sign that should not be there:</p> <pre><code>elif(count == 5000): check5 = round(time() - start, 3) check5 -= [-] 0.4 Beep(850, 100) </code></pre> <p>This makes your program add 0.4 rather than subtract, whi...
2
2016-07-22T22:03:19Z
[ "python", "subtraction" ]
Looping over large sparse array
38,535,861
<p>Let's say I have a (sparse) matrix <code>M</code> size <code>(N*N, N*N)</code>. I want to select elements from this matrix where the outer product of <code>grid</code> (a <code>(n,m)</code> array, where <code>n*m=N</code>) is True (it is a boolean 2D array, and <code>na=grid.sum()</code>). This can be done as follow...
0
2016-07-22T22:01:22Z
38,538,601
<p>I don't know if it was a typo, or code error, but your example is missing an <code>iternext</code>:</p> <pre><code>R=[] it = np.nditer ( A, flags=['multi_index'] ) while not it.finished: if it[0]: R.append(M[it.multi_index]) it.iternext() </code></pre> <p>I think appending to a list is simpler and ...
1
2016-07-23T05:45:12Z
[ "python", "arrays", "numpy", "scipy" ]
Efficiently index a multidemnsional numpy array by another array
38,535,868
<p>I have an array <code>x</code> which specific values I would like to access, whose indices are given by another array.</p> <p>For example, <code>x</code> is </p> <pre><code>array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) </code></pre> <p>and th...
0
2016-07-22T22:01:58Z
38,535,919
<p>You can pass in an iterable of <code>axis0</code> coordinates and an iterable of <code>axis1</code> coordinates. See <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing" rel="nofollow">the Numpy docs here</a>.</p> <pre><code>i0, i1 = zip(*idxs) x[i0, i1] </code></pre> <p>...
3
2016-07-22T22:07:44Z
[ "python", "arrays", "numpy" ]
Two python pools, two queues
38,535,920
<p>I am trying to understand how pool and queue work in Python, and the following example doesn't work as expected. I expect the program to end, but it's stuck in an infinite loop because the second queue isn't getting emptied.</p> <pre><code>import multiprocessing import os import time inq = multiprocessing.Queue() ...
-1
2016-07-22T22:07:55Z
38,536,972
<p>This is a very odd way to use a <code>Pool</code>. The function passed to the constructor is called only once per process in the pool. It's intended for one-time initialization tasks, and is rarely used.</p> <p>As is, your <code>worker2</code> is called exactly twice, one time for each process in yout <code>p2</c...
3
2016-07-23T00:27:30Z
[ "python", "queue", "pool" ]
Pandas: Delete rows based on multiple columns values
38,535,931
<p>I have a dataframe with columns <code>A,B,C</code>. I have a list of tuples like <code>[(x1,y1), (x2,y2), ...]</code>. I would like to delete all rows that meet the following condition: <code>(B=x1 &amp;&amp; C=y1) | (B=x2 &amp;&amp; C=y2) | ...</code> How can I do that in pandas? I wanted to use the <code>isin</cod...
5
2016-07-22T22:09:36Z
38,536,020
<p>It will probably be more efficient to <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">use boolean indexing</a> than a bunch of calls to <code>DataFrame.drop</code>. This is because Pandas doesn't have to reallocate memory in each loop iteration.</p> <pre><code>m =...
0
2016-07-22T22:18:50Z
[ "python", "pandas" ]
Pandas: Delete rows based on multiple columns values
38,535,931
<p>I have a dataframe with columns <code>A,B,C</code>. I have a list of tuples like <code>[(x1,y1), (x2,y2), ...]</code>. I would like to delete all rows that meet the following condition: <code>(B=x1 &amp;&amp; C=y1) | (B=x2 &amp;&amp; C=y2) | ...</code> How can I do that in pandas? I wanted to use the <code>isin</cod...
5
2016-07-22T22:09:36Z
38,536,146
<p>Use pandas indexing</p> <pre><code>df.set_index(list('BC')).drop(tuples, errors='ignore').reset_index() </code></pre> <hr> <h3>Timing</h3> <pre><code>def linear_indexing_based(df, tuples): idx = np.array(tuples) BC_arr = df[['B','C']].values shp = np.maximum(BC_arr.max(0)+1,idx.max(0)+1) BC_IDs =...
5
2016-07-22T22:32:59Z
[ "python", "pandas" ]
Pandas: Delete rows based on multiple columns values
38,535,931
<p>I have a dataframe with columns <code>A,B,C</code>. I have a list of tuples like <code>[(x1,y1), (x2,y2), ...]</code>. I would like to delete all rows that meet the following condition: <code>(B=x1 &amp;&amp; C=y1) | (B=x2 &amp;&amp; C=y2) | ...</code> How can I do that in pandas? I wanted to use the <code>isin</cod...
5
2016-07-22T22:09:36Z
38,536,170
<p><strong>Approach #1</strong></p> <p>Here's a vectorized approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy's broadcasting</code></a> -</p> <pre><code>def broadcasting_based(df, tuples): idx = np.array(tuples) mask = (df.B.values == idx[:, None,...
4
2016-07-22T22:35:34Z
[ "python", "pandas" ]
Debugging from PyCharm to Visual Studio C++ code
38,536,062
<p>I'm currently trying to debug issues in <a href="https://github.com/BVLC/caffe/tree/windows" rel="nofollow">Caffe for Windows</a> PyCaffe.</p> <p>Because of a <a href="https://github.com/Microsoft/PTVS/issues/1439" rel="nofollow">bug in Python Tools for Visual Studio</a>, PTVS doesn't work so I'm using PyCharm and ...
0
2016-07-22T22:23:10Z
38,603,201
<p>We attach to one process and allow to set breakpoints within code that has not started from the VS debugger. But one important issue is that we often debug/run the app in the VS, for example, we debug the Web code that runs under IIS, we will attach to the IIS process or others. </p> <p>Your project is different fr...
0
2016-07-27T03:27:26Z
[ "python", "c++", "visual-studio", "debugging", "pycharm" ]
Youcompleteme plugin for vim fails to provide completion for error codes from errno.h
38,536,090
<p>I've never used vim at work, only starting to familiarize myself with it and so far like it very much.</p> <p>For <strong>YouCompleteMe</strong> plugin to work for my test project I took .ycm_extra_conf.py file from <a href="https://github.com/Valloric/ycmd/blob/master/cpp/ycm/.ycm_extra_conf.py" rel="nofollow">her...
0
2016-07-22T22:25:41Z
38,556,721
<p>By further googling I found out that macro completion can be obtained with (Ctrl-Space).</p>
1
2016-07-24T20:58:41Z
[ "python", "c++", "vim", "youcompleteme" ]
Tensorflow Deep and Wide Demo issue
38,536,155
<p>I tried to run the code directly from tensorflow's <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py" rel="nofollow">Deep and Wide demo repo</a>:</p> <p>There is an immediate issue with <code>urllib</code> which can easily be fixed by using <code>urllib....
2
2016-07-22T22:33:57Z
38,558,946
<p>urllib is for 2.7, try running it in 2.7 instead of 3.5.</p>
0
2016-07-25T02:37:40Z
[ "python", "tensorflow", "python-3.5" ]
Tensorflow Deep and Wide Demo issue
38,536,155
<p>I tried to run the code directly from tensorflow's <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py" rel="nofollow">Deep and Wide demo repo</a>:</p> <p>There is an immediate issue with <code>urllib</code> which can easily be fixed by using <code>urllib....
2
2016-07-22T22:33:57Z
39,523,280
<p>I had the same issue. This solved it.</p> <p>I had to install Tensorflow under Python 2.7. Here's how to do it with a virtual environment, using Conda:</p> <pre><code># Python 2.7 $ conda create -n tensorflow python=2.7 $ source activate tensorflow (tensorflow)$ # Your prompt should change # Linux/Mac OS X, Pyt...
0
2016-09-16T03:18:59Z
[ "python", "tensorflow", "python-3.5" ]
Simple way of excluding an element from a calculation on a list?
38,536,214
<p>For example I want to check the correlation coefficient between two lists like:</p> <pre><code>r = np.corrcoef(list25, list26)[0,1] </code></pre> <p>but I want to exclude -1's in the lists from the calculation. Is there a simple one-liner way of doing this instead of making a new copies of the lists and iterating ...
0
2016-07-22T22:40:06Z
38,536,239
<p>There is a one liner solution. It's creating a new list without the ones. It can be done using <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">List Comprehension</a>:</p> <pre><code>new_list = [x for x in old_list if x != -1] </code></pre> <p>it basically copies everything that...
1
2016-07-22T22:43:46Z
[ "python", "list" ]
Simple way of excluding an element from a calculation on a list?
38,536,214
<p>For example I want to check the correlation coefficient between two lists like:</p> <pre><code>r = np.corrcoef(list25, list26)[0,1] </code></pre> <p>but I want to exclude -1's in the lists from the calculation. Is there a simple one-liner way of doing this instead of making a new copies of the lists and iterating ...
0
2016-07-22T22:40:06Z
38,536,411
<p>Use a generator</p> <pre><code>def greater_neg_1(items): for item in items: if item&gt;-1: yield item </code></pre> <p>Usage:</p> <pre><code>&gt;&gt;&gt; L = [1,-1,2,3,4,-1,4] &gt;&gt;&gt; list(greater_neg_1(L)) [1, 2, 3, 4, 4] </code></pre> <p>or:</p> <pre><code>r = np.corrcoef(greater_...
1
2016-07-22T23:05:35Z
[ "python", "list" ]
Simple way of excluding an element from a calculation on a list?
38,536,214
<p>For example I want to check the correlation coefficient between two lists like:</p> <pre><code>r = np.corrcoef(list25, list26)[0,1] </code></pre> <p>but I want to exclude -1's in the lists from the calculation. Is there a simple one-liner way of doing this instead of making a new copies of the lists and iterating ...
0
2016-07-22T22:40:06Z
38,538,693
<p>If you actually want to remove the <code>-1</code> from the lists:</p> <pre><code>while -1 in list25: list25.remove(-1) </code></pre>
1
2016-07-23T05:57:53Z
[ "python", "list" ]
merge pandas csv in different directories
38,536,247
<p>I have csv files with same names in different directories and i want to merge them as a single csv.</p> <pre> dir1 abcd__diff.csv efgh__diff.csv dir2 abcd_diffhere.csv efgh_diffhere.csv operation dir1/abcd_diff.csv join dir2/abcd_diffhere.csv dir1/efgh_diff.csv join dir2/efgh_diffhere.csv </pre> <p...
2
2016-07-22T22:44:21Z
38,536,612
<p>Consider <code>zip()</code> on the two file name lists where a dictionary of dataframes are appended (avoiding 200 separate objects). Keys to dictionary would be unique filenames shared by each pair. Below assumes filename lists do not have directories just base names of files.</p> <pre><code>import os ... dfDict =...
2
2016-07-22T23:32:01Z
[ "python", "csv", "pandas", "join", "merge" ]
merge pandas csv in different directories
38,536,247
<p>I have csv files with same names in different directories and i want to merge them as a single csv.</p> <pre> dir1 abcd__diff.csv efgh__diff.csv dir2 abcd_diffhere.csv efgh_diffhere.csv operation dir1/abcd_diff.csv join dir2/abcd_diffhere.csv dir1/efgh_diff.csv join dir2/efgh_diffhere.csv </pre> <p...
2
2016-07-22T22:44:21Z
38,536,842
<p>Situate files like this</p> <pre><code>files1 = [] files2 = [] dir1path = './dir1/' dir2path = './dir2/' dir1 = os.listdir(dir1path) dir2 = os.listdir(dir2path) for f in dir1: fmatch = f.split('.csv')[0] + 'here.csv' if fmatch in dir2: files1.append(f) files2.append(fmatch) files1 = [o...
3
2016-07-23T00:06:07Z
[ "python", "csv", "pandas", "join", "merge" ]
Can't import Orekit - 'DLL load failed'
38,536,425
<p>I try to run Orekit library through python. I use Anaconda, as proposed in <a href="https://www.orekit.org/forge/projects/orekit-python-wrapper/wiki/Installation" rel="nofollow">official tutorial</a>. Unfortunately, I come across following error as soon as I try to <code>import orekit</code> in python 2.7 console:</...
0
2016-07-22T23:06:23Z
38,546,885
<p>The solution was to install jdk through Anaconda by:</p> <pre><code>conda install -c cyclus java-jdk </code></pre> <p>I found it in official <a href="https://www.orekit.org/wws/arc/orekit-users/2016-07/msg00001.html" rel="nofollow">mailing list thread</a>.</p>
0
2016-07-23T22:15:53Z
[ "java", "python", "anaconda" ]
Find rolling 52 week high on daily stock market data in pandas
38,536,453
<p>This seems like a simple question (and answer) but I'm having trouble with it.</p> <p>The issue:</p> <p>I have a pandas dataframe full of OHLC data. I want to find the rolling 52 week high throughout the dataframe.</p> <p>My dataset is from yahoo. You can pull the same data down with the folllowing code to get d...
1
2016-07-22T23:09:47Z
38,536,645
<p>If your data has business-day frequency then there should be roughly 5 rows per week. So 52 weeks would roughly correspond to <code>window=52*5</code>.</p> <p>Of course, there might be a few other days missing due to holidays. To be more accurate, you could use <code>asfreq('D')</code> to change the frequency fro...
2
2016-07-22T23:35:53Z
[ "python", "pandas" ]
mongoengine - filter by "OR" on a single field in a single query
38,536,515
<p>Here's a (really) rough example of what I'm looking for - given a document with the following schema:</p> <pre><code>from mongoengine import Document, StringField, DateTimeField class Client(Document): name = StringField() activated_on = DateTimeField(required=False) </code></pre> <p>How would I query it ...
0
2016-07-22T23:18:37Z
38,537,127
<p>You can use <a href="http://docs.mongoengine.org/guide/querying.html#advanced-queries" rel="nofollow">Q class</a> :</p> <pre><code>from mongoengine.queryset.visitor import Q as MQ Client.objects(MQ(activated_on__exists=False)|MQ(activated_on__lte=datetime.datetime(2016,7,22))) </code></pre>
0
2016-07-23T00:58:29Z
[ "python", "mongoengine" ]
grab headers from multiple tsv/csv files
38,536,539
<p>I have a list of tsv files where I am looking to grab column headers for all the files.</p> <pre><code>with open(os.path.abspath('reference/file.tsv'), 'rU') as file: reader = csv.reader(file) row1 = next(reader) </code></pre> <p>Currently, this snippet only reads 1 file where I have a list of files that...
0
2016-07-22T23:21:29Z
38,536,689
<p>The <code>files</code> variable in your code is the content of the <code>reference</code> folder, meaning all files and subfolders of the folder. They are returned in a list of strings, containing only the file or subfolder name. This means that you'll have to prefix the path yourself.</p> <p>Example:</p> <pre><co...
1
2016-07-22T23:42:19Z
[ "python", "csv" ]
grab headers from multiple tsv/csv files
38,536,539
<p>I have a list of tsv files where I am looking to grab column headers for all the files.</p> <pre><code>with open(os.path.abspath('reference/file.tsv'), 'rU') as file: reader = csv.reader(file) row1 = next(reader) </code></pre> <p>Currently, this snippet only reads 1 file where I have a list of files that...
0
2016-07-22T23:21:29Z
38,536,713
<p>I try this and it works.</p> <pre><code>import os import csv dir_path = os.path.abspath('reference/') files = os.listdir(dir_path) for f in files: with open(dir_path +'/'+f, 'rU') as file: reader = csv.reader(file) row1 = next(reader) print row1 </code></pre>
1
2016-07-22T23:46:35Z
[ "python", "csv" ]
How to set locale for all children of python app?
38,536,543
<p>I have written an app indicator in python for Ubuntu desktop, which calls several external programs via subprocess. It works fine under English locale , but breaks with others. </p> <p>I know that there is a way to do <code>subprocess.call( ['command','arg1','arg3'], env=new_env_dict)</code> however I am intereste...
2
2016-07-22T23:22:00Z
38,539,274
<p>So far I have not found a way to globally tell all <code>subprocess</code> calls to use specific environment , so I decided to go with single function that only takes list of arguments , and locale set as shown in <a href="http://stackoverflow.com/a/13404327/3701431">related post</a> but with slight variation.</p> ...
1
2016-07-23T07:23:10Z
[ "python", "subprocess", "locale" ]
passing soap envelope in Python works on urllib but not on requests
38,536,769
<p>I'm passing a soap envelope in Python2 with urllib and it works fine, but upon upgrading to Python3 and requests, the transaction fails. The specific error on the failure is, "The server cannot service the request because the media type is unsupported." Here are the content/commands for each:</p> <h1>Python2/urllib...
0
2016-07-22T23:55:41Z
38,536,848
<p>Wow... I figured it out as soon as I posted my question: apparently headers cannot simply be a positional argument in requests like they can in urllib--you have to specify <code>headers=</code> and voila!</p> <p>I changed this: <code>request = requests.post(self._url, xml, request_headers)</code></p> <p>to this: <...
0
2016-07-23T00:07:10Z
[ "python", "soap", "http-headers" ]
Django template tag search through for-loop looking for specific object with default if not found
38,536,797
<p>I'm passing a queryset of people to my django template, some of which have been assigned a "seat" and others that haven't. Seats can be assigned to no one and therefore remain empty. For each seat, I want the template to loop through the queryset looking for someone in that seat. If the for loop doesn't find anyone ...
0
2016-07-22T23:59:30Z
38,536,847
<p>Yes, because <a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#for-empty" rel="nofollow">for...empty</a> works like that. It basically can't know if your seat is empty or not, for that you need to implement your own logic. </p> <p>I don't know the details of your model, but guessing from your e...
0
2016-07-23T00:07:07Z
[ "python", "html", "django", "django-templates" ]
Django template tag search through for-loop looking for specific object with default if not found
38,536,797
<p>I'm passing a queryset of people to my django template, some of which have been assigned a "seat" and others that haven't. Seats can be assigned to no one and therefore remain empty. For each seat, I want the template to loop through the queryset looking for someone in that seat. If the for loop doesn't find anyone ...
0
2016-07-22T23:59:30Z
38,547,259
<p>John Gordon's comment made me realize I shouldn't try to do too much in the template itself. In the view I created a list called "seats" and filled the appropriate seats, and then passed it to the template:</p> <pre><code>seats = [] for n in range(4): try: seats.append(students.objects.get(s...
0
2016-07-23T23:19:16Z
[ "python", "html", "django", "django-templates" ]
Get the latest non NaN values of timeseries for each identifier in pandas
38,536,829
<p>I am stuck on how to get the latest non-NaN values of a DataFrame for unique identifiers. So I have a Pandas DataFrame with a column of IDs, values, and years, similar to this:</p> <pre><code> | ID | Values | Year ------------------------- 0 | A | 4.0 | 2016 1 | B | NaN | 2016 2 | C | NaN | 2016 3...
3
2016-07-23T00:04:17Z
38,536,870
<p>You were sooo close. Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>ffill()</code></a>:</p> <pre><code>df.pivot(index='Year',columns='ID',values='Values').ffill().values[-1] </code></pre> <p>Result:</p> <pre><code>array([ 4., 2., 1., 1.]) <...
3
2016-07-23T00:10:23Z
[ "python", "pandas" ]
Get the latest non NaN values of timeseries for each identifier in pandas
38,536,829
<p>I am stuck on how to get the latest non-NaN values of a DataFrame for unique identifiers. So I have a Pandas DataFrame with a column of IDs, values, and years, similar to this:</p> <pre><code> | ID | Values | Year ------------------------- 0 | A | 4.0 | 2016 1 | B | NaN | 2016 2 | C | NaN | 2016 3...
3
2016-07-23T00:04:17Z
38,536,879
<p>This should do it:</p> <pre><code>df.ix[df.groupby('ID').Values.apply(lambda x: x.first_valid_index())] </code></pre> <p><a href="http://i.stack.imgur.com/3ifr2.png" rel="nofollow"><img src="http://i.stack.imgur.com/3ifr2.png" alt="enter image description here"></a></p>
2
2016-07-23T00:11:52Z
[ "python", "pandas" ]
Get the latest non NaN values of timeseries for each identifier in pandas
38,536,829
<p>I am stuck on how to get the latest non-NaN values of a DataFrame for unique identifiers. So I have a Pandas DataFrame with a column of IDs, values, and years, similar to this:</p> <pre><code> | ID | Values | Year ------------------------- 0 | A | 4.0 | 2016 1 | B | NaN | 2016 2 | C | NaN | 2016 3...
3
2016-07-23T00:04:17Z
38,536,949
<p>Another <code>groupby</code> option:</p> <p>If the data is already sorted by <code>'Year'</code> descending, like in the example data:</p> <pre><code>df.groupby('ID')['Values'].first() </code></pre> <p>If the data isn't already sorted:</p> <pre><code>df.sort_values(by='Year').groupby('ID')['Values'].last() </cod...
3
2016-07-23T00:23:31Z
[ "python", "pandas" ]
Add docstring to a namedtuple field
38,536,959
<p>I know it is possible to add docstring for namedtuples by subclassing it, e.g.</p> <pre><code>from collections import namedtuple NT = namedtuple('NT', ['f1', 'f2', 'f3']) class NTWithDoc(NT): """ DOCSTRING """ __slots__ = () </code></pre> <p>Now I wish to add docstring for f1, f2, and f3. Is there a way of...
1
2016-07-23T00:25:31Z
38,537,118
<p>I'm not sure if there is a good way to do this on python2.x. On python3.x, you can swap out the <code>__doc__</code> directly:</p> <pre><code>$ python3 Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "licens...
1
2016-07-23T00:56:42Z
[ "python", "namedtuple" ]
Python Tkinter OptionMenu Arguments
38,536,999
<p>I have a somewhat OCD trait where I like to explicit specify what arguments are being set to what values. For example, given a function:</p> <pre><code>def func(a, b): return a+b </code></pre> <p>Anytime I call on the above function in my code, I always write:</p> <pre><code>func(a=6, b=7) </code></pre> <p>I...
0
2016-07-23T00:33:04Z
38,541,956
<p>Unfortunately, the <code>OptionMenu</code> widget is somewhat poorly implemented. Regardless of your preferences, the optionmenu isn't designed to accept keyword arguments for the first three parameters <code>master</code>, <code>variable</code>, and <code>value</code>. They must be presented in that order as positi...
1
2016-07-23T12:46:45Z
[ "python", "tkinter", "optionmenu" ]
Googe drive api - no support for map export (python)
38,537,063
<p>Using the python api client I can export google docs using <code>export</code> or <code>export_media</code> and non-google doc material with <code>get_media</code>.</p> <p>Maps saved in the user account are unexportable. <code>export</code> returns the error</p> <p><code>HttpError: &lt;HttpError 403 ... returned ...
0
2016-07-23T00:46:33Z
38,616,818
<p>You can use <code>Drive.About.get</code> to determine the export formats available for each Google MIME type:</p> <pre><code>GET https://www.googleapis.com/drive/v3/about?fields=exportFormats&amp;key={YOUR_API_KEY} { "exportFormats": { "application/vnd.google-apps.form": [ "application/zip" ], "applicati...
0
2016-07-27T15:06:22Z
[ "python", "google-drive-sdk" ]
AttributeError: 'module' object has no attribute '__version__'
38,537,125
<p>I have installed LDA plibrary (using pip) I have a very simple test code (the next two rows)</p> <blockquote> <p>import lda</p> <p>print lda.datasets.load_reuters()</p> </blockquote> <p>But i keep getting the error </p> <blockquote> <p>AttributeError: 'module' object has no attribute 'datasets'</p> </blo...
0
2016-07-23T00:58:01Z
38,537,431
<p>Do you have a module named <code>lda.py</code> or <code>lda.pyc</code> in the current directory?</p> <p>If so, then your import statement is finding that module instead of the "real" lda module.</p>
0
2016-07-23T01:59:40Z
[ "python", "module", "dataset", "attributeerror", "lda" ]
Zip through a list and get every pair of items
38,537,188
<p>I would like to zip through a list of strings as below</p> <pre><code>collections = [u'Room Designers', u'BCRF', u'House'] </code></pre> <p>What I would like to achieve is 6 combinations of the three elements in the list - </p> <pre><code>("Room Designers", "BCRF"), ("Room Designers", "House"), ("BCRF", "House"),...
1
2016-07-23T01:09:31Z
38,537,199
<p>If you wanted to do it the way you've written, you need to omit the final <code>zip</code> call because that will break the strings up into their individual characters and pair <em>those</em> up. </p> <pre><code>zipall = [(i,j) for i in collections for j in collections if i!=j] # [(u'Room Designers', u'BCRF'), (u'...
1
2016-07-23T01:12:45Z
[ "python", "string", "zip" ]
How can I write the argument name from Python argparse to a file?
38,537,217
<p>I want to use argparse to write the argument names &amp; values it receives to a file. I have this so far:</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument("--infile", help = "seed file", default = 'test') parser.add_argument("--lang", help="wiki language bigram", default = 'en...
0
2016-07-23T01:16:22Z
38,537,273
<p>Have you tried</p> <pre><code>print(args) # the default Namespace display format </code></pre> <p>or</p> <pre><code>print(vars(args)) </code></pre> <p><code>vars(args)</code> is a dictionary, which you can display in a number of different ways. You could convert it to a list of tuples (<code>.items()</code>...
1
2016-07-23T01:25:17Z
[ "python", "argparse", "with-statement" ]
How to find element based on text and class with Selenium?
38,537,223
<p>I have an html table, and I want to find the <code>td</code> element in <code>tbody</code> based on the text and if it doesn't contain a certain class. It should ignore anything in <code>thead</code> even if the text is present.</p> <pre><code>... &lt;div id="mytable"&gt; &lt;div&gt; &lt;table&gt; ...
2
2016-07-23T01:17:10Z
38,537,246
<p>You are on the right track. <a href="https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/contains" rel="nofollow"><code>contains()</code></a> is a function and expects 2 arguments to be passed in - a string where to look and a substring - what to look. Fix your expression:</p> <pre><code>"//div/table/tbody...
0
2016-07-23T01:20:51Z
[ "python", "python-2.7", "selenium", "xpath", "selenium-webdriver" ]
Optimizing min function for changing lists
38,537,346
<p>I am dealing with a problem where I need to keep track of the minimum number in a list. However, this list is constantly diminishing, say like from a million elements to a single element. I was looking for a way to avoid checking the minimum value everytime I got a one element smaller list. Like keeping track of the...
0
2016-07-23T01:41:01Z
38,537,423
<p>Let's say your program would take some time to sort that list</p> <pre><code>a = [10,9,10,8,7,6,5,4,3,2,1,1,1,0] # you're just removing a = sorted(a) #sort ascending # then you remove stuff from your list # but always a[0] is minimum element min = a[0] #you must be careful, there must be at least one item so che...
1
2016-07-23T01:57:37Z
[ "python", "algorithm", "performance" ]
pandas the row data transform to the column data
38,537,399
<p>I have a datafram like :</p> <pre><code>user_id category view collect 1 1 a 2 3 2 1 b 5 9 3 2 a 8 6 4 3 a 7 3 5 3 b 4 2 6 3 c 3 0 7 4 e 1 4 </code></pre> <p>how to change it to a new dataframe ,each user_id can appear once,then the category with t...
1
2016-07-23T01:50:48Z
38,537,440
<p>The desired result can be obtained by <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="nofollow">pivoting <code>df</code></a>, with values from <code>user_id</code> becoming the index and values from <code>category</code> becoming a column level:</p> <pre><code>import numpy as np import pan...
1
2016-07-23T02:01:27Z
[ "python", "pandas" ]
How to share a variable between two python scripts run seperately
38,537,405
<p>I'm an extreme noob to python, so If there's a better way to do what I'm asking please let me know.</p> <p>I have one file, which works with flask to create markers on a map. It has an array which stores these said markers. I'm starting the file through command prompt, and opening said file multiple times. Basicall...
0
2016-07-23T01:52:48Z
38,537,488
<p>Your description is kind of confusing, but if I understand you correctly, one way of doing this would be to keep the value of the variable in a separate file.</p> <p>When a script needs the value, read the value from the file and add one to it. If the file doesn't exist, use a default value of 1. Finally, rewrite...
1
2016-07-23T02:13:29Z
[ "python", "arrays", "variables" ]
How to share a variable between two python scripts run seperately
38,537,405
<p>I'm an extreme noob to python, so If there's a better way to do what I'm asking please let me know.</p> <p>I have one file, which works with flask to create markers on a map. It has an array which stores these said markers. I'm starting the file through command prompt, and opening said file multiple times. Basicall...
0
2016-07-23T01:52:48Z
38,537,524
<p>I think you could use <code>pickle.dump(your array, file)</code> to serie the data(your array) intoto a file. And at next time running the script, you could just load the data back with <code>pickle.dump(your array, file)</code></p>
0
2016-07-23T02:20:31Z
[ "python", "arrays", "variables" ]
How to share a variable between two python scripts run seperately
38,537,405
<p>I'm an extreme noob to python, so If there's a better way to do what I'm asking please let me know.</p> <p>I have one file, which works with flask to create markers on a map. It has an array which stores these said markers. I'm starting the file through command prompt, and opening said file multiple times. Basicall...
0
2016-07-23T01:52:48Z
38,537,583
<p>What you seem to be looking for is some form of inter-process communication. In terms of python, each process has its own memory space and its own variables meaning that if I ran.</p> <pre><code>number += 1 print(number) </code></pre> <p>Multiple times then I would get 1,2..5 on a new line. No matter how many time...
2
2016-07-23T02:32:10Z
[ "python", "arrays", "variables" ]
Invalid block tag. Did you forget to register or load this tag?
38,537,464
<p>Getting an invalid block tag message <code>Invalid block tag on line 2: 'out'. Did you forget to register or load this tag?</code> but don't know why. Here's my setup:</p> <p>graphs.html</p> <pre><code>{% out %} </code></pre> <p>views.py</p> <pre><code>out = 'something to say' template = loader.get_template('viz...
2
2016-07-23T02:06:01Z
38,537,520
<p>I think you want to try {{ out }} instead of {% out %}.</p>
7
2016-07-23T02:19:42Z
[ "python", "html", "django" ]
unable to install cairosvg on centos 6
38,537,532
<p>when executing sudo pip install cairosvg on Centos getting following error</p> <pre><code> self.run_setup(setup_script, setup_base, args) File "/usr/lib/python2.6/site-packages/setuptools/command/easy_install.py", line 949, in run_setup raise DistutilsError("Setup script exited with %s" % (v.args[0],)) distuti...
0
2016-07-23T02:22:25Z
38,540,686
<p>CentOS 6.8 - 64</p> <pre><code># yum install libffi-devel.x86_64 # pip install cairosvg . . Installing collected packages: pycparser, cffi, cairocffi, cairosvg Running setup.py install for pycparser Running setup.py install for cffi Running setup.py install for cairocffi Running setup.py install for cairos...
0
2016-07-23T10:22:26Z
[ "python", "svg", "centos", "cairo" ]
Use __float__ with non-float type
38,537,551
<p>Per my <a href="http://stackoverflow.com/q/38533476/3928184">question from earlier today</a> (which was wonderfully answered, and I appreciate everyone's insight), I've <a href="https://github.com/bjd2385/fftconvolve/blob/master/operalist.py" rel="nofollow">extended that small class</a> for the heck of it to almost ...
1
2016-07-23T02:26:31Z
38,537,777
<p>Unfortunately, you can't. I can't find any precise wording on this, but <a href="https://docs.python.org/3/reference/datamodel.html#object.__complex__" rel="nofollow">the documentation states</a>:</p> <blockquote> <p>Called to implement the built-in functions complex(), int(), float() and round(). Should return...
1
2016-07-23T03:14:33Z
[ "python", "list" ]
Run commands on python
38,537,572
<p>I'm trying to create a script to automatically compile apache. Sadly on my work I need to compile each an every apache I install.<br> So, I came up with this little code to run a command:</p> <pre><code>print("Source location %s" % source_location) print("Configure command %s" % configure_command) config = subproce...
0
2016-07-23T02:30:24Z
38,537,587
<p>You can use <code>os.chdir</code> to change the current directory of your script to be the same as the directory which contains the source code.</p> <pre><code>os.chdir(source_location) </code></pre> <p>Alternately, you could change <code>configure_command</code> to first change directories using <code>cd</code> p...
1
2016-07-23T02:32:47Z
[ "python", "apache", "python-3.x" ]
How to continue onto the next object in a word list after the nth loop
38,537,607
<p>Sorry for the confusing title, but basically I have two word list files and I want them to print out as show below.</p> <p>One text file is formatted like this:</p> <pre><code>1 12 123 </code></pre> <p>And the other is like this:</p> <pre><code>Test1 Test2 Test3 </code></pre> <p>I am trying to achieve this in t...
0
2016-07-23T02:37:56Z
38,537,703
<p>Something like this? Open both files and for every line in file one print five in file two:</p> <pre><code>with open('file1.txt', 'r') as f1: with open('file2.txt', 'r') as f2: for line1 in f1: i = 0 for line2 in f2: i += 1 print(line2.rstrip('\n')...
1
2016-07-23T02:57:56Z
[ "python", "python-2.7" ]
scipy's cdist incompatible with Sympy symbols
38,537,627
<p>I realised today that sympy's matrix symbols in a vector (for multiple partial element-wise derivatives over a covariance matrix) was incompatible with scipy's cdist during the the optimize.minimize process, as it assumes actual use of numbers when making the function call (fair enough).</p> <p>It first runs into t...
1
2016-07-23T02:42:50Z
38,541,729
<p>As you've found, scipy.distance.cdist does not handle arbitrary objects. You'll need to implement Euclidean norm yourself.</p>
1
2016-07-23T12:20:41Z
[ "python", "optimization", "scipy", "sympy" ]
scipy's cdist incompatible with Sympy symbols
38,537,627
<p>I realised today that sympy's matrix symbols in a vector (for multiple partial element-wise derivatives over a covariance matrix) was incompatible with scipy's cdist during the the optimize.minimize process, as it assumes actual use of numbers when making the function call (fair enough).</p> <p>It first runs into t...
1
2016-07-23T02:42:50Z
38,579,090
<p>You can get the norm of a SymPy matrix expression by first converting it to an explicit matrix object, then using the norm method. </p> <pre><code>In [13]: A = MatrixSymbol("A", 1, 3) In [14]: A.as_explicit().norm() Out[14]: __________________________ ╱ 2 2 2 ╲╱ │A₀₀│ + │...
1
2016-07-25T23:53:55Z
[ "python", "optimization", "scipy", "sympy" ]
Remove rows from Pandas DataFrame based on index condition
38,537,753
<p>I have a dataframe like this:</p> <pre><code> 0 1 2 3 4 19238V105 NaN NaN NaN NaN NaN 91731X102 NaN NaN NaN 2450900.0 996600.0 97X1 NaN NaN NaN N...
2
2016-07-23T03:11:01Z
38,537,886
<p>Try this:</p> <pre><code>df[df.index.str.len() &gt;= 9] </code></pre>
1
2016-07-23T03:34:56Z
[ "python", "pandas", "dataframe" ]
Joining Python dict with MySQL table
38,537,855
<p>Is there a way to perform an SQL query that joins a MySQL table with a dict-like structure that is not in the database but instead provided in the query?</p> <p>In particular, I regularly need to post-process data I extract from a database with the respective exchange rates. Exchange rates are not stored in the dat...
2
2016-07-23T03:28:21Z
38,538,171
<p>This solution doesn't use a 'join', but does combine the data from Python into SQL via a case statement. You could generate the sql you want in python (as a string) that includes these values in a giant case statement. </p> <p>You give no details, and don't say which version of Python, so it's hard to provide usef...
1
2016-07-23T04:30:39Z
[ "python", "mysql", "sql" ]
Set logging levels
38,537,905
<p>I'm trying to use the standard library to debug my code:</p> <p>This works fine:</p> <pre><code>import logging logging.basicConfig(level=logging.info) logger = logging.getLogger(__name__) logger.info('message') </code></pre> <p>I can't make work the logger for the lower levels: </p> <pre><code>logging.basicConfi...
1
2016-07-23T03:38:29Z
38,537,983
<p>What Python version? That workd for me in 3.4. But note that <a href="https://docs.python.org/3.4/library/logging.html#logging.basicConfig" rel="nofollow">basicConfig()</a> won't effect the root handler if it's already setup:</p> <blockquote> <p>This function does nothing if the root logger already has handlers c...
1
2016-07-23T03:55:08Z
[ "python", "logging" ]
Set logging levels
38,537,905
<p>I'm trying to use the standard library to debug my code:</p> <p>This works fine:</p> <pre><code>import logging logging.basicConfig(level=logging.info) logger = logging.getLogger(__name__) logger.info('message') </code></pre> <p>I can't make work the logger for the lower levels: </p> <pre><code>logging.basicConfi...
1
2016-07-23T03:38:29Z
38,538,348
<p>I use the following setup for logging</p> <h2>Yaml based config</h2> <p>Create a yaml file called <strong>logging.yml</strong> like this</p> <pre><code>version: 1 formatters: simple: format: "%(name)s - %(lineno)d - %(message)s" complex: format: "%(asctime)s - %(name)s - %(lineno)d - ...
0
2016-07-23T05:02:46Z
[ "python", "logging" ]
How can I detect the method to request data from this site?
38,537,941
<p><strong>UPDATE:</strong> I've put together the following script to use the url for the XML <em>without the time-code-like suffix</em> as recommended in the <a href="http://stackoverflow.com/a/38538127/3904031">answer below</a>, and report the downlink powers which clearly fluctuate on the website. I'm getting three ...
1
2016-07-23T03:46:16Z
38,538,127
<p>Using a random number (or a timestamp...) in a get parameter tricks the browser into really making the request (instead of using the browser cache).</p> <p>This method is some kind of "hack" the webdevs use so that they are sure the request actually happens.</p> <p>Since you aren't using a web browser, I'm pretty ...
1
2016-07-23T04:20:15Z
[ "python", "url", "web" ]
How can I detect the method to request data from this site?
38,537,941
<p><strong>UPDATE:</strong> I've put together the following script to use the url for the XML <em>without the time-code-like suffix</em> as recommended in the <a href="http://stackoverflow.com/a/38538127/3904031">answer below</a>, and report the downlink powers which clearly fluctuate on the website. I'm getting three ...
1
2016-07-23T03:46:16Z
38,541,348
<p>Regarding your updated question, why avoid sending the <code>r</code> query string parameter when it is very easy to generate it? Also, with the <a href="http://docs.python-requests.org" rel="nofollow"><code>requests</code></a> module, it's easy to send the parameter with the request too:</p> <pre><code>import time...
1
2016-07-23T11:38:04Z
[ "python", "url", "web" ]
pandas comparing series with numpy float gives TypeError
38,537,943
<p>In <code>pandas</code>, you can do this:</p> <pre><code>&gt;&gt;&gt; x = pd.DataFrame([[1,2,3,4], [3,4,5,6]], columns=list('abcd')) &gt;&gt;&gt; x a b c d 0 1 2 3 4 1 3 4 5 6 &gt;&gt;&gt; 2 &lt; x.a 0 False 1 True Name: a, dtype: bool </code></pre> <p>However, when I try it with it with a <cod...
2
2016-07-23T03:46:57Z
38,542,991
<p>This seems to be a known issue talked about <a href="https://github.com/pydata/pandas/issues/13006" rel="nofollow">here</a> and fixed <a href="https://github.com/pydata/pandas/pull/13307" rel="nofollow">here</a>, making it tough to find the source if you (like me) are running <code>0.18.0</code> and trying to find t...
0
2016-07-23T14:43:55Z
[ "python", "numpy", "pandas" ]
How can I use POST from requests module to login to Github?
38,537,963
<p>I have tried logging into GitHub using the following code:</p> <pre><code>url = 'https://github.com/login' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'login':'username', 'password':'password', ...
1
2016-07-23T03:50:47Z
38,538,011
<p>I think you get back to the login page because you are redirected and since your code doesn't send back your cookies, you can't have a session.</p> <p>You are looking for session persistance, <code>requests</code> provides it :</p> <blockquote> <p>Session Objects The Session object allows you to persist certain ...
1
2016-07-23T03:59:05Z
[ "python", "python-3.x", "post", "github", "python-requests" ]
How can I use POST from requests module to login to Github?
38,537,963
<p>I have tried logging into GitHub using the following code:</p> <pre><code>url = 'https://github.com/login' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'login':'username', 'password':'password', ...
1
2016-07-23T03:50:47Z
38,545,068
<p>You can also try using the PyGitHub API to perform common git tasks. Check the link below: <a href="https://github.com/PyGithub/PyGithub" rel="nofollow">https://github.com/PyGithub/PyGithub</a></p>
0
2016-07-23T18:17:06Z
[ "python", "python-3.x", "post", "github", "python-requests" ]
How to use Selenium to get this index?
38,538,032
<p>I'm trying to retrieve the fear index from the link <a href="http://money.cnn.com/data/fear-and-greed/" rel="nofollow">http://money.cnn.com/data/fear-and-greed/</a>. The index is dynamically changing. When I inspect the element, it shows the coding below. I'm just wondering how to use python Selenium to get the 84 a...
3
2016-07-23T04:02:35Z
38,538,114
<p>According to the <a href="https://w3c.github.io/webdriver/webdriver-spec.html#get-element-text" rel="nofollow">specification</a>, <code>.text</code> would only give you the <em>rendered text</em> by default, which, I suspect, is becoming empty because of the weird styling of the "needleChart" parent container. </p> ...
2
2016-07-23T04:17:34Z
[ "python", "selenium" ]
How to use Selenium to get this index?
38,538,032
<p>I'm trying to retrieve the fear index from the link <a href="http://money.cnn.com/data/fear-and-greed/" rel="nofollow">http://money.cnn.com/data/fear-and-greed/</a>. The index is dynamically changing. When I inspect the element, it shows the coding below. I'm just wondering how to use python Selenium to get the 84 a...
3
2016-07-23T04:02:35Z
38,538,121
<p>You can find it by finding the element and extract its innerHTML text:</p> <pre><code>element = webdriver.find_element_by_xpath("//div[@id='needleChart']/ul/li") text = element.get_attribute("innerHTML") </code></pre> <p>text will contain all text as following:</p> <pre><code>Fear &amp; Greed Now: 86 (Extreme Gre...
1
2016-07-23T04:18:34Z
[ "python", "selenium" ]