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
Replacing values in a column for a subset of rows
40,095,632
<p>I have a <code>dataframe</code> having multiple columns. I would like to replace the value in a column called <code>Discriminant</code>. Now this value needs to only be replaced for a few rows, whenever a condition is met in another column called <code>ids</code>. I tried various methods; The most common method seem...
0
2016-10-17T21:04:46Z
40,095,819
<p>Maybe something like this. I don't have a dataframe to test it, but... </p> <pre><code>df['Discriminant'] = np.where(df['ids'] == 'some_condition', 'replace', df['Discriminant']) </code></pre>
1
2016-10-17T21:19:01Z
[ "python", "pandas", "dataframe" ]
Python - insert lines on txt following a sequence without overwriting
40,095,670
<p>I want to insert the name of a file before each file name obtained through glob.glob, so I can concatenate them through FFMPEG by sorting them into INTRO+VIDEO+OUTRO, the files have to follow this order:</p> <p>INSERTED FILE NAME<br> FILE<br> INSERTED FILE NAME<br> INSERTED FILE NAME<br> FILE<br> INSERTED FILE NAM...
0
2016-10-17T21:07:24Z
40,096,049
<p>You are trying to modify <code>contents</code> list. I think if new list is used to get final output, then it will be simple and more readable as below. And as <strong>Zen of Python</strong> states</p> <p><strong>Simple is always better than complex.</strong> </p> <ol> <li>Consider you got <code>file_list</code> a...
1
2016-10-17T21:34:51Z
[ "python", "video", "ffmpeg" ]
Multi-dimensional outer-product in python
40,095,686
<p>I was doing MNIST dataset and trying to get a outer product of my two vectors <code>w_i(ith class)</code> and <code>a_k(kth sample)</code>.</p> <p>The <code>w_i</code>, for <code>i = 0...9</code>, has 784 coordinates.</p> <p>The <code>a_k</code>, for <code>k = 1...n</code>, also has 784 coordinates.</p> <p>I crea...
2
2016-10-17T21:08:48Z
40,095,793
<p>It looks like you want the following:</p> <pre><code>res = np.einsum('pi,qi-&gt;pq', w, a) </code></pre> <p>Which is shorthand for the following in index notation:</p> <pre><code>res[p,q] = w[p,i]*a[q,i] </code></pre> <p>In this notation, the convention is to sum over all indices which do not appear in the outpu...
3
2016-10-17T21:16:38Z
[ "python", "arrays", "numpy", "multidimensional-array", "scipy" ]
When to apply(pd.to_numeric) and when to astype(np.float64) in python?
40,095,712
<p>I have a pandas DataFrame object named <code>xiv</code> which has a column of <code>int64</code> Volume measurements. </p> <pre><code>In[]: xiv['Volume'].head(5) Out[]: 0 252000 1 484000 2 62000 3 168000 4 232000 Name: Volume, dtype: int64 </code></pre> <p>I have read other posts (like <a href="...
2
2016-10-17T21:10:28Z
40,095,999
<p>If you already have numeric dtypes (<code>int8|16|32|64</code>,<code>float64</code>,<code>boolean</code>) you can convert it to another "numeric" dtype using <strong>Pandas</strong> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow">.astype()</a> method.</p> <p>...
2
2016-10-17T21:31:19Z
[ "python", "pandas", "numpy", "dataframe", "types" ]
Vertica Python Connection
40,095,768
<p>I'm trying to connect to a Vertica database via Python. Here is what I have so far.</p> <p>Using <code>vertica_python</code>:</p> <pre><code>! pip install vertica_python from vertica_python import connect conn_info = {'host': '192.168...', 'port': my_port_number, 'user': 'my_uid', ...
0
2016-10-17T21:15:02Z
40,095,993
<p>You can pass key/value pair like that in Python.</p> <p>Use as follow:</p> <pre><code>from vertica_python import connect connection = connect( host='jdbc:vertica://...', port=my_port_number, user='my_uid', password='my_pwd' ) </code></pre>
0
2016-10-17T21:30:57Z
[ "python", "database-connectivity" ]
Python script for reformatting a text file into a csv using Python
40,095,784
<p>I have been asked to read in a text file containing this:</p> <pre class="lang-none prettyprint-override"><code>1. Wicked Stepmother (1989) as Miranda A couple comes home from vacation to find that their grandfather has … 2. Directed By William Wyler (1988) as Herself During the Golden Age of Hollywood, Will...
-4
2016-10-17T21:16:02Z
40,107,510
<p>This could be done easily using a regular expression but I am guessing you do not wish to use that. </p> <p>Instead the problem can be solved by reading the file in a line at a time and deciding if the line starts with a number followed by a <code>.</code>. If it does, start you start building up a list of lines un...
1
2016-10-18T11:52:15Z
[ "python", "string", "csv", "file-handling" ]
SQLAlchemy: order by columns in chain joined relations
40,095,933
<p>In my app I'v got such models: </p> <pre class="lang-python prettyprint-override"><code>class A(Base): id = Column(UUID, primary_key=True) name_a = Column(Text) class B(Base): id = Column(UUID, primary_key=True) name_b = Column(Text) parent_a_id = Column(UUID, ForeignKey(A.id)) parent_a = r...
0
2016-10-17T21:27:50Z
40,096,141
<p>I played around with your sample and used PostgreSQL for added points. </p> <p>Your query returns a list of C objects, and traditionally in SQL you can only sort by columns that you retrieve. The relations are retrieved behind the scenes so I don't see why it should be possible to sort by them. </p> <p>On the brig...
1
2016-10-17T21:41:25Z
[ "python", "sqlalchemy", "order", "sql-order-by", "relation" ]
Generating random numbers as the value of dictionary in python
40,096,005
<p>Could you please tell me how can I generate a dictionary with 100 rows that have random number between 0 and 1 in each row as the value? For example in data frame, I can have:</p> <pre><code> df['Rand'] = random.sample(random.random(), 100) </code></pre> <p>But I don't know how to do that for a dictionary.</p>
-1
2016-10-17T21:31:44Z
40,096,044
<p>Firstly, it should be <code>list</code> and not <code>dict</code>. Check: <a href="http://stackoverflow.com/questions/3489071/in-python-when-to-use-a-dictionary-list-or-set">In Python, when to use a Dictionary, List or Set?</a></p> <p>In order to get the list of values, you may use <em>list comprehension</em> as: <...
0
2016-10-17T21:34:27Z
[ "python", "dictionary", "random" ]
Generating random numbers as the value of dictionary in python
40,096,005
<p>Could you please tell me how can I generate a dictionary with 100 rows that have random number between 0 and 1 in each row as the value? For example in data frame, I can have:</p> <pre><code> df['Rand'] = random.sample(random.random(), 100) </code></pre> <p>But I don't know how to do that for a dictionary.</p>
-1
2016-10-17T21:31:44Z
40,096,074
<p>I think what you want is something like:</p> <pre><code>{k: random.random() for k in range(100)} </code></pre>
2
2016-10-17T21:36:54Z
[ "python", "dictionary", "random" ]
pandas subset using sliced boolean index
40,096,059
<p>code to make test data:</p> <pre><code>import pandas as pd import numpy as np testdf = {'date': range(10), 'event': ['A', 'A', np.nan, 'B', 'B', 'A', 'B', np.nan, 'A', 'B'], 'id': [1] * 7 + [2] * 3} testdf = pd.DataFrame(testdf) print(testdf) </code></pre> <p>gives </p> <pre><code> date event id...
0
2016-10-17T21:35:46Z
40,096,523
<p>This worked</p> <pre><code>idx = np.where(bool_sliced_idx1==True)[0] ## or # np.ravel(np.where(bool_sliced_idx1==True)) idx_original = df_sub.index[idx] testdf.iloc[idx_original,:] </code></pre>
0
2016-10-17T22:14:07Z
[ "python", "pandas", "indexing", "dataframe", "slice" ]
pandas subset using sliced boolean index
40,096,059
<p>code to make test data:</p> <pre><code>import pandas as pd import numpy as np testdf = {'date': range(10), 'event': ['A', 'A', np.nan, 'B', 'B', 'A', 'B', np.nan, 'A', 'B'], 'id': [1] * 7 + [2] * 3} testdf = pd.DataFrame(testdf) print(testdf) </code></pre> <p>gives </p> <pre><code> date event id...
0
2016-10-17T21:35:46Z
40,096,535
<p>IIUC, you can just combine all of your conditions at once, instead of trying to chain them. For example, <code>df_sub.date &lt; 4</code> is really just <code>(testdf.event == 'A') &amp; (testdf.date &lt; 4)</code>. So, you could do something like:</p> <pre><code># Create the conditions. cond1 = (testdf.event == '...
3
2016-10-17T22:15:46Z
[ "python", "pandas", "indexing", "dataframe", "slice" ]
The positions of all vowels in the string
40,096,173
<p>I am trying to write programs that reads a line of input as a string and print the positions of all vowels in the string.</p> <pre><code>line = str(input("Enter a line of text: ")) vowels = ('a', 'e', 'i', 'o', 'u') position = "" for i in line : if i.lower() in vowels : position += ("%d ", i) print("Pos...
-3
2016-10-17T21:43:44Z
40,096,207
<p>If you want a list of indexes, the following should work using <code>enumerate</code>:</p> <pre><code>&gt;&gt;&gt; text = 'hello world vowel' &gt;&gt;&gt; vowels = 'aeiou' &gt;&gt;&gt; [i for i, c in enumerate(text.lower()) if c in vowels] [1, 4, 7, 13, 15] </code></pre> <p>For your comma formatting:</p> <pre><co...
4
2016-10-17T21:47:25Z
[ "python", "string", "python-3.x" ]
Find most frequent phone number from given .txt file
40,096,185
<p>For example: me.txt (which conatains data as well as phone numbers)which has below info</p> <pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea...
0
2016-10-17T21:45:14Z
40,096,221
<p>You just need <code>collections.Counter</code></p> <pre><code>from collections import Counter text = '''\ (999) 999-3333 (888) 999-2212 (111) 222-2223 (999) 999-3333 (888) 222-2222 (999) 999-3333 ''' counter = Counter() for phone in text.split('\n'): counter[phone] += 1 print counter.most_common(1) </cod...
3
2016-10-17T21:48:27Z
[ "python" ]
Find most frequent phone number from given .txt file
40,096,185
<p>For example: me.txt (which conatains data as well as phone numbers)which has below info</p> <pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea...
0
2016-10-17T21:45:14Z
40,096,378
<p>You have several problems in the code. I fixed the indentation error on the last line. Next, your approach has to iterate through the characters of the file; <strong>readlines</strong> returns a list of strings, one per line. Your second line necessarily returns null, because there's no entire line that will sati...
0
2016-10-17T22:00:17Z
[ "python" ]
Find most frequent phone number from given .txt file
40,096,185
<p>For example: me.txt (which conatains data as well as phone numbers)which has below info</p> <pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea...
0
2016-10-17T21:45:14Z
40,096,395
<p>Your text file seems to have some non-related stuff around it. Taking just the numbers will make the numbers unreadable as they are merged with random numbers in the text.</p> <p>Since I can't tell the exact format of the phone numbers on a line, you can use a regex to extract the number from a line.</p> <p>You ca...
0
2016-10-17T22:02:13Z
[ "python" ]
What does the Python operater ilshift (<<=)?
40,096,260
<p>What does the Python operator ilshift (&lt;&lt;=) and where can I find infos about it?</p> <p>Thanks</p> <p><a href="https://docs.python.org/2/library/operator.html#operator.ilshift" rel="nofollow">https://docs.python.org/2/library/operator.html#operator.ilshift</a></p> <p><a href="http://www.pythonlake.com/pytho...
-5
2016-10-17T21:51:30Z
40,096,508
<p>It is an BitwiseOperators (Bitwise Right Shift): <a href="https://wiki.python.org/moin/BitwiseOperators" rel="nofollow">https://wiki.python.org/moin/BitwiseOperators</a></p> <blockquote> <p>All of these operators share something in common -- they are "bitwise" operators. That is, they operate on numbers (normal...
-1
2016-10-17T22:12:52Z
[ "python" ]
Creating histograms in pandas with columns with equidistant base, not proportional to the range
40,096,278
<p>I am creating an histogram in pandas simply using:</p> <pre><code>train_data.hist("MY_VARIABLE", bins=[0,5, 10,50,100,500,1000,5000,10000,50000,100000]) </code></pre> <p>(train_data is a pandas df).</p> <p>The problem is that, since the range <code>[50000,100000]</code> is so large, I can barely see the small ran...
2
2016-10-17T21:52:57Z
40,096,493
<p>You can do it this way:</p> <pre><code>bins = [0, 5, 10,50,100,500,1000,5000,10000,50000,100000] df.groupby(pd.cut(df.a, bins=bins, labels=bins[1:])).size().plot.bar(rot=0) </code></pre> <p>Demo:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,10**5,(10**4,2)),columns=list('ab')) bins = [0, 5, 10,50,100,500,...
1
2016-10-17T22:11:30Z
[ "python", "pandas", "histogram" ]
Why getting Memory Error? Python
40,096,308
<p>I have a 5gb text file and i am trying to read it line by line. My file is in format-: Reviewerid&lt;\t>pid&lt;\t>date&lt;\t>title&lt;\t>body&lt;\n> This is my code </p> <pre><code>o = open('mproducts.txt','w') with open('reviewsNew.txt','rb') as f1: for line in f1: line = line.strip() line2 = ...
3
2016-10-17T21:55:15Z
40,096,817
<p><strong>Update:</strong></p> <p>Installing 64 bit Python solves the issue.</p> <p>OP was using 32 bit Python that's why getting into memory limitation.</p> <hr> <p>Reading whole comments I think this can help you.</p> <ul> <li>You can't read file in chunk (as 1024) since you want to process data.</li> <li>Inste...
2
2016-10-17T22:44:35Z
[ "python" ]
Lambda function does not return correct value
40,096,323
<p>Im trying to make a variant of the Gillespie algorithm, and to determine the reaction propensities Im trying to automatically generate the propensity vector using lambda expressions. However when creating SSA.P all goes wrong. The last loop in the block of code, PROPLOOP, returns two propensities, where the one gene...
3
2016-10-17T21:56:29Z
40,096,669
<p>The issue is that you're creating your <code>lambda</code> functions in a loop, and they refer to the variables <code>i</code> and <code>j</code> that may change as the loop goes on.</p> <p>The lambda doesn't copy the values of <code>i</code> or <code>j</code> when it is created, it just keeps a reference to the na...
2
2016-10-17T22:27:20Z
[ "python", "numpy", "lambda" ]
ipython 5.1 export interactive session to script
40,096,497
<p>So, I know I can export an ipython session to a notebook, and then convert that notebook to many format using <code>jupyter nbconvert ...</code>. </p> <p>However, the <a href="http://ipython.readthedocs.io/en/stable/interactive/magics.html?highlight=magic#magic-notebook" rel="nofollow">doc</a> also says I should be...
0
2016-10-17T22:11:51Z
40,118,328
<p>The answer was, as Thomas K. said, use <code>%history -f ...</code> instead...</p>
0
2016-10-18T21:24:22Z
[ "python", "session", "ipython", "jupyter-notebook", "ipython-magic" ]
Django general and app templates
40,096,516
<p>I want to customize my Django project, I will have a dashboard app and a home site app (you can enter from this home site to the dashboard with a URL). I want to save a template for the HTML and css so both apps can use them.</p> <p>I followed <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial07/#custom...
0
2016-10-17T22:13:15Z
40,115,188
<p>I found a way to do this. The problem isn't with the templates settings, the problem is with the <code>staticfiles_dir</code>.</p> <pre><code>STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), 'var/css/style.css' ] </code></pre> <p>It is important to remark that the templates should have <code>&lt;link...
0
2016-10-18T18:11:03Z
[ "python", "django", "django-templates" ]
Getting KeyError : 3
40,096,574
<p>Getting KeyError: 3 when trying to do the following to find the topological sort:</p> <pre><code>def dfs_topsort(graph): # recursive dfs with L = [] # additional list for order of nodes color = { u : "white" for u in graph } found_cycle = [False] for u in graph: ...
0
2016-10-17T22:19:33Z
40,096,684
<p>It seems that the <code>dfs_topsort</code> algorithm needs a <code>key</code> for every <code>value</code> that exists in the graph. </p> <p>So we need to include keys for each of the values. The first one that's missing is <code>3</code>, which caused the <code>KeyError: 3</code>, and also <code>13</code>. If we i...
0
2016-10-17T22:29:45Z
[ "python", "graph", "dfs", "topological-sort" ]
Using print as class method name in Python
40,096,601
<p>Does Python disallow using <code>print</code> (or other reserved words) in class method name?</p> <p><code>$ cat a.py</code></p> <pre><code>import sys class A: def print(self): sys.stdout.write("I'm A\n") a = A() a.print() </code></pre> <p><code>$ python a.py</code></p> <pre><code>File "a.py", line 3...
2
2016-10-17T22:21:41Z
40,096,640
<p>The restriction is gone in Python 3, when print was changed from a statement to a function. Indeed, you can get the new behaviour in Python 2 with a future import:</p> <pre><code>&gt;&gt;&gt; from __future__ import print_function &gt;&gt;&gt; import sys &gt;&gt;&gt; class A(object): ... def print(self): ... ...
2
2016-10-17T22:25:05Z
[ "python", "printing", "reserved" ]
Using print as class method name in Python
40,096,601
<p>Does Python disallow using <code>print</code> (or other reserved words) in class method name?</p> <p><code>$ cat a.py</code></p> <pre><code>import sys class A: def print(self): sys.stdout.write("I'm A\n") a = A() a.print() </code></pre> <p><code>$ python a.py</code></p> <pre><code>File "a.py", line 3...
2
2016-10-17T22:21:41Z
40,096,661
<p><strong>print</strong> is a reserved word in Python 2.x, so you can't use it as an identifier. Here is a list of reserved words in Python: <a href="https://docs.python.org/2.5/ref/keywords.html" rel="nofollow">https://docs.python.org/2.5/ref/keywords.html</a>.</p>
0
2016-10-17T22:26:46Z
[ "python", "printing", "reserved" ]
How do I open a text file in Python?
40,096,612
<p>Currently I am trying to open a text file called "temperature.txt" i have saved on my desktop using file handler, however for some reason i cannot get it to work. Could anyone tell me what im doing wrong.</p> <pre><code>#!/Python34/python from math import * fh = open('temperature.txt') num_list = [] for num in ...
2
2016-10-17T22:22:16Z
40,098,340
<p>You simply need to use .readlines() on fh</p> <p>like this:</p> <pre><code>#!/Python34/python from math import * fh = open('temperature.txt') num_list = [] read_lines = fh.readlines() for line in read_lines: num_list.append(int(line)) fh.close() </code></pre>
-1
2016-10-18T01:57:39Z
[ "python", "python-3.x", "filehandler" ]
How do I open a text file in Python?
40,096,612
<p>Currently I am trying to open a text file called "temperature.txt" i have saved on my desktop using file handler, however for some reason i cannot get it to work. Could anyone tell me what im doing wrong.</p> <pre><code>#!/Python34/python from math import * fh = open('temperature.txt') num_list = [] for num in ...
2
2016-10-17T22:22:16Z
40,103,074
<p>The pythonic way to do this is </p> <pre><code>#!/Python34/python from math import * num_list = [] with open('temperature.text', 'r') as fh: for line in fh: num_list.append(int(line)) </code></pre> <p>You don't need to use close here because the 'with' statement handles that automatically.</p> <p>If...
0
2016-10-18T08:19:12Z
[ "python", "python-3.x", "filehandler" ]
How do I send a DHCP request to find DHCP server IP address? Is this possible?
40,096,621
<p>Is it possible to write a small script that will send out a DHCP broadcast request and find the DHCP server address?</p> <p>I need this for a project, but my research led me to believe that you cannot do this on Windows? I would need a small script for OSX, Linux and Windows. </p>
3
2016-10-17T22:23:09Z
40,096,738
<p>I think you're asking an <a href="http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem">XY Problem</a>: You want to know how to find the DHCP IP address on windows, via python?</p> <p>There is a solution on SuperUser for <a href="http://superuser.com/questions/314145/how-to-find-my-dhcp-server-ip-ad...
0
2016-10-17T22:36:53Z
[ "python", "dhcp" ]
How do I send a DHCP request to find DHCP server IP address? Is this possible?
40,096,621
<p>Is it possible to write a small script that will send out a DHCP broadcast request and find the DHCP server address?</p> <p>I need this for a project, but my research led me to believe that you cannot do this on Windows? I would need a small script for OSX, Linux and Windows. </p>
3
2016-10-17T22:23:09Z
40,097,001
<p>Okay, I'm going to make the assumption that your default gateway is configured to point at your DHCP server. I found the following package and was able to get my default gateway:</p> <pre><code>#!/usr/bin/env python import netifaces gateway_info = netifaces.gateways() print(gateway_info) </code></pre> <p>I of cou...
0
2016-10-17T23:05:22Z
[ "python", "dhcp" ]
How to Make uWSGI die when it encounters an error?
40,096,695
<p>I have my Python app running through uWSGI. Rarely, the app will encounter an error which makes it not be able to load. At that point, if I send requests to uWSGI, I get the error <code>no python application found, check your startup logs for errors</code>. What I would like to happen in this situation is for uWSGI ...
0
2016-10-17T22:31:12Z
40,096,953
<p>After an hour of searching, I finally found a way to do this. Just pass the <code>--need-app</code> argument when starting uWSGI, or add <code>need-app = true</code> in your .ini file, if you run things that way. No idea why this is off by default (in what situation would you ever want uWSGI to keep running when you...
1
2016-10-17T22:59:26Z
[ "python", "uwsgi", "supervisord" ]
Modulus problems
40,096,784
<p>**I'm having problems using modulus for a simple evens and odds game. **Whether for even or odd no matter what, the return is "Odd you win" or "Even you win" even when the player + cpu = 3 % 2 = 1 in function (even) I get a return of "Even you win."</p> <pre><code>import random even_odds = list(range(0,2)) play = r...
0
2016-10-17T22:41:33Z
40,096,808
<p>You need to use parens:</p> <pre><code>if (player + cpu) % 2 != 0: </code></pre> <p>You can see the difference with a simple example:</p> <pre><code>In [10]: 5 + 5 % 2 Out[10]: 6 In [11]: (5 + 5) % 2 Out[11]: 0 </code></pre> <p><code>%</code> has a higher <a href="https://docs.python.org/2/reference/expressio...
2
2016-10-17T22:44:00Z
[ "python", "math", "modulus" ]
Modulus problems
40,096,784
<p>**I'm having problems using modulus for a simple evens and odds game. **Whether for even or odd no matter what, the return is "Odd you win" or "Even you win" even when the player + cpu = 3 % 2 = 1 in function (even) I get a return of "Even you win."</p> <pre><code>import random even_odds = list(range(0,2)) play = r...
0
2016-10-17T22:41:33Z
40,096,821
<p>The <strong>modulo</strong> applies only for the <code>cpu</code> variable. </p> <p>Use <code>(player + cpu) % 2</code> to apply it for the sum.</p> <pre><code>&gt;&gt;&gt; player = 2 &gt;&gt;&gt; cpu = 1 &gt;&gt;&gt; player + cpu % 2 3 &gt;&gt;&gt; (player + cpu) % 2 1 </code></pre> <hr> <p><code>%</code> evalu...
1
2016-10-17T22:44:44Z
[ "python", "math", "modulus" ]
Ranking python dictionary by percentile
40,096,826
<p>If i have a dictionary that records the count frequency of random objects:</p> <pre><code>dict = {'oranges': 4 , 'apple': 3 , 'banana': 3 , 'pear' :1, 'strawberry' : 1....} </code></pre> <p>And I want only the keys that are in the top 25th percentile by frequency, how would i do that ? Especially if it's a very lo...
2
2016-10-17T22:45:24Z
40,096,939
<p>Use a <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> object and exploit its <a href="https://docs.python.org/2/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>most_common</code></a> method to return t...
2
2016-10-17T22:58:00Z
[ "python", "numpy", "dictionary" ]
Put list into dict with first row header as keys
40,096,846
<p>I have the following python list:</p> <pre><code>[['A,B,C,D'], ['1,2,3,4'], ['5,6,7,8']] </code></pre> <p>How can I put it into a dict and use the first sub list as the keys?:</p> <pre><code>{'A': '1', 'B': '2', 'C': '3', 'D': '4'} {'A': '5', 'B': '6', 'C': '7', 'D': '8'} </code></pre> <p>Thanks in advan...
2
2016-10-17T22:47:21Z
40,096,878
<p>You can <code>zip</code> the first element of the list with the remaining elements of the list after splitting the string in each sublist:</p> <pre><code># to split string in the sublists lst = [i[0].split(',') for i in lst] [dict(zip(lst[0], v)) for v in lst[1:]] #[{'A': '1', 'B': '2', 'C': '3', 'D': '4'}, # {'A...
1
2016-10-17T22:51:11Z
[ "python" ]
Put list into dict with first row header as keys
40,096,846
<p>I have the following python list:</p> <pre><code>[['A,B,C,D'], ['1,2,3,4'], ['5,6,7,8']] </code></pre> <p>How can I put it into a dict and use the first sub list as the keys?:</p> <pre><code>{'A': '1', 'B': '2', 'C': '3', 'D': '4'} {'A': '5', 'B': '6', 'C': '7', 'D': '8'} </code></pre> <p>Thanks in advan...
2
2016-10-17T22:47:21Z
40,096,881
<p>Just use a <a href="https://docs.python.org/2/library/csv.html#csv.DictReader" rel="nofollow">DictReader</a> instance. People usually use these with a file object, but actually it doesn't really care what you pass it as long as it can iterate the thing.</p> <pre><code>&gt;&gt;&gt; L = [['A,B,C,D'], ... ['1,2,3,4'...
1
2016-10-17T22:51:30Z
[ "python" ]
Put list into dict with first row header as keys
40,096,846
<p>I have the following python list:</p> <pre><code>[['A,B,C,D'], ['1,2,3,4'], ['5,6,7,8']] </code></pre> <p>How can I put it into a dict and use the first sub list as the keys?:</p> <pre><code>{'A': '1', 'B': '2', 'C': '3', 'D': '4'} {'A': '5', 'B': '6', 'C': '7', 'D': '8'} </code></pre> <p>Thanks in advan...
2
2016-10-17T22:47:21Z
40,096,906
<p>Let's start with your data as presented in the question:</p> <pre><code>&gt;&gt;&gt; a = [['A,B,C,D'], ['1,2,3,4'], ['5,6,7,8']] </code></pre> <p>Now, let's convert that to the desired list of dictionaries:</p> <pre><code>&gt;&gt;&gt; [dict(zip(a[0][0].split(','), c[0].split(','))) for c in a[1:]] [{'A': '1', 'C'...
1
2016-10-17T22:54:28Z
[ "python" ]
I am using Kivy in Python and only the last button has it's embedded objects appearing
40,096,850
<p>I apologize in advance if my question is stupid or obvious, but I have been researching this over and over and am coming up with nothing. I am currently using Kivy and have multiple buttons in a gridlayout, which is in a scrollview. Withing these buttons I have a label and an image. Only the last of my buttons show...
0
2016-10-17T22:47:46Z
40,107,645
<p>Here is something that should help you get what you want:</p> <p>A main.py like this:</p> <pre><code>from kivy.app import App import webbrowser class Solis(App): def __init__(self, **kwargs): super(Solis, self).__init__(**kwargs) self.lead1image='https://pbs.twimg.com/profile_images/562300519...
0
2016-10-18T11:58:00Z
[ "python", "kivy" ]
Getting current build number in jenkins using python
40,097,012
<p>I have a python script from which I am trying to get the current build number of a job in jenkins. Below script gives the last build number and whether the build is success or failure. How can I get the current build number? I mean when I run this script, It will build with new build number and how can I get that cu...
0
2016-10-17T23:06:19Z
40,098,295
<p>I think the answer you're looking for is within the python-jenkins <a href="http://python-jenkins.readthedocs.io/en/latest/examples.html" rel="nofollow">documentation</a> specifically at Example 9</p> <p>The code snippet below is from their documentation:</p> <pre><code>next_bn = server.get_job_info('job_name')['n...
0
2016-10-18T01:51:56Z
[ "python", "jenkins", "jobs", "jenkins-api" ]
What is the most efficient way to compare every value of 2 numpy matrices?
40,097,024
<p>I'd like to more efficiently take every value of 2 matrices(<code>a</code> and <code>b</code>) of the same size and return a third boolean(or 1/ 0 matrix to make things clean) into matrix<code>c</code> containing the results of the conditions.</p> <p>Example:</p> <p>Condition: <code>For a == 0 and b == 3</code></p...
-1
2016-10-17T23:07:04Z
40,097,139
<p>You <em>can</em> use (pretty) much the expression that you wanted:</p> <pre><code>&gt;&gt;&gt; (a == 0) &amp; (b == 3) matrix([[False, False], [ True, False]], dtype=bool) </code></pre> <p>Beware, you <em>need</em> the parenthesis to make the precendence work out as you'd like -- Normally <code>&amp;</code...
0
2016-10-17T23:19:35Z
[ "python", "python-3.x", "oop", "numpy", "matrix" ]
Plotting asymmetric error bars Matplotlib
40,097,086
<p>So I have three sets of data:</p> <pre><code>min_data = np.array([ 0.317, 0.312, 0.305, 0.296, 0.281, 0.264, 0.255, 0.237, 0.222, 0.203, 0.186, 0.17, 0.155, 0.113, 0.08]) avg_data = np.array([ 0.3325, 0.3235, 0.3135, 0.30216667, 0.2905, 0.27433333, 0.26116667, 0.24416667, 0.22833333, 0.20966667, 0.19366667, 0.17...
2
2016-10-17T23:13:21Z
40,097,584
<p>Your code is failing because it thinks that <code>'bo'</code> is the <code>yerr</code> argument since the third argument in <code>plt.errorbar</code> is <code>yerr</code>. If you want to pass the format specifier, then you should use the <code>fmt</code> keyword. </p> <pre><code>plt.errorbar(x, avg_data, fmt='bo'...
2
2016-10-18T00:14:34Z
[ "python", "numpy", "matplotlib" ]
BS4 get XML tag variables
40,097,088
<p>I am playing around with web scraping using bs4 and trying to get the title and color tag from this line of xml <code>&lt;graph gid="1" color="#000000" balloon_color="#000000" title="Approve"&gt;</code></p> <p>The output result would be a dict something along the lines of <code>{'title':'approve', 'color':'#000000'...
2
2016-10-17T23:13:40Z
40,097,165
<p>You just need to pull the <em>attributes</em> once you find the <em>graph node</em>:</p> <pre><code>import requests from bs4 import BeautifulSoup soup = BeautifulSoup(requests.get("http://charts.realclearpolitics.com/charts/1044.xml").content,"xml") g = soup.find("graph", gid="1") data = {"title":g["title"], "colo...
2
2016-10-17T23:22:49Z
[ "python", "xml", "python-3.x", "beautifulsoup" ]
Return code of a bash script being called from a Subprocess
40,097,144
<p>I am writing a script that imports a bunch of data to a couchdb database, the issue is each db takes around 15 minutes, so I do not watch the whole thing as I have on average 20 db to import.</p> <p>The script loops through an array of items, and then calls subprocess on each in order run the import before moving o...
3
2016-10-17T23:20:09Z
40,097,515
<p>Note that when you run:</p> <pre><code>docker exec -it </code></pre> <p>your <code>-it</code> flags are doing something contrary to the point of what you are trying. You are trying to open an interactive session. This isn't actually <em>executing</em> the command.</p> <p>You can remove both of these from your com...
0
2016-10-18T00:06:09Z
[ "python", "bash", "docker" ]
Python loop through Dataframe 'Series' object has no attribute
40,097,194
<p>Using pandas version 0.19.0, I have a dataframe with compiled regular expressions inside. I want to loop over the dataframe and see if any of the regular expressions match a value. I can do it with two for loops, but I can't figure out how to do it so that it'll return a same sized dataframe.</p> <pre><code>impor...
2
2016-10-17T23:25:41Z
40,097,973
<p>It looks like you need to use the <code>applymap</code> method. See the docs <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html?highlight=applymap" rel="nofollow">here</a> for more info. </p> <pre><code>df.applymap(lambda x: x.match('a')) </code></pre> <p>Output:</p> <p>...
0
2016-10-18T01:12:51Z
[ "python", "pandas", "dataframe" ]
How do I median bin a 2D image in python?
40,097,213
<p>I have a 2D numarray, of size WIDTHxHEIGHT. I would like to bin the array by finding the median of each bin so that the resultant array is WIDTH/binsize x HEIGHT/binsize. Assume that both WIDTH and HEIGHT are divisible by binsize. </p> <p>I have found solutions where the binned array values are the sum or average o...
0
2016-10-17T23:27:38Z
40,109,865
<p>Is this what you are looking for? </p> <pre><code>import numpy as np a = np.arange(24).reshape(4,6) def median_binner(a,bin_x,bin_y): m,n = np.shape(a) return np.array([np.median(col) for row in a.reshape(bin_x,bin_y,m//bin_x,n//bin_y) for col in row]).reshape(bin_x,bin_y) print "Original Matrix:" print...
0
2016-10-18T13:38:46Z
[ "python", "arrays", "numpy" ]
How do I add list in xlsxwriter?
40,097,255
<p>I'm having hard time outputting my format in spreadsheet using xlsxwriter. I have four keys.</p> <pre><code>worksheet.write('A1', 'Provider Name', bold) worksheet.write('A2', 'Description', bold) worksheet.write('A3', 'Number of Store', bold) worksheet.write('A4', 'City', bold) </code></pre> <p>I want to be able t...
1
2016-10-17T23:32:35Z
40,103,882
<p>You can use <a href="https://xlsxwriter.readthedocs.io/worksheet.html#worksheet-write-row" rel="nofollow"><code>write_row()</code></a> (or <a href="https://xlsxwriter.readthedocs.io/worksheet.html#worksheet-write-column" rel="nofollow"><code>write_column()</code></a>) to write lists in one go: </p> <pre><code># Som...
0
2016-10-18T09:01:10Z
[ "python", "xlsxwriter" ]
Python 3.5 dictionary comparison
40,097,366
<p>I am trying to compare all elements of one dictionary to make sure they are in a second with the correct number. I am new at Python so I know there is something simple I am probably missing and I have been working on this one problem for hours so my code is likely very ugly and wrong. Here is an example of what I ha...
2
2016-10-17T23:47:22Z
40,097,707
<p>So you want to check to see that every letter in <code>dict2</code> has at mapping in <code>dict1</code> least as large as that letters mapping in <code>dict2</code>? That's accomplished fairly easily.</p> <pre><code>def can_spell(dict1, dict2): try: return all(dict1[k] &gt;= v for k, v in dict2.items(...
2
2016-10-18T00:31:09Z
[ "python", "python-3.x", "dictionary" ]
Python sorting a nested list with conditional comparison
40,097,372
<p>I am trying to sort a nested list <code>A</code>. <code>len(A) = n</code> and <code>len(A[i]) = d</code> for all <code>i</code>. I would like to sort using the first element of <code>A[i]</code>. But if <code>A[i][0] == A[j][0]</code> then I want to sort using the next element, i.e., <code>A[i][1]</code>. If <code>A...
-1
2016-10-17T23:47:53Z
40,097,651
<p>This is the default Python sorting behavior. Have you tried doing this and it hasn't worked?</p>
1
2016-10-18T00:24:04Z
[ "python", "python-3.x", "sorting", "key" ]
How to use Multiprocessing in Python within a class
40,097,485
<p>What I'd like to do is use multiprocessing on one of my class methods. I have tried to follow the example in the Python help file but am not getting the result expected. Here is my class file:</p> <pre><code>import os import telnetlib class PowerSupply(): # ---------------------------------- # def __init_...
0
2016-10-18T00:02:36Z
40,098,160
<p>Ok, here's what I suppose the program will do:</p> <ol> <li>At <code>PowerSuppy(8000,'L1')</code>, it starts a subprocess and calls <code>self.print_time('tname','delay')</code>. Since <code>'delay'</code> is not a number it immediately raises a <code>TypeError</code> in the subprocess and end (so <code>self.P.join...
1
2016-10-18T01:34:15Z
[ "python", "oop", "python-multiprocessing" ]
How to use Multiprocessing in Python within a class
40,097,485
<p>What I'd like to do is use multiprocessing on one of my class methods. I have tried to follow the example in the Python help file but am not getting the result expected. Here is my class file:</p> <pre><code>import os import telnetlib class PowerSupply(): # ---------------------------------- # def __init_...
0
2016-10-18T00:02:36Z
40,098,172
<p>Try to add a function in your class:</p> <pre><code>def print_time_subprocess(self, tname, delay): p = Process(target=self.print_time, args=('tname','delay')) p.start() </code></pre> <p>and use this to test:</p> <pre><code>ps1 = PowerSupply(8000,'L1') ps1.print_time_subprocess('thread1',2) ps1.print_time_...
1
2016-10-18T01:35:49Z
[ "python", "oop", "python-multiprocessing" ]
Which API key do I use in SpeechRecognition (Google) in python
40,097,617
<p>I am working on a project that uses voice recognition in python and I was looking at some example code, I was wondering which API key to use and what does it look like.</p> <pre><code>def callback(recognizer, audio): # received audio data, now we'll recognize it using Google Speech Recognition try: # for testin...
0
2016-10-18T00:19:23Z
40,098,146
<p>Create an account here <a href="https://cloud.google.com/speech/" rel="nofollow">Google Cloud Speech API</a>. You will be able to get a limited amount of api requests with a free account. for a full documentation, visit <a href="https://cloud.google.com/speech/docs/rest-tutorial" rel="nofollow">https://cloud.google....
0
2016-10-18T01:31:45Z
[ "python", "api" ]
Pandas Grouping - Creating a Generic Aggregation Function
40,097,706
<p>I need to do a lot of aggregation on data and I was hoping to write a function that would allow me to pass</p> <p>1) The string to use for grouping 2) The fields that would constitute the numerator/denominator/ and formula</p> <p>As I will be doing a lot of cuts on the data using different groupings and different ...
0
2016-10-18T00:31:01Z
40,097,904
<p>You can achieve this using <code>eval()</code> function</p> <pre><code>import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/master/ch08/tips.csv", sep=',') groupbyvalue = ['sex', 'smoker'] fieldstoaggregate = ['tip','total_bill'] dfformula = "r.tip/r.total_bill" (df.groupby(gr...
1
2016-10-18T01:00:58Z
[ "python", "pandas", "dataframe", "aggregate", "aggregation" ]
Making a list of mouse over event functions in Tkinter
40,097,711
<p>I'm making a GUI for a medical tool as a class project. Given a condition, it should output a bunch of treatment options gathered from different websites like webMD. I would like to be able to handle mouseover events on any of the treatments listed to give a little more information about the treatment (such as the c...
3
2016-10-18T00:32:05Z
40,097,861
<blockquote> <p>I can't write a function definition for every single possible label, they would number in the hundreds or thousands. I'm sure there's a very pythonic way to do it, but I have no idea what.</p> </blockquote> <p>Check out <a href="http://www.secnetix.de/olli/Python/lambda_functions.hawk" rel="nofollow"...
3
2016-10-18T00:54:35Z
[ "python", "list", "user-interface", "tkinter", "mouseover" ]
How to click on the list of the <li> elements in an <ul> elements with selenium in python?
40,097,838
<p><a href="https://i.stack.imgur.com/0rFR0.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/0rFR0.jpg" alt="enter image description here"></a></p> <p>I tried to select 2002 in dropdown menu. It doesn't work at any late. I used xpath</p> <pre><code>driver.find_element_by_xpath("html/body/main/div/form/div[3]/d...
2
2016-10-18T00:51:18Z
40,097,955
<p>If you're able to open dropdown item but unable to click on item, you should try using <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow"><code>Explicit Waits</code></a> with <code>WebDriverWait</code> to wait until this element is visible and enable to click as below :-</p> <p...
1
2016-10-18T01:09:24Z
[ "python", "selenium" ]
How to click on the list of the <li> elements in an <ul> elements with selenium in python?
40,097,838
<p><a href="https://i.stack.imgur.com/0rFR0.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/0rFR0.jpg" alt="enter image description here"></a></p> <p>I tried to select 2002 in dropdown menu. It doesn't work at any late. I used xpath</p> <pre><code>driver.find_element_by_xpath("html/body/main/div/form/div[3]/d...
2
2016-10-18T00:51:18Z
40,097,995
<p>First of all, try to avoid using absolute XPATH. Use something like this:</p> <pre><code>'//ul[@id="uiBirthYear"]/li/a[@data-value="2002"]' </code></pre> <p>Also ensure, that the DOM is fully built, before you trying to get/click on this element.</p> <p>Try to set an <em>implicit wait</em></p> <pre><code>driver....
0
2016-10-18T01:14:50Z
[ "python", "selenium" ]
How to remove the all the curly bracket in dictionary of dictionaries
40,097,863
<p>I wish to remove all the curly brackets from my current output. My current output as shown below:</p> <pre><code> {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 }} </code></pre> <p>My current code as shown below:</p> ...
3
2016-10-18T00:54:53Z
40,097,901
<p>You can do this by converting the dictionary first to a string and then replacing all the brackets with empty strings:</p> <pre><code>d = {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQSEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1}} print(str(d).replace("{","").repl...
1
2016-10-18T01:00:29Z
[ "python", "dictionary" ]
How to remove the all the curly bracket in dictionary of dictionaries
40,097,863
<p>I wish to remove all the curly brackets from my current output. My current output as shown below:</p> <pre><code> {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 }} </code></pre> <p>My current code as shown below:</p> ...
3
2016-10-18T00:54:53Z
40,097,968
<p>Build up the string like so</p> <pre><code>d = {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1}} st = ', '.join('%r: %s' % (k, ', '.join('%r: %r' % (sk, sv) for sk, sv in v.items())) for k, v in d.items()) print(st) </co...
0
2016-10-18T01:12:07Z
[ "python", "dictionary" ]
How to remove the all the curly bracket in dictionary of dictionaries
40,097,863
<p>I wish to remove all the curly brackets from my current output. My current output as shown below:</p> <pre><code> {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 }} </code></pre> <p>My current code as shown below:</p> ...
3
2016-10-18T00:54:53Z
40,098,210
<pre><code>d = {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1}} ', '.join(['{}: {}'.format(merchant, ', '.join(['{}: {}'.format(product, quantity) for product, quantity in products.items()])) for merchant, products in d.ite...
0
2016-10-18T01:40:57Z
[ "python", "dictionary" ]
How to remove the all the curly bracket in dictionary of dictionaries
40,097,863
<p>I wish to remove all the curly brackets from my current output. My current output as shown below:</p> <pre><code> {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 }} </code></pre> <p>My current code as shown below:</p> ...
3
2016-10-18T00:54:53Z
40,098,348
<pre><code>import re result={'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1}} expected_output=re.sub("}|{","",str(result)) </code></pre>
0
2016-10-18T01:58:40Z
[ "python", "dictionary" ]
Downloading the top comments for an imgur image (jpg)
40,097,882
<p>How can I access the comments related to an imgur image using json? </p> <p>for <a href="http://imgur.com/gallery/DVNWyG8" rel="nofollow">http://imgur.com/gallery/DVNWyG8</a> , browsing to <a href="http://api.imgur.com/3/image/DVNWyG8.json" rel="nofollow">http://api.imgur.com/3/image/DVNWyG8.json</a> yields:</p> <...
0
2016-10-18T00:58:19Z
40,098,189
<p>This python library here suits your needs, <a href="https://github.com/Imgur/imgurpython" rel="nofollow">https://github.com/Imgur/imgurpython</a></p>
0
2016-10-18T01:38:20Z
[ "python", "json", "web-scraping", "imgur" ]
Downloading the top comments for an imgur image (jpg)
40,097,882
<p>How can I access the comments related to an imgur image using json? </p> <p>for <a href="http://imgur.com/gallery/DVNWyG8" rel="nofollow">http://imgur.com/gallery/DVNWyG8</a> , browsing to <a href="http://api.imgur.com/3/image/DVNWyG8.json" rel="nofollow">http://api.imgur.com/3/image/DVNWyG8.json</a> yields:</p> <...
0
2016-10-18T00:58:19Z
40,098,483
<pre><code> 21 for item in imgur_client.gallery_item_comments("c1SN8", sort='best'): 22 print item.comment </code></pre> <p>Will do the job</p>
1
2016-10-18T02:17:14Z
[ "python", "json", "web-scraping", "imgur" ]
list.sort() not sorting values correctly by second tuple parameter
40,097,975
<p>I am trying to sort a list of tuples by the second parameter in the tuple in Python 3.5.2 to find which algorithms take the <code>least -&gt; most</code> time in ascending order, however for some reason the looks to be sorting by random. My code:</p> <pre><code>import math def speeds(n): new_dictionary = {} ...
0
2016-10-18T01:13:02Z
40,098,040
<p>If you examine <code>sorted_list</code> following the sort, you will see that it has been sorted correctly.</p> <pre><code>[(11, 0), (7, 1.027450511266727), (6, 1.3627418135330593), (17, 1.9765855902562173), (3, 4.0), (1, 11.618950038622252), (14, 15.000000000000002), (10, 15.263794126054286), (15, 60), (4, 75), (1...
4
2016-10-18T01:20:26Z
[ "python", "python-3.x", "sorting", "tuples" ]
list.sort() not sorting values correctly by second tuple parameter
40,097,975
<p>I am trying to sort a list of tuples by the second parameter in the tuple in Python 3.5.2 to find which algorithms take the <code>least -&gt; most</code> time in ascending order, however for some reason the looks to be sorting by random. My code:</p> <pre><code>import math def speeds(n): new_dictionary = {} ...
0
2016-10-18T01:13:02Z
40,098,056
<p>When you iterate over your tuples, you want to print the <em>tuple</em> itself:</p> <pre><code>for tup in sorted_list: print(tup) </code></pre> <p>otherwise, you are printing the values at the index based on the <em>first value</em> of the index. For example, the first value in the sorted list is:</p> <pre><c...
1
2016-10-18T01:22:37Z
[ "python", "python-3.x", "sorting", "tuples" ]
PyQt5 Pass user inputs from GUI to main code
40,097,999
<p>I have an interface that prompts users for 3 inputs and a selection from a comboBox. What I want to happen is have all of the information entered by the user, they press the button and then those inputs are used to run on the subsequent processes for the project (folder creation, copying, ect).</p> <p>My problem i...
0
2016-10-18T01:15:29Z
40,098,242
<p>Instead of having the slot connected to the push button's <code>clicked()</code> signal quit the application, just have it run the code you're interested in using the appropriate values.</p> <p>So the <code>assign()</code> method could more aptly be named <code>callNextProcess()</code>, which retrieves the values f...
0
2016-10-18T01:44:14Z
[ "python", "qt", "pyqt5" ]
Plot each column of Pandas dataframe pairwise against one column
40,098,058
<p>I have a pandas dataframe where one of the columns is a set of labels that I would like to plot each of the other columns against in subplots. In other words, I want the y-axis of each subplot to use the same column, called 'labels', and I want a subplot for each of the remaining columns with the data from each colu...
0
2016-10-18T01:22:42Z
40,098,371
<p>The problem with that code is that you didn't specify an x value. It seems nonsensical because it's plotting the <code>labels</code> column against an index from 0 to the number of rows. As far as I know, you can't do what you want in pandas directly. You might want to check out <a href="https://seaborn.github.io/ge...
1
2016-10-18T02:01:20Z
[ "python", "pandas", "plot" ]
python sentence tokenizing according to the word index of dictionary
40,098,093
<p>I have a vocabulary with the form of dic = {'a':30, 'the':29,....}, the key is the word, the value is its word count. </p> <p>I have some sentences, like:</p> <p>"this is a test"</p> <p>"an apple"</p> <p>....</p> <p>In order to tokenize the sentences, each sentence will be encoded as the word index of dictionar...
0
2016-10-18T01:25:45Z
40,098,700
<p>There are a couple of issues with your code:</p> <ol> <li><p>You're not tokenizing on a word, but a character. You need to split up each line into words</p></li> <li><p>You're appending into one large list, instead of a list of lists representing each sentence/line</p></li> <li><p>Like you said, you don't limit the...
1
2016-10-18T02:46:21Z
[ "python", "encoding", "tokenize" ]
ImportError only for crontab job?
40,098,216
<p>So I wrote a nifty automation script that does some of my work for me via the jira module + handy dandy logic. It runs perfectly from the command line via:</p> <pre><code>me@local] ~/Documents/auto_updater &gt; python /Users/me/Documents/auto_updater/jira_updater.py Missing info starting checking out: ES-20157...
0
2016-10-18T01:41:07Z
40,100,537
<p>probably explicitly append the lib path for jira in jira_updater.py should do.</p> <pre><code># added code below before import jira # append path where jira lib located, for example in /usr/bin/lib import sys sys.path.append('/usr/bin/lib') # if yout don't know where jira located, use code below to get jira path f...
0
2016-10-18T05:54:18Z
[ "python", "import", "cron", "jira" ]
What does <function at ...> mean
40,098,280
<p>Here's the code:</p> <pre><code>def my_func(f, arg): return f(arg) print((lambda x: 2*x*x, (5))) &gt;&gt;&gt;(&lt;function &lt;lambda&gt; at 0x10207b9d8&gt;, 5) </code></pre> <p>How to solve the error, and can some please explain in a clear language what exactly that error means.</p>
0
2016-10-18T01:48:37Z
40,098,556
<p>There is no error; you simply supplied two arguments to <code>print</code>, the <code>lambda x: 2*x*x</code> and <code>5</code>. You're not calling your anonymous function rather, just passing it to <code>print</code>.</p> <p><code>print</code> will then call the objects <code>__str__</code> method which returns wh...
2
2016-10-18T02:27:35Z
[ "python", "function", "python-3.x" ]
Converting If statement to a loop
40,098,290
<p>I am working on a practice problem where we are to input a list into a function argument, that will represent a tic tac toe board, and return the outcome of the board. That is, X wins, O wins, Draw, or None (null string).</p> <p>I have it solved, but I was wondering if there is a way I could manipulate my algorithm...
0
2016-10-18T01:50:49Z
40,098,499
<p>First up, there are only <em>eight</em> ways to win at TicTacToe. You have nine compare-and-return statements so one is superfluous. In fact, on further examination, you check <code>00, 11, 22</code> <em>three</em> times (cases 3, 6 and 9) and totally <em>miss</em> the <code>02, 11, 20</code> case.</p> <p>In terms ...
5
2016-10-18T02:19:16Z
[ "python", "loops", "for-loop", "while-loop" ]
Default value for ndb.KeyProperty
40,098,294
<p>I have these two models:</p> <pre><code>################# ### Usergroup ### ################# class Usergroup(ndb.Model): group_name = ndb.StringProperty(indexed = False, required = True) is_admin_group = ndb.BooleanProperty(indexed = False, required = False, default = False) ############ ### User ### ###...
1
2016-10-18T01:51:45Z
40,110,173
<p>FWIW, a quick test with your code as <code>models.py</code> shows this to be working just fine, at least on the development server:</p> <pre><code> from models import User user = User(email='email', username='username') user.put() </code></pre> <p>produced:</p> <p><a href="https://i.stack.imgur.com/Zm...
1
2016-10-18T13:53:08Z
[ "python", "google-app-engine", "flask", "google-app-engine-python" ]
Use a list to conditionally fill a new column based on values in multiple columns
40,098,300
<p>I am trying to populate a new column within a pandas dataframe by using values from several columns. The original columns are either <code>0</code> or '1' with exactly a single <code>1</code> per series. The new column would correspond to df['A','B','C','D'] by populating <code>new_col = [1, 3, 7, 10]</code> as show...
1
2016-10-18T01:52:59Z
40,098,712
<p>It's not the most elegant solution, but for me it beats the if/elif/elif loop:</p> <pre><code>d = {'A': 1, 'B': 3, 'C': 7, 'D': 10} def new_col(row): k = row[row == 1].index.tolist()[0] return d[k] df['new_col'] = df.apply(new_col, axis=1) </code></pre> <p>Output:</p> <pre><code> A B C D new_c...
0
2016-10-18T02:47:10Z
[ "python", "list", "python-2.7", "pandas" ]
Use a list to conditionally fill a new column based on values in multiple columns
40,098,300
<p>I am trying to populate a new column within a pandas dataframe by using values from several columns. The original columns are either <code>0</code> or '1' with exactly a single <code>1</code> per series. The new column would correspond to df['A','B','C','D'] by populating <code>new_col = [1, 3, 7, 10]</code> as show...
1
2016-10-18T01:52:59Z
40,098,922
<p>I can think of a few ways, mostly involving <code>argmax</code> or <code>idxmax</code>, to get either an ndarray or a Series which we can use to fill the column.</p> <p>We could drop down to <code>numpy</code>, find the maximum locations (where the 1s are) and use those to index into an array version of new_col:</p...
1
2016-10-18T03:14:32Z
[ "python", "list", "python-2.7", "pandas" ]
How to use Iterator that traverses the doubly linked list and skips null nodes
40,098,393
<p>Since the doubly linked list has two dummy nodes, one is the head and the other one is the tail. I can skip the dummy tail node by <code>self.__current == None: raise StopIteration</code>, but I don't know how to pass the dummy head nodes and continue traverse the following node.</p> <pre><code>class LinkedListDLL:...
0
2016-10-18T02:03:46Z
40,098,653
<p>You should refactor your code keeping in mind that <code>NodeDLL(None)</code> may not be the same as <code>None</code>. With that done:</p> <pre><code>def __next__(self): if not self.__current.get_next(): raise StopIteration #Skips first value in list, i.e. head self.__current = self.__current....
0
2016-10-18T02:40:09Z
[ "python", "linked-list", "iterator", "doubly-linked-list" ]
Python -Passing a class method as the default value of an argument to another class initialization
40,098,414
<p>Modifying the original question to prevent confusions. I have 2 classes defined in 2 different modules:</p> <pre><code>class Heuristic: def process(self,data,x,y): processed_data = (data + x) /y return processed_data class GTS(Abstract_Strat): def __init__(self, data, method= Heuristic().p...
-1
2016-10-18T02:06:33Z
40,098,492
<p>In python, you must construct an instance of the class before you can have access to an object and then subsequently it's methods.</p> <p>You might do something like:</p> <pre><code>class GTS(Abstract_Strat): heuristic = Heuristic(data) def __init__(self, data, method= heuristic.process(),*args): s...
1
2016-10-18T02:18:01Z
[ "python", "class", "methods", "parameter-passing", "typeerror" ]
Python -Passing a class method as the default value of an argument to another class initialization
40,098,414
<p>Modifying the original question to prevent confusions. I have 2 classes defined in 2 different modules:</p> <pre><code>class Heuristic: def process(self,data,x,y): processed_data = (data + x) /y return processed_data class GTS(Abstract_Strat): def __init__(self, data, method= Heuristic().p...
-1
2016-10-18T02:06:33Z
40,099,065
<p>I resolved the issue mentioned in the modified question above by changing <code>Heuristic().process()</code> to <code>Heuristic().process</code> when passing it as the default value of the function parameter. </p> <p>Would also like to thank Andrew for his comment on the original version of the question.</p>
0
2016-10-18T03:34:04Z
[ "python", "class", "methods", "parameter-passing", "typeerror" ]
How to Scrape Page HTML and follow Next Link in Selenium
40,098,489
<p>I'm trying to scrape a website for research, and I'm stuck. I want the scraper to read the page source, and append that to a local HTML file so I can analyze the data off-campus. I have experimented with <code>BeautifulSoup</code> and <code>Scrapy</code>, but I have found that I need to use <code>Selenium</code> to ...
1
2016-10-18T02:17:38Z
40,100,124
<p>You need to assign the <code>page source</code> to <code>source</code> variable inside the while loop.</p> <pre><code>source = driver.page_source while True: with open("test.html", "a") as TestFile: TestFile.write(source) try: driver.implicitly_wait(200) driver.find_element_by_css_selector(...
0
2016-10-18T05:22:20Z
[ "python", "selenium" ]
The `or` operator on dict.keys()
40,098,500
<p>As I've been unable to find any documentation on this, so I'll ask here. </p> <p>As shown in the code below, I found that the <code>or</code> operator (<code>|</code>), worked as such:</p> <pre><code>a = {"a": 1,"b": 2, 2: 3} b = {"d": 10, "e": 11, 11: 12} keys = a.keys() | b.keys() aonce = a.keys() | a.values() ...
3
2016-10-18T02:19:17Z
40,098,512
<p>The <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects">Python 3 Documentation</a> notes that the <code>dict.keys</code> method is set-like and implements <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Set"><code>collections.abc.Set</code></a>.</p> <p>N...
5
2016-10-18T02:21:13Z
[ "python", "python-3.x", "python-3.5" ]
Controlling contour label formatting in pyplot
40,098,535
<p>I'm making a plot where I have contours at <code>[2000, 4000, 6000, 8000]</code>. The contours are labeled as 2000.000, 4000.000 etc. I'd like to get rid of all those trailing zeros. The best option I can find right now is here: <a href="http://matplotlib.org/examples/pylab_examples/contour_label_demo.html" rel="...
0
2016-10-18T02:24:37Z
40,101,078
<p>The <code>fmt</code> parameter can be either a classic format string or a callable that converts a scalar to a string.</p> <p>If you don't have fancy requirements you could just pass <code>fmt='%d'</code> instead of a custom class.</p> <p>For common formats you should be also able to resort to the default formatte...
0
2016-10-18T06:31:10Z
[ "python", "matplotlib" ]
(<type 'exceptions.ValueError'>, ValueError('need more than 1 value to unpack',), <traceback object at 0x7f24dea1a0e0>) NULL NULL NULL
40,098,589
<p>I have HIVE table like this in MapR.</p> <p><a href="https://i.stack.imgur.com/zTolR.png" rel="nofollow"><img src="https://i.stack.imgur.com/zTolR.png" alt="enter image description here"></a></p> <p>data was separated with commas at back end. I am trying to use custom map reduce in using python. Here is the python...
0
2016-10-18T02:31:36Z
40,098,954
<p>The only line in your code that could give you that error is this one:</p> <pre><code>userid, movieid, rating, unixtime = line.split(',') </code></pre> <p>So it's complaining that there aren't enough values to unpack, which means there aren't any commas in the line. Try printing the line before processing it; that...
0
2016-10-18T03:18:47Z
[ "python", "hive", "mapr" ]
TypeError: can't pickle face_BasicFaceRecognizer objects
40,098,624
<p>I want to store the trained object, however there is an error shown above. What should I do if I need to store this trained model?</p> <pre><code>fishface = cv2.face.createFisherFaceRecognizer() m = fishface.train(training_data, np.asarray(training_labels)) output = open('data.pkl', 'wb') pickle.dump(fishface, out...
0
2016-10-18T02:36:00Z
40,099,011
<p>Unfortunately, OpenCV bindings typically don't support pickling. You'll have to use built-in OpenCV serialization.</p> <p>You can do <code>m.save("serialized_recognizer.cv2")</code> and at runtime, <code>m.load("serialized_recognizer.cv2")</code>, if <code>m</code> is an instantiated FaceRecognizer.</p>
0
2016-10-18T03:27:41Z
[ "python", "opencv", "pickle" ]
pandas Dataframe columns doing algorithm
40,098,680
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({ 'A': ['a', 'a', 'a', 'a', 'a'], 'lon1': [128.0, 135.0, 125.0, 123.0, 136.0], 'lon2': [128.0, 135.0, 139.0, 142.0, 121.0], 'lat1': [38.0, 32.0, 38.0, 38.0, 38.0], 'lat2': [31.0, 32.0, 35.0, 38.0, 29.0], 'angle': [0, 0, 0, 0, 0] ...
0
2016-10-18T02:44:10Z
40,098,861
<p>It seems like you are trying to apply function <code>angle(...)</code> to every row of your dataframe.</p> <p>First it is necessary to cast all your string-typed numbers into float so as to calculate.</p> <pre><code>df1.loc[:, "lon1"] = df1.loc[:, "lon1"].astype("float") df1.loc[:, "lon2"] = df1.loc[:, "lon2"].ast...
1
2016-10-18T03:06:04Z
[ "python", "pandas" ]
pandas Dataframe columns doing algorithm
40,098,680
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({ 'A': ['a', 'a', 'a', 'a', 'a'], 'lon1': [128.0, 135.0, 125.0, 123.0, 136.0], 'lon2': [128.0, 135.0, 139.0, 142.0, 121.0], 'lat1': [38.0, 32.0, 38.0, 38.0, 38.0], 'lat2': [31.0, 32.0, 35.0, 38.0, 29.0], 'angle': [0, 0, 0, 0, 0] ...
0
2016-10-18T02:44:10Z
40,098,864
<p>I'm sure there's a more vectorized solution, but here is a solution using the row-wise version of the <code>apply</code> method, which only slightly alters your function:</p> <pre><code>def angle(row): dx = row.lon2 - row.lon1 dy = row.lat2 - row.lat1 direction = 0; if ((dx == 0) &amp; (dy == 0)): ...
0
2016-10-18T03:06:37Z
[ "python", "pandas" ]
imgur_client.search_gallery doesn't yield many images
40,098,718
<p>I wonder how can I modify this code so that it will show more queries? Right now it only shows 59 queries that only one of them has more than 30 comments:</p> <pre><code> 9 imgur_client = ImgurClient(client_id, client_secret, access_token, refresh_token) 10 11 search = imgur_client.gallery_search('cat', window=...
0
2016-10-18T02:48:00Z
40,098,811
<p>You should use the <code>page=</code> parameter to gallery_search to get the next page of results and iterate over them that way.</p>
1
2016-10-18T02:59:40Z
[ "python", "api", "web-scraping", "imgur" ]
Python format() without {}
40,098,740
<p>I am working on python 3.6 64 bit.</p> <p>Here is my code:</p> <pre><code>days = "Mon Tue Wed Thu Fri Sat Sun" print("Here are the days",format(days)) </code></pre> <p>The output I got is </p> <p>Here are the days Mon Tue Wed Thu Fri Sat Sun</p> <p>I didn't add "{}" in my string. Also I used a comma "," instea...
0
2016-10-18T02:50:04Z
40,098,772
<p>The print function prints the arguments one right after the other, with a space in between. The <code>format</code> call, finding no replacements, is doing nothing and returning the original string.</p> <p>Here are some examples that may help:</p> <pre><code>&gt;&gt;&gt; colors = "Red Blue" &gt;&gt;&gt; print("Her...
0
2016-10-18T02:54:17Z
[ "python", "format" ]
Python format() without {}
40,098,740
<p>I am working on python 3.6 64 bit.</p> <p>Here is my code:</p> <pre><code>days = "Mon Tue Wed Thu Fri Sat Sun" print("Here are the days",format(days)) </code></pre> <p>The output I got is </p> <p>Here are the days Mon Tue Wed Thu Fri Sat Sun</p> <p>I didn't add "{}" in my string. Also I used a comma "," instea...
0
2016-10-18T02:50:04Z
40,098,785
<p>I think you're thinking what's happening is similar to:</p> <pre><code>print("Here are the days {}".format(days)) </code></pre> <p>However, what's actually happening is that you're passing in multiple arguments to print(). If you look at the <a href="https://docs.python.org/3/library/functions.html#print" rel="nof...
1
2016-10-18T02:56:11Z
[ "python", "format" ]
Python format() without {}
40,098,740
<p>I am working on python 3.6 64 bit.</p> <p>Here is my code:</p> <pre><code>days = "Mon Tue Wed Thu Fri Sat Sun" print("Here are the days",format(days)) </code></pre> <p>The output I got is </p> <p>Here are the days Mon Tue Wed Thu Fri Sat Sun</p> <p>I didn't add "{}" in my string. Also I used a comma "," instea...
0
2016-10-18T02:50:04Z
40,099,310
<p>Some of the confusion here may be the difference between the <code>format()</code> <em>function</em> and the related <code>"string".format()</code> <em>method</em>. The function invokes the object's (first argument) <code>__format__()</code> method with a <em>format specification</em> (second argument). If the sec...
0
2016-10-18T04:04:11Z
[ "python", "format" ]
Why running a Python script as a service in Windows can not write data to text?
40,098,752
<p>I want to reproduce the same result as <a href="http://www.chrisumbel.com/article/windows_services_in_python" rel="nofollow">Windows Services in Python</a>:</p> <pre><code>import win32service import win32serviceutil import win32event class PySvc(win32serviceutil.ServiceFramework): # you can NET START/S...
0
2016-10-18T02:51:25Z
40,114,875
<p>Converting Comment to Answer...</p> <p>Try using a full path for the test.dat file (C:\servicedata\test,dat). The path when you run in the interperter is different from when you run as a service.</p>
0
2016-10-18T17:50:03Z
[ "python", "windows" ]
Python code to return total count of no. of positions in which items are differing at same index
40,098,820
<p>A=[1,2,3,4,5,6,7,8,9] B=[1,2,3,7,4,6,5,8,9]</p> <p>I have to compare these two lists and return the count of no. of location in which items are differing using one line python code.</p> <p>For example: the output should be 4 for given arrays because at index (3,4,5,6) the items are differing.So, program should re...
0
2016-10-18T03:01:14Z
40,098,992
<pre><code>count = sum(a != b for a, b in zip(A, B)) print(count) </code></pre> <p>or just <code>print sum(a != b for a, b in zip(A, B))</code></p> <p>you can check about <a href="https://bradmontgomery.net/blog/pythons-zip-map-and-lambda/" rel="nofollow">zip/lambda/map here</a>, those tools are very powerfull and im...
1
2016-10-18T03:24:36Z
[ "python", "arrays", "python-2.7", "python-3.x", "numpy" ]
Python code to return total count of no. of positions in which items are differing at same index
40,098,820
<p>A=[1,2,3,4,5,6,7,8,9] B=[1,2,3,7,4,6,5,8,9]</p> <p>I have to compare these two lists and return the count of no. of location in which items are differing using one line python code.</p> <p>For example: the output should be 4 for given arrays because at index (3,4,5,6) the items are differing.So, program should re...
0
2016-10-18T03:01:14Z
40,114,857
<p>There are <a href="http://stackoverflow.com/questions/28663856/how-to-count-the-occurrence-of-certain-item-in-an-ndarray-in-python">many ways</a> to do this. If you're using numpy, you could just use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.count_nonzero.html" rel="nofollow"><code>np.count...
0
2016-10-18T17:48:49Z
[ "python", "arrays", "python-2.7", "python-3.x", "numpy" ]
How do I find the location of Python module sources while I can not import it?
40,098,880
<p>The answer in <a href="http://stackoverflow.com/questions/269795/how-do-i-find-the-location-of-python-module-sources">How do I find the location of Python module sources?</a> says just import it and print its <code>__file__</code>. But my question is that I cannot import a library <code>cv2</code> while it returns <...
0
2016-10-18T03:08:55Z
40,099,175
<p>Try:</p> <pre><code>import imp imp.find_module('cv2') </code></pre>
1
2016-10-18T03:47:06Z
[ "python", "module", "python-import" ]
How do I complete my OAuth Google Login?
40,098,935
<p>My application has React and Redux running on the client side and Flask running on the server side.</p> <p>I received a OAUTH token from Google on my client in the form of:</p> <pre><code> Object { El: "109087143026456349612", Zi: Object, w3: Object, googleId: "109087143026456349612", tokenObj: Object, tokenId...
-1
2016-10-18T03:15:45Z
40,101,480
<p>Steps are like this </p> <ol> <li>Get google auth data after user successfully connects to your app.</li> <li>After a user successfully signs in, send the user's ID token to your server using HTTPS.</li> <li>Then, on the server, verify the integrity of the ID token and retrieve the user's ID from the sub claim of t...
0
2016-10-18T06:53:55Z
[ "python", "reactjs", "flask", "oauth" ]
Python Update Dictionary values to reference dataframes with the same name
40,098,963
<p>I have many dataframes with names such as 'ABC', 'XYZ'...</p> <p>I also have a dictionary with keys, where each key has a list of 200 values which are the names of the dataframes i.e. ['ABC','XYZ',...]</p> <p>I want to update this dictionary, so instead of containing the names of the dataframes, it contains the da...
2
2016-10-18T03:20:05Z
40,099,212
<p>What are the keys currently in this dictionary? / Where are your dataframes currently stored? You probably want something like this: </p> <pre><code>dfDict ={dfName: &lt;df&gt;} #assuming a bit here newDict = {} for key, value in oldDict.items(): newDict[key] = { dfName:dfDict[dfName] for dfName in value } </co...
1
2016-10-18T03:52:48Z
[ "python", "pandas", "dictionary", "dataframe", "nested" ]
Python Update Dictionary values to reference dataframes with the same name
40,098,963
<p>I have many dataframes with names such as 'ABC', 'XYZ'...</p> <p>I also have a dictionary with keys, where each key has a list of 200 values which are the names of the dataframes i.e. ['ABC','XYZ',...]</p> <p>I want to update this dictionary, so instead of containing the names of the dataframes, it contains the da...
2
2016-10-18T03:20:05Z
40,099,215
<p>Easy enough, use <code>eval</code>:</p> <pre><code>u, v, w, x, y, z = 1, 2, 3, 4, 5, 6 frames = {} names = {'a' : ['u', 'v'], 'b' : ['w', 'x'], 'c' : ['y', 'z']} for key in names: frames[key] = dict(zip(names[key], [eval(name) for name in names[key]])) frames # Output: {'a': [1, 2], 'b': [3, 4...
2
2016-10-18T03:53:03Z
[ "python", "pandas", "dictionary", "dataframe", "nested" ]
Opening a pdf bytestring for reading
40,098,982
<p>I am working on a scrapy spider, trying to convert pdfs, using pdfminer (<a href="https://pypi.python.org/pypi/pdfminer2" rel="nofollow">https://pypi.python.org/pypi/pdfminer2</a>). I have no interest in saving the actual PDF to disk , and so I've been advised to look into the io.bytesIO subclass at <a href="https:/...
0
2016-10-18T03:22:53Z
40,101,128
<p>There are two problems:</p> <ol> <li><code>in_memory_pdf</code> is already a file-like object for <code>str</code> (or <code>bytes</code> in Py3), can be directly used without opening. Thus changing <code>fp = file(in_memory_pdf, 'rb')</code> to <code>fp = in_memory_pdf</code> partially worked.</li> <li>The second ...
1
2016-10-18T06:35:24Z
[ "python", "pdf" ]
How to parse this file using python?
40,098,984
<p>I have a file with contents like</p> <pre><code>[Input:1] Name=Feature1 Transform=Linear Slope=1 Intercept=0 [Input:4] Name=Feature2 Transform=Linear Slope=1 Intercept=0 [Input:2] Expression=( if ( &gt; Var 10000000) ( - Var 10000000) ( + Var 10000000)) Transform=Freeform [Input:3] Transform=FreeForm Expression=...
-1
2016-10-18T03:23:03Z
40,099,037
<p>I guess u can try config</p> <pre><code>import ConfigParser conf = ConfigParser.ConfigParser() conf.read("test.cfg") sections = conf.sections() print 'sections:', sections #sections: ['sec_b', 'sec_a'] options = conf.options("Input:1") </code></pre> <p>but I misunderstand that how to define Ex...
0
2016-10-18T03:30:41Z
[ "python", "parsing", "text" ]
How to parse this file using python?
40,098,984
<p>I have a file with contents like</p> <pre><code>[Input:1] Name=Feature1 Transform=Linear Slope=1 Intercept=0 [Input:4] Name=Feature2 Transform=Linear Slope=1 Intercept=0 [Input:2] Expression=( if ( &gt; Var 10000000) ( - Var 10000000) ( + Var 10000000)) Transform=Freeform [Input:3] Transform=FreeForm Expression=...
-1
2016-10-18T03:23:03Z
40,099,087
<p>You can generate a grammar analyzer which can parse this file by BNF. Use Boson to do this, Boson is a lightweight grammar analyzer generator.</p> <p><a href="https://github.com/ictxiangxin/boson" rel="nofollow">Boson Github</a></p>
0
2016-10-18T03:36:17Z
[ "python", "parsing", "text" ]
How to parse this file using python?
40,098,984
<p>I have a file with contents like</p> <pre><code>[Input:1] Name=Feature1 Transform=Linear Slope=1 Intercept=0 [Input:4] Name=Feature2 Transform=Linear Slope=1 Intercept=0 [Input:2] Expression=( if ( &gt; Var 10000000) ( - Var 10000000) ( + Var 10000000)) Transform=Freeform [Input:3] Transform=FreeForm Expression=...
-1
2016-10-18T03:23:03Z
40,100,770
<p>Try:</p> <pre><code>try: # Python 2 import ConfigParser as cfgp except: # Python 3 import configparser as cfgp class MyObject: def __getitem__(self, attr): return getattr(self, attr) conf = cfgp.ConfigParser() conf.optionxform = str conf.read('sample.cfg') objects = [] for section in c...
1
2016-10-18T06:09:58Z
[ "python", "parsing", "text" ]
Testing taskqueues locally on google app engine using dev_appserver.py
40,098,999
<p>My app engine app has 2 queues. A worker from the first queue initiates several workers in the second queue and wait for them to complete and consolidate.</p> <p>This works fine when I deploy it, but it <s>doesn't work</s> never spawns the tasks in the second queue when testing locally. It gets stuck while waiting ...
1
2016-10-18T03:26:19Z
40,107,896
<p>Generally sleeping in GAE app code is not a good idea - wasting instance uptime, increasing request latency, risk of exceeding the request deadline etc.</p> <p>You can achieve the same functionality by enqueuing a delayed BigTask (using the <code>countdown</code> option) which would check the status for all smaller...
2
2016-10-18T12:10:00Z
[ "python", "google-app-engine", "task-queue" ]
raise ImgurClientError('JSON decoding of response failed.') imgurpython.helpers.error.ImgurClientError: JSON decoding of response failed
40,099,046
<p>For the code below:</p> <pre><code> 12 imgur_client = ImgurClient(client_id, client_secret, access_token, refresh_token) 13 for p in range(100, 500): 14 search = imgur_client.gallery_search('cat', window='all', sort='time', page=p) 15 for i in range(0, len(search)): 16 #print(search[i].link) 17...
0
2016-10-18T03:31:52Z
40,099,484
<p>Maybe not the best solution but this solved the problem:</p> <pre><code> 1 from imgurpython import ImgurClient 2 import inspect 3 import random 4 import urllib2 5 import requests 6 from imgurpython.helpers.error import ImgurClientError 15 imgur_client = ImgurClient(client_id, client_secret, access_toke...
0
2016-10-18T04:24:32Z
[ "python", "json", "api", "exception", "imgur" ]
Installing bpython for Python 3
40,099,088
<p>I've been using bpython for Python 2 and now I want to use it for Python 3 as well.</p> <p>However I've run into problems. The bpython documentation reads:</p> <blockquote> <p>bpython supports Python 3. It's as simple as running setup.py with Python 3.</p> </blockquote> <p>When I run the setup script it creates...
1
2016-10-18T03:36:18Z
40,099,124
<p><a href="https://docs.python.org/3/install/#standard-build-and-install" rel="nofollow">Run <code>python3 setup.py install</code> command</a> (without <code>install</code> it only builds); You may need to prepend the command with <code>sudo</code>: <code>sudo python3 setup.py install</code>.</p> <p>BTW, you can also...
1
2016-10-18T03:41:57Z
[ "python", "pip", "distutils", "bpython" ]
Python - convert list into dictionary in order to reduce complexity
40,099,239
<p>Let's say I have a big list:</p> <pre><code>word_list = [elt.strip() for elt in open("bible_words.txt", "r").readlines()] </code></pre> <p><code>//complexity O(n) --&gt; proporcional to list length "n"</code></p> <p>I have learned that <code>hash function</code> used for building up <code>dictionaries</code> all...
0
2016-10-18T03:56:43Z
40,099,692
<p>The code from the question does just one thing: fills all words from a file into a list. The complexity of that is O(n).</p> <p>Filling the same words into any other type of container will still have at least O(n) complexity, because it has to read all of the words from the file and it has to put all of the words i...
5
2016-10-18T04:45:38Z
[ "python", "list", "dictionary", "asymptotic-complexity" ]
Why can I make a numpy array that's (apparently) bigger than my computer's memory?
40,099,264
<p>When I run code below:</p> <pre><code>import scipy.sparse x = scipy.sparse.random(100000, 100000, 1e-4) y = x.toarray() print(y.nbytes) </code></pre> <p>I get an output of 80000000000 bytes = 80 GB. And yet I am using a Macbook Air with only 4 GB of RAM. Can someone explain how I am (apparently) creating a NumPy a...
0
2016-10-18T03:59:40Z
40,099,378
<p>This is because numpy doesn't actually allocate all that space. Most likely sparse arrays and matrices are represented with <a href="http://btechsmartclass.com/DS/U1_T14.html" rel="nofollow">triplets, linked nodes</a> or some other means of ignoring all the empty space between. The bytes are calculated based on the ...
0
2016-10-18T04:12:57Z
[ "python", "numpy", "memory", "scipy", "sparse-matrix" ]