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
Very Simple Program Crashing Python 3.5 and spyder
39,176,831
<pre><code>xx = 0 n = 4294967295 while xx &lt;= n: print("xx = ", xx, bin(xx)) xx += 1 </code></pre> <p>This results in the following traceback:</p> <pre><code> File "&lt;ipython-input-2-0c9d04ddbbc6&gt;", line 1, in &lt;module&gt; runfile('C:/Users/Allen/Documents/Python Scripts/crunchy.py', wdir='C:/U...
0
2016-08-27T02:16:15Z
39,176,907
<p>It seems that you are using ipython. </p> <p>According to this page: <a href="https://github.com/ipython/ipython/issues/9168" rel="nofollow">https://github.com/ipython/ipython/issues/9168</a></p> <p>you might run into a know issue and will be fixed in the next release. By the way, that program does not crash when ...
0
2016-08-27T02:35:18Z
[ "python", "anaconda", "spyder" ]
How to fix python module import errors in jenkins
39,176,832
<p>I am having module import errors in Jenkins despite setting my path and python path based on questions here on stack overflow</p> <p>I have tried this</p> <p><a href="http://stackoverflow.com/questions/12995809/jenkins-putting-my-python-module-on-the-pythonpath?rq=1">Jenkins: putting my Python module on the PYTHON...
0
2016-08-27T02:16:35Z
39,180,676
<p>So finally figured it out</p> <p>You need to create the virtual env during the test so this is the final command that works</p> <pre><code>#!/bin/bash export WORKSPACE=`pwd` # Create/Activate virtualenv virtualenv testenv -p /usr/bin/python3 source testenv/bin/activate # Install requirements pip install -r re...
0
2016-08-27T11:34:41Z
[ "python", "django", "jenkins" ]
Django request.user becomes anonymous after redirect
39,176,844
<p>In my Django app I create a User from django.contrib.auth.models, and I am using request.user in multiple view functions without a problem. In one of my view functions I change the user password, save the user, and redirect the client to another view function. Once I try to get the user from the request in that func...
1
2016-08-27T02:19:37Z
39,176,996
<p>Yes. See the documentation about <a href="https://docs.djangoproject.com/en/dev/topics/auth/default/#session-invalidation-on-password-change" rel="nofollow">session invalidation on password change</a>. To fix it, see this bit in particular:</p> <blockquote> <p>The default password change views included with Djang...
1
2016-08-27T02:51:50Z
[ "python", "django", "redirect", "user" ]
Dataframe for HiveContext in spark is not callable
39,176,864
<p>I have the below spark script:</p> <pre><code>from pyspark import SparkContext, SparkConf from pyspark.sql import SQLContext, HiveContext spark_context = SparkContext(conf=SparkConf()) sqlContext = HiveContext(spark_context) outputPartition=sqlContext.sql("select * from dm_mmx_merge.PLAN_PARTITION ORDER BY PARTITIO...
-1
2016-08-27T02:24:37Z
39,181,086
<p>In line </p> <pre><code> outputPartition.filter(outputPartition(partition)==3).show() </code></pre> <p>you are trying to use outputPartition as a method. Use</p> <pre><code> outputPartition['partition'] </code></pre> <p>instead of</p> <pre><code> outputPartition(partition) </code></pre>
2
2016-08-27T12:21:04Z
[ "python", "apache-spark", "pyspark" ]
Uploading contents of Django FileField to a remote server
39,176,878
<p>In a Django project of mine, users upload video files. Initially, I was uploading them directly to Azure Blob Storage (equivalent to storing it on Amazon S3). I.e. in models.py I had:</p> <pre><code>class Video(models.Model): video_file = models.FileField(upload_to=upload_path, storage=OverwriteStorage()) </code...
3
2016-08-27T02:27:07Z
39,195,066
<p>I've solved a similar issue with Amazon's S3, but the concept should be the same.</p> <p>First, I use <code>django-storages</code>, and by default, upload my media files to S3 (<code>django-storages</code> also supports Azure). Then, my team set up an NFS share mount on our Django web servers from the destination s...
1
2016-08-28T19:36:50Z
[ "python", "django", "file-upload", "django-models" ]
how to pivot complex dataframe
39,176,882
<p>I have a dataframe shown in below.</p> <pre><code>df =pd.DataFrame({'ID': [1, 2, 3, 4, 5], 'contract1' :["A", "B", "C", "D", "B"], 'contract2' :["C", "A", np.nan, "A", np.nan], 'contract3' :[np.nan, "C", np.nan, np.nan, np.nan] }) df ID contract1 contract2 contract3 1 ...
3
2016-08-27T02:29:00Z
39,176,955
<p>You can melt your original data frame to long format and then use <code>crosstab()</code> on the ID and value column:</p> <pre><code>import pandas as pd df1 = df.set_index('ID').stack().rename("Type").reset_index() pd.crosstab(df1.ID, df1.Type) # Type A B C D # ID # 1 1 0 1 0 #...
0
2016-08-27T02:44:13Z
[ "python", "pandas", "dataframe" ]
how to pivot complex dataframe
39,176,882
<p>I have a dataframe shown in below.</p> <pre><code>df =pd.DataFrame({'ID': [1, 2, 3, 4, 5], 'contract1' :["A", "B", "C", "D", "B"], 'contract2' :["C", "A", np.nan, "A", np.nan], 'contract3' :[np.nan, "C", np.nan, np.nan, np.nan] }) df ID contract1 contract2 contract3 1 ...
3
2016-08-27T02:29:00Z
39,178,599
<p>We could also do this with <code>melt/pivot_table</code></p> <pre><code>res = pd.melt(df, id_vars = ['ID'], value_vars = ['contract1', 'contract2', 'contract3']).pivot_table(index = 'ID', columns = 'value', fill_value = 0, aggfunc=len) print(res) # variable #value A B C D #I...
1
2016-08-27T07:26:49Z
[ "python", "pandas", "dataframe" ]
how to pivot complex dataframe
39,176,882
<p>I have a dataframe shown in below.</p> <pre><code>df =pd.DataFrame({'ID': [1, 2, 3, 4, 5], 'contract1' :["A", "B", "C", "D", "B"], 'contract2' :["C", "A", np.nan, "A", np.nan], 'contract3' :[np.nan, "C", np.nan, np.nan, np.nan] }) df ID contract1 contract2 contract3 1 ...
3
2016-08-27T02:29:00Z
39,179,029
<p>A Faster implementation would be to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> in conjunction with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html" rel="nofollow"><code>str.get_dummies</co...
2
2016-08-27T08:21:56Z
[ "python", "pandas", "dataframe" ]
How to use Firefox add-on SDK / places/bookmarks API from Python
39,176,887
<p>I am looking for a kick-start on how to access Firefox bookmarks, folders and tabs from Python using Firefox SDK. I already tested accessing places.sqlite through the SQLite3 library, but it can run in read-only mode since Firefox locks the database while in use.</p> <p>How do I initialize the SDK from Python (3.x...
1
2016-08-27T02:29:25Z
39,193,928
<p>I have investigated a little further, or better: asked to an experienced friend.</p> <p>The answer seems to be: you cannot invoke Firefox's SDK from anything different than Javascript. It has no bindings for other languages, also because they could not work in Firefox.</p> <p>In addition to that the guide I linked...
0
2016-08-28T17:24:38Z
[ "python", "sqlite", "firefox", "sdk" ]
Apache Storm - Error on initialization (Worker)
39,176,913
<p>storm-1.0.1</p> <p>my <strong>storm.yaml</strong>:</p> <pre><code>storm.zookeper.servers: - "zookeper" storm.zookeeper.port: 2181 # nimbus.host: "nimbus" nimbus.seeds: ["nimbus"] storm.local.dir: "/var/log/storm" supervisor.slots.ports: - 6700 - 6701 - 6702 - 6703 worker.childopts: "-Xmx768m" nimbus.chi...
1
2016-08-27T02:35:38Z
39,182,840
<p>As the error indicates the class <code>backtype.storm.messaging.netty.Context</code> is not found.</p> <blockquote> <p>Caused by: java.lang.ClassNotFoundException: backtype.storm.messaging.netty.Context</p> </blockquote> <p>In Storm <code>1.0.0</code> the was a major refactoring renaming many packages. I guess y...
1
2016-08-27T15:35:41Z
[ "java", "python", "netty", "apache-storm" ]
Apache Storm - Error on initialization (Worker)
39,176,913
<p>storm-1.0.1</p> <p>my <strong>storm.yaml</strong>:</p> <pre><code>storm.zookeper.servers: - "zookeper" storm.zookeeper.port: 2181 # nimbus.host: "nimbus" nimbus.seeds: ["nimbus"] storm.local.dir: "/var/log/storm" supervisor.slots.ports: - 6700 - 6701 - 6702 - 6703 worker.childopts: "-Xmx768m" nimbus.chi...
1
2016-08-27T02:35:38Z
39,187,727
<p>the problem was that my JAVA_HOME env var was pointing to a wrong folder.</p> <p><strong>before:</strong></p> <p>JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.101-1.b14.fc24.x86_64/jre/</p> <p><strong>after</strong>:</p> <p>JAVA_HOME=/usr/lib/jvm/java-1.8.0-oracle-1.8.0.92.x86_64/</p> <p>I got recommendation ...
0
2016-08-28T03:18:15Z
[ "java", "python", "netty", "apache-storm" ]
Formatting output of CSV file in Python
39,176,935
<p>I am creating a very rudimentary "Address Book" program in Python. I am grabbing contact data from a CSV file, the contents of which looks like the following example:</p> <pre><code>Name,Phone,Company,Email Elon Musk,454-6723,SpaceX,emusk@spacex.com Larry Page,853-0653,Google,lpage@gmail.com Tim Cook,133-0419,Appl...
3
2016-08-27T02:40:02Z
39,177,024
<p>You could use <code>format</code> to left justify your output. For example,</p> <pre><code>f = open("contactlist.csv") csv_f = csv.reader(f) for row in csv_f: print('{:&lt;15} {:&lt;15} {:&lt;20} {:&lt;25}'.format(*row)) </code></pre> <p>Output:</p> <pre><code>Name Phone Company ...
2
2016-08-27T02:56:58Z
[ "python", "csv", "format" ]
Can't find all tables in website
39,176,936
<p>I'm trying to get the code for all the tables inside <a href="http://www.pro-football-reference.com/years/1932" rel="nofollow">http://www.pro-football-reference.com/years/1932</a>, but I'm only getting the first table.</p> <p>I've tried switching the parser to lxml, but it still gives the length value of 1 for tota...
1
2016-08-27T02:40:05Z
39,177,475
<p>This is because your page render the table by javascript. So there is 2 ways to do that </p> <ul> <li>first one is using a scraping engine with javascript like Selenium.</li> <li>second one is finding inside the html content and render it yourself.</li> </ul> <p>For this code I approach the 2nd one. Found that the...
1
2016-08-27T04:31:48Z
[ "python", "beautifulsoup" ]
Python: Function not holding the value of a variable after execution
39,176,982
<p>I'm trying to convert a string input (y/n) into an integer (1/0). The function appears to be working, as when the 'convert' function is executed using 'a' as an argument, the argument is printed inside the function, however printing outside the function uses the original value of the variable 'a'. I've tried using r...
1
2016-08-27T02:49:25Z
39,177,040
<p>You never actually change <code>a</code> because you never modify the global one. You pass it into a function, where it's value is copied into a local variable <code>x</code>. You then modify <code>x</code>, but it doesn't affect <code>a</code>. Here's an alternative:</p> <pre><code>a = input("Are you happy?(y/n)")...
0
2016-08-27T03:00:13Z
[ "python", "function", "python-3.x", "variables", "if-statement" ]
Python: Function not holding the value of a variable after execution
39,176,982
<p>I'm trying to convert a string input (y/n) into an integer (1/0). The function appears to be working, as when the 'convert' function is executed using 'a' as an argument, the argument is printed inside the function, however printing outside the function uses the original value of the variable 'a'. I've tried using r...
1
2016-08-27T02:49:25Z
39,177,042
<p>That is because you are not changing <code>a</code> at all. You are simply passing <code>a</code> to the <code>convert</code> method, but this will not actually <em>change</em> what is in <code>a</code>. In order to change <code>a</code>, you need to assign <code>a</code> to the result of what <code>convert</code> w...
3
2016-08-27T03:00:42Z
[ "python", "function", "python-3.x", "variables", "if-statement" ]
How to pipe data from /dev/ttyUSB0 to a python script
39,176,985
<p>I can <code>sudo cat /dev/ttyUSB0</code> and data is flowing in the console.</p> <p>but I cant figure out how to do this in a python script, to consume the data.</p> <p>I tried</p> <pre><code>sudo python test.py &lt; /dev/ttyUSB0 sudo cat /dev/ttyUSB0 | python test.py </code></pre> <p>where test.py</p> <pre><c...
2
2016-08-27T02:50:12Z
39,177,386
<p>you can read the data from usb port/ serial port in python using <a href="https://pypi.python.org/pypi/pyserial" rel="nofollow">pyserial</a> library</p> <pre><code>import serial ser = serial.Serial('/dev/ttyUSB0', 9600) while True: data = ser.readline() if data: print(data) </code></pre> <p>you do...
0
2016-08-27T04:13:38Z
[ "python", "serial-port" ]
max sum of list elements each separated by (at least) k elements
39,177,120
<p>given a list of numbers to find the maximum sum of non-adjacent elements with time complexity o(n) and space complexity of o(1), i could use this :</p> <pre><code>sum1= 0 sum2= list[0] for i in range(1, len(list)): num= sum1 sum1= sum2+ list[i] sum2= max(num, sum2) print(max(sum2, sum1)) </code></pre>...
3
2016-08-27T03:18:25Z
39,177,241
<p>EDIT: I had misunderstood the question, if you need to have 'atleast' k elements in between then following is an <code>O(n^2)</code> solution.</p> <p>If the numbers are non-negative, then the DP recurrence relation is:</p> <pre><code>DP[i] = max (DP[j] + A[i]) For all j st 0 &lt;= j &lt; i - k = A[i] otherw...
2
2016-08-27T03:40:14Z
[ "python", "algorithm", "dynamic-programming" ]
max sum of list elements each separated by (at least) k elements
39,177,120
<p>given a list of numbers to find the maximum sum of non-adjacent elements with time complexity o(n) and space complexity of o(1), i could use this :</p> <pre><code>sum1= 0 sum2= list[0] for i in range(1, len(list)): num= sum1 sum1= sum2+ list[i] sum2= max(num, sum2) print(max(sum2, sum1)) </code></pre>...
3
2016-08-27T03:18:25Z
39,178,071
<p>It's possible to solve this with space <em>O(k)</em> and time <em>O(nk)</em>. if <em>k</em> is a constant, this fits the requirements in your question.</p> <p>The algorithm loops from position <em>k + 1</em> to <em>n</em>. (If the array is shorter than that, it can obviously be solved in <em>O(k)</em>). At each ste...
4
2016-08-27T06:12:12Z
[ "python", "algorithm", "dynamic-programming" ]
max sum of list elements each separated by (at least) k elements
39,177,120
<p>given a list of numbers to find the maximum sum of non-adjacent elements with time complexity o(n) and space complexity of o(1), i could use this :</p> <pre><code>sum1= 0 sum2= list[0] for i in range(1, len(list)): num= sum1 sum1= sum2+ list[i] sum2= max(num, sum2) print(max(sum2, sum1)) </code></pre>...
3
2016-08-27T03:18:25Z
39,178,108
<p>Not sure for the complexity but coding efficiency landed me with</p> <pre><code>max([sum(l[i::j]) for j in range(k,len(l)) for i in range(len(l))]) </code></pre> <p>(I've replace <code>list</code> variable by <code>l</code> not to step on a keyword).</p>
0
2016-08-27T06:18:34Z
[ "python", "algorithm", "dynamic-programming" ]
max sum of list elements each separated by (at least) k elements
39,177,120
<p>given a list of numbers to find the maximum sum of non-adjacent elements with time complexity o(n) and space complexity of o(1), i could use this :</p> <pre><code>sum1= 0 sum2= list[0] for i in range(1, len(list)): num= sum1 sum1= sum2+ list[i] sum2= max(num, sum2) print(max(sum2, sum1)) </code></pre>...
3
2016-08-27T03:18:25Z
39,185,319
<p>Here's a quick implementation of the algorithm described by Ami Tavory (as far as I understand it). It should work for any sequence, though if your list is all negative, the maximum sum will be <code>0</code> (the sum of an empty subsequence).</p> <pre><code>import collections def max_sum_separated_by_k(iterable, ...
1
2016-08-27T20:10:46Z
[ "python", "algorithm", "dynamic-programming" ]
Python Syntax Error: expected an intended block
39,177,135
<h1> So first i clicked on Run Module</h1> <p><a href="http://i.stack.imgur.com/N9BfB.png" rel="nofollow"><img src="http://i.stack.imgur.com/N9BfB.png" alt="So first i clicked on Run Module "></a></p> <h1>Then this came up</h1> <p><a href="http://i.stack.imgur.com/Ei0U8.png" rel="nofollow"><img src="http://i.stack....
1
2016-08-27T03:22:50Z
39,177,147
<p>You have to indent the <code>print('Oh no')</code>:</p> <pre><code>if criminal=='Y': print('Oh no') elif criminal=='N': print('Thank god!') </code></pre>
1
2016-08-27T03:24:58Z
[ "python", "syntax-error" ]
Python Syntax Error: expected an intended block
39,177,135
<h1> So first i clicked on Run Module</h1> <p><a href="http://i.stack.imgur.com/N9BfB.png" rel="nofollow"><img src="http://i.stack.imgur.com/N9BfB.png" alt="So first i clicked on Run Module "></a></p> <h1>Then this came up</h1> <p><a href="http://i.stack.imgur.com/Ei0U8.png" rel="nofollow"><img src="http://i.stack....
1
2016-08-27T03:22:50Z
39,177,152
<p>You need to indent after an <code>if</code> and the <code>elif</code>:</p> <pre><code>if criminal=='Y': print('Oh no') elif criminal=='N': print('Thank god!') </code></pre> <p>Also, don't indent after the <code>import</code>:</p> <pre><code>import time print("First we need to know you.") </code></pre>
3
2016-08-27T03:25:24Z
[ "python", "syntax-error" ]
using map function to square a list
39,177,332
<p>I have a list which I want to square each of them.</p> <p>this is what I have done</p> <pre><code>def square(x): return x*x numbers = [1,2,3,4,5,6] squares = map(square, numbers) squares_as_strings = str(squares) print(','.join(squares_as_strings)) </code></pre> <p>but the answer is this</p> <pre><code>...
0
2016-08-27T04:03:09Z
39,177,337
<p>Just solve it with simple list comprehension.</p> <pre><code>squares = [i*i for i in numbers] </code></pre> <p>Or, using map:</p> <pre><code>squares = map(lambda x:x*x,numbers) </code></pre>
1
2016-08-27T04:04:07Z
[ "python", "string", "list" ]
using map function to square a list
39,177,332
<p>I have a list which I want to square each of them.</p> <p>this is what I have done</p> <pre><code>def square(x): return x*x numbers = [1,2,3,4,5,6] squares = map(square, numbers) squares_as_strings = str(squares) print(','.join(squares_as_strings)) </code></pre> <p>but the answer is this</p> <pre><code>...
0
2016-08-27T04:03:09Z
39,177,356
<p>If you want to use the <code>map</code> function, you can use:</p> <pre><code>squares = list(map(square, numbers)) </code></pre> <p>The <code>map</code> function will return a <code>map</code> object.</p>
0
2016-08-27T04:07:50Z
[ "python", "string", "list" ]
using map function to square a list
39,177,332
<p>I have a list which I want to square each of them.</p> <p>this is what I have done</p> <pre><code>def square(x): return x*x numbers = [1,2,3,4,5,6] squares = map(square, numbers) squares_as_strings = str(squares) print(','.join(squares_as_strings)) </code></pre> <p>but the answer is this</p> <pre><code>...
0
2016-08-27T04:03:09Z
39,177,363
<p>The problem is in these lines:</p> <pre><code>squares_as_strings = str(squares) print(','.join(squares_as_strings)) </code></pre> <p>Applying <code>str</code> to the <code>squares</code> array does not make each number a string. Instead it gives this - <code>'[1, 2, 3]'</code>, which is a string, not an array of s...
1
2016-08-27T04:08:59Z
[ "python", "string", "list" ]
using map function to square a list
39,177,332
<p>I have a list which I want to square each of them.</p> <p>this is what I have done</p> <pre><code>def square(x): return x*x numbers = [1,2,3,4,5,6] squares = map(square, numbers) squares_as_strings = str(squares) print(','.join(squares_as_strings)) </code></pre> <p>but the answer is this</p> <pre><code>...
0
2016-08-27T04:03:09Z
39,177,368
<pre><code>def square(x): return x*x numbers = [1,2,3,4,5,6] squares = map(square, numbers) print(str(squares)) #str() in not needed </code></pre>
1
2016-08-27T04:10:09Z
[ "python", "string", "list" ]
using map function to square a list
39,177,332
<p>I have a list which I want to square each of them.</p> <p>this is what I have done</p> <pre><code>def square(x): return x*x numbers = [1,2,3,4,5,6] squares = map(square, numbers) squares_as_strings = str(squares) print(','.join(squares_as_strings)) </code></pre> <p>but the answer is this</p> <pre><code>...
0
2016-08-27T04:03:09Z
39,177,369
<p>You map the <code>square</code> function, but you're not mapping the <code>str</code> function. Your <code>squares_as_strings</code> is one string, of the entire list.</p> <p>Change <code>str(squares)</code> to <code>map(str, squares)</code>.</p>
1
2016-08-27T04:10:10Z
[ "python", "string", "list" ]
using map function to square a list
39,177,332
<p>I have a list which I want to square each of them.</p> <p>this is what I have done</p> <pre><code>def square(x): return x*x numbers = [1,2,3,4,5,6] squares = map(square, numbers) squares_as_strings = str(squares) print(','.join(squares_as_strings)) </code></pre> <p>but the answer is this</p> <pre><code>...
0
2016-08-27T04:03:09Z
39,177,372
<p>This is happening because you are calling a <code>join</code> on a string and not on a <code>list</code>. Ultimately, you are not handling the result of your <code>map</code> properly.</p> <p>If you are using Python 2, your map will give you a list, so simply print out <code>squares</code> and you will have your ex...
1
2016-08-27T04:10:17Z
[ "python", "string", "list" ]
Python numpy reshape issues
39,177,438
<p>I am working with machine learning and numpy and having issues with the <code>np.reshape()</code> function. My data sizes are reading in the variable console as Dataframe(22,5), x(21,4),x_lately(1,4), y(22,). I tried reshaping them with <code>np.reshape(22,5)</code> since that is the dataframe size and it is giving...
0
2016-08-27T04:23:28Z
39,177,816
<p>You really need to describe your data better.</p> <p>I can imagine the pieces fitting together:</p> <pre><code>Dataframe(22,5), x(21,4),x_lately(1,4), y(22,) </code></pre> <p>The dataframe has 22 rows, 5 columns. <code>y</code> could be one column (22 items). <code>x</code> could be most of the 4 other columns,...
0
2016-08-27T05:32:17Z
[ "python", "numpy", "machine-learning" ]
Trouble parsing data from website into dictionary: python3
39,177,504
<p>I'm trying to parse data from a stock exhcange website and for example for a particular stock the URL is</p> <p><a href="https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=SGJHL" rel="nofollow">https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=S...
0
2016-08-27T04:37:07Z
39,177,978
<p>It seems that this is a JSON response. You can use JSON library to access to the key values like this :</p> <pre><code>jsonData = json.load('YOUR RAW DATA') print (jsonData['bcStartDate']) </code></pre>
0
2016-08-27T05:56:05Z
[ "python", "parsing", "beautifulsoup" ]
exception when get a subset of a pandas data frame
39,177,556
<p>I want to get the first, 2nd and 4th column of a data frame, which is column <code>c_a,c_b,c_d</code>, what is wrong with my code?</p> <p>I post my code, data (123.csv) and error message,</p> <pre><code>sample = pd.read_csv('123.csv', header=None, skiprows=1, dtype={0:str, 1:str, 2:str, 3:float}) sample.column...
1
2016-08-27T04:45:59Z
39,177,583
<p>You need to use <code>df.iloc[:, [0, 1, 3]]</code> instead (or <code>df[[0, 1, 3]]</code>).</p> <p>Comma separates the row indexer and the column indexer. </p>
2
2016-08-27T04:50:10Z
[ "python", "python-2.7", "pandas", "numpy", "dataframe" ]
exception when get a subset of a pandas data frame
39,177,556
<p>I want to get the first, 2nd and 4th column of a data frame, which is column <code>c_a,c_b,c_d</code>, what is wrong with my code?</p> <p>I post my code, data (123.csv) and error message,</p> <pre><code>sample = pd.read_csv('123.csv', header=None, skiprows=1, dtype={0:str, 1:str, 2:str, 3:float}) sample.column...
1
2016-08-27T04:45:59Z
39,177,594
<p>Try </p> <pre><code>X = sample[['c_a', 'c_b', 'c_d']] </code></pre> <p>More explicit than using <code>iloc</code>.</p>
2
2016-08-27T04:52:26Z
[ "python", "python-2.7", "pandas", "numpy", "dataframe" ]
Variant Of Two Sum Solution Extremely Slow in Objective C
39,177,643
<p>I'm taking an algorithms design and analysis course, and was given programming question which is a variant of the two sum problem:</p> <p><strong>The input is an array of 1 million integers, both positive and negative. Compute the number of target values t in the interval [-10000,10000] (inclusive) such that there...
0
2016-08-27T05:02:35Z
39,183,747
<blockquote> <p>Is there something I'm missing about the difference between these two solutions that would explain such a vast difference in performance?</p> </blockquote> <p>You are solving the problem "backwards". You start with <em>t</em> and then search for a pair which sums to it. Think of the extreme example o...
2
2016-08-27T17:14:55Z
[ "python", "objective-c", "algorithm", "hashtable", "big-o" ]
Executing an insert into postgres using psycopg2
39,177,660
<p>I'm trying to insert data using psycopg2 into postgres. Here is the psuedo code I have. It seems to run without error but when I use navicat to check, it doesn't seem to update in the database. I did restart navicat to be sure.</p> <pre><code>conn = psycopg2.connect("dbname=dbname user=username password = **** hos...
1
2016-08-27T05:05:45Z
39,177,694
<p>commit the data?</p> <pre><code>conn.commit() </code></pre>
0
2016-08-27T05:12:40Z
[ "python", "postgresql", "psycopg2" ]
My python code is not inserting data into the databse. I have no idea why?
39,177,697
<p>My code is just making a database which stores links. But due to some reason when i open the database, it is an empty table. I have no idea why does this happen.</p> <p>Not Causing any trouble</p> <pre><code>#!/usr/bin/python import urllib2 from BeautifulSoup import * import sqlite3 count = 0 ecount = 0 aj = list...
1
2016-08-27T05:13:23Z
39,177,910
<p>I think you should not use query like <code>sql = '''INSERT INTO URL(LINKS, ID) VALUES (%s, %d)'''</code></p> <p>For inserting variables directly in your query use format strings like this :</p> <pre><code>sql = cur.execute("INSERT INTO URL(LINKS, ID) VALUES (?,?)",(x,y)) </code></pre>
0
2016-08-27T05:46:06Z
[ "python", "sql", "database", "sqlite" ]
My python code is not inserting data into the databse. I have no idea why?
39,177,697
<p>My code is just making a database which stores links. But due to some reason when i open the database, it is an empty table. I have no idea why does this happen.</p> <p>Not Causing any trouble</p> <pre><code>#!/usr/bin/python import urllib2 from BeautifulSoup import * import sqlite3 count = 0 ecount = 0 aj = list...
1
2016-08-27T05:13:23Z
39,177,916
<p>In this line:</p> <pre><code>sql = '''INSERT INTO URL(LINKS, ID) VALUES (%s, %d)''' </code></pre> <p>Try changing it to this:</p> <pre><code>sql = '''INSERT INTO URL(LINKS, ID) VALUES (?, ?)''' </code></pre> <p>This post <a href="http://stackoverflow.com/questions/13613037/is-this-python-code-vulnerable-to-sql-i...
1
2016-08-27T05:46:51Z
[ "python", "sql", "database", "sqlite" ]
Python - sys.stdout.flush() on 2 lines in python 2.7
39,177,788
<p>I am writing with python 2.7</p> <p>I have the following code:</p> <pre><code>a = 0 b = 0 while True: a += 1 b += 1 print str(a) print str(b) </code></pre> <p>The output looks like:</p> <pre><code>1 1 2 2 3 3 4 .... </code></pre> <p>And want to flush these two lines with <code>stdout.flush()</co...
0
2016-08-27T05:27:10Z
39,177,802
<p>to go to the upper line from the current one this has to be written on the stdout <code>\x1b[1A</code></p> <pre><code>CURSOR_UP_ONE = '\x1b[1A' </code></pre> <p>to erase the contents of the line <code>\x1b[2K</code> has to be written on stdout.</p> <pre><code>ERASE_LINE = '\x1b[2K' </code></pre> <p>this way you...
3
2016-08-27T05:30:30Z
[ "python", "python-2.7", "stdout", "flush", "sys" ]
matplotlib.pyplot.plot() doesn't show the graph
39,177,983
<p>I am learning Python and I have a side project to learn to display data using matplotlib.pyplot module. Here is an example to display the data using dates[] and prices[] as data. Does anyone know why we need line 5 and line 6? I am confused why this step is needed to have the graph displayed. </p> <pre><code>f...
0
2016-08-27T05:56:47Z
39,178,073
<p>Line 5 and 6 transform what Im assuming are row vectors (im not sure how <code>data</code> and <code>prices</code> are encoded before this transformation) into column vectors. So now you have vectors that look like this. </p> <pre><code>[0, 1, 2, 3] </code></pre> <p>which is the form that <code>linear_model....
0
2016-08-27T06:12:24Z
[ "python", "matplotlib", "linear-regression" ]
matplotlib.pyplot.plot() doesn't show the graph
39,177,983
<p>I am learning Python and I have a side project to learn to display data using matplotlib.pyplot module. Here is an example to display the data using dates[] and prices[] as data. Does anyone know why we need line 5 and line 6? I am confused why this step is needed to have the graph displayed. </p> <pre><code>f...
0
2016-08-27T05:56:47Z
39,178,224
<p>try the following in terminal to check the backend:</p> <pre><code>import matplotlib import matplotlib.pyplot print matplotlib.backends.backend </code></pre> <p>If it shows 'agg', it is a non-interactive one and wont show but plt.savefig works.</p> <p>To show the plot, you need to switch to TkAgg or Qt4Agg.</p> ...
1
2016-08-27T06:35:48Z
[ "python", "matplotlib", "linear-regression" ]
matplotlib.pyplot.plot() doesn't show the graph
39,177,983
<p>I am learning Python and I have a side project to learn to display data using matplotlib.pyplot module. Here is an example to display the data using dates[] and prices[] as data. Does anyone know why we need line 5 and line 6? I am confused why this step is needed to have the graph displayed. </p> <pre><code>f...
0
2016-08-27T05:56:47Z
39,178,627
<p>My approach is exactly like yours but still without line 5 and 6 display is correct. I think those line are unnecessary. It seems that you do not need fit() function because of your input data are in row format.</p>
0
2016-08-27T07:30:43Z
[ "python", "matplotlib", "linear-regression" ]
Interpolate a discrete grid of dots
39,178,021
<p>I'm referencing <a href="http://stackoverflow.com/questions/5146025/python-scipy-2d-interpolation-non-uniform-data">this question</a> and <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.html" rel="nofollow">this documentation</a> in trying to turn a set of points (the p...
0
2016-08-27T06:05:08Z
39,181,082
<p>First, your uncertain points are mainly at an edge, so it's actually <a href="http://stackoverflow.com/questions/2745329/how-to-make-scipy-interpolate-give-an-extrapolated-result-beyond-the-input-range">extrapolation</a>. Second, interpolation methods built into <code>scipy</code> deal with continuous functions defi...
1
2016-08-27T12:20:21Z
[ "python", "numpy", "scipy", "interpolation" ]
Python - removing some punctuation from text
39,178,054
<p>I want Python to remove only some punctuation from a string, let's say I want to remove all the punctuation except '@'</p> <pre><code>import string remove = dict.fromkeys(map(ord, '\n ' + string.punctuation)) sample = 'The quick brown fox, like, totally jumped, @man!' sample.translate(remove) </code></pre> <p>Here...
1
2016-08-27T06:09:21Z
39,178,095
<p><a href="https://docs.python.org/2/library/string.html#string.punctuation" rel="nofollow">str.punctuation</a> contains all the punctuations. Remove <code>@</code> from it. Then replace with <code>''</code> whenever you get that punctuation string. </p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; a = string.punct...
2
2016-08-27T06:16:11Z
[ "python" ]
Python - removing some punctuation from text
39,178,054
<p>I want Python to remove only some punctuation from a string, let's say I want to remove all the punctuation except '@'</p> <pre><code>import string remove = dict.fromkeys(map(ord, '\n ' + string.punctuation)) sample = 'The quick brown fox, like, totally jumped, @man!' sample.translate(remove) </code></pre> <p>Here...
1
2016-08-27T06:09:21Z
39,178,110
<p>Just remove the character you don't want to touch from the replacement string:</p> <pre><code>import string remove = dict.fromkeys(map(ord, '\n' + string.punctuation.replace('@',''))) sample = 'The quick brown fox, like, totally jumped, @man!' sample.translate(remove) </code></pre> <p>Also note that I changed <cod...
2
2016-08-27T06:18:40Z
[ "python" ]
How to split a string on commas or periods in nltk
39,178,154
<p>I want to separate a string on commas and/or periods in nltk. I've tried with <code>sent_tokenize()</code> but it separates only on periods.</p> <p>I've also tried this code</p> <pre><code>from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktLanguageVars ex_sent = "This is an example showing sentence filtr...
0
2016-08-27T06:26:10Z
39,190,983
<p>How about something simpler with <code>re</code>:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; sent = "This is an example showing sentence filtration.This is how it is done, in case of Python I want to learn more. So, that i can have some experience over it, by it I mean python." &gt;&gt;&gt; re.split(r'[.,]'...
1
2016-08-28T11:52:38Z
[ "python", "nltk" ]
Testing within a python class method
39,178,265
<p>I am using unittest in python to test a project. The project defines classes that are intended for other python developers to subclass. The project can then be run and utilizes the subclasses that the user has written.</p> <p>I want to test that the subclass's methods are being passed correct data by the project. ...
0
2016-08-27T06:42:02Z
39,178,302
<p>You can try unittest in docstring.</p> <p>Have a look at this:</p> <p><a href="http://docs.python-guide.org/en/latest/writing/tests/#doctest" rel="nofollow">http://docs.python-guide.org/en/latest/writing/tests/#doctest</a></p>
-1
2016-08-27T06:47:02Z
[ "python", "class", "python-unittest" ]
Testing within a python class method
39,178,265
<p>I am using unittest in python to test a project. The project defines classes that are intended for other python developers to subclass. The project can then be run and utilizes the subclasses that the user has written.</p> <p>I want to test that the subclass's methods are being passed correct data by the project. ...
0
2016-08-27T06:42:02Z
39,195,722
<p>I was able to get this working by using <code>raise</code> to pass a custom exception up to the <code>unittest.TestCase</code>. The custom exception can be packed with whatever data needs to be tested. I don't show it here, but <code>test_helper.py</code> is just a bare bones subclass of <code>Exception</code>.</p...
0
2016-08-28T20:58:18Z
[ "python", "class", "python-unittest" ]
Phyton 3.5 "for loop" "enumerate()” Select Word from List
39,178,294
<p>Hi I'm new here I've just started learning python</p> <p>Individual words in wordList will be referred to as “word” as a variable.</p> <p>who would I set this up this for a python english grammar gen program by the way. </p> <p>also I wanna try to Enter a loop that repeats once for each word in wordList. Try...
-2
2016-08-27T06:45:53Z
39,178,326
<p>if your question is how to use enumerate, here's an application for your code sample:</p> <pre><code>import random candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'PIGEON', 'POSTER', 'TELEVISIO...
0
2016-08-27T06:50:17Z
[ "python", "python-3.x", "for-loop", "enumerate" ]
Capture keyPressEvent in minimized PyQt application
39,178,311
<p>I am trying to write an error reporting application and would like to keep it as a tray icon for the most part - but the idea is to maximize it with a specific key combination (e.g. "Ctrl+Alt+H", or something like it).</p>
0
2016-08-27T06:48:10Z
39,180,938
<p>Look like not possible as is. But I found that. It should be a start of an answer for you:</p> <p><a href="http://libqxt.bitbucket.org/doc/tip/qxtglobalshortcut.html" rel="nofollow">http://libqxt.bitbucket.org/doc/tip/qxtglobalshortcut.html</a></p> <p><a href="http://stackoverflow.com/questions/23193038/how-to-det...
0
2016-08-27T12:03:32Z
[ "python", "pyqt", "keyboard-shortcuts", "trayicon" ]
Capture keyPressEvent in minimized PyQt application
39,178,311
<p>I am trying to write an error reporting application and would like to keep it as a tray icon for the most part - but the idea is to maximize it with a specific key combination (e.g. "Ctrl+Alt+H", or something like it).</p>
0
2016-08-27T06:48:10Z
39,198,155
<p>Thanks for reply, I was looking deeper into some of the codes I had in my repo and found out this - <a href="https://sourceforge.net/p/pyhook/wiki/PyHook_Tutorial/" rel="nofollow">https://sourceforge.net/p/pyhook/wiki/PyHook_Tutorial/</a></p> <p>This is specifically for windows but saw pyxhook for linux</p> <p><a...
0
2016-08-29T03:36:11Z
[ "python", "pyqt", "keyboard-shortcuts", "trayicon" ]
value counts of group by in pandas
39,178,329
<p>I am new to pandas and was trying to learn about this feature.</p> <pre><code>iris = datasets.load_iris() grps = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] iris = pd.DataFrame(iris.data[:,0],columns = ["SL"]) iris['bins'] = pd.cut(iris["SL"], 10 ,labels = grps ) iris['target'] = datasets.load_iris().target...
1
2016-08-27T06:50:30Z
39,179,715
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> after you have binned them into bins corresponding to the groups specified in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel=...
1
2016-08-27T09:48:29Z
[ "python", "pandas", "matplotlib", "dataframe" ]
value counts of group by in pandas
39,178,329
<p>I am new to pandas and was trying to learn about this feature.</p> <pre><code>iris = datasets.load_iris() grps = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] iris = pd.DataFrame(iris.data[:,0],columns = ["SL"]) iris['bins'] = pd.cut(iris["SL"], 10 ,labels = grps ) iris['target'] = datasets.load_iris().target...
1
2016-08-27T06:50:30Z
39,180,624
<p>Try this:</p> <pre><code>In [83]: import seaborn as sns In [84]: x = iris.groupby(['target','bins']).size().to_frame('occurences').reset_index() In [85]: x Out[85]: target bins occurences 0 0 1 9 1 0 2 19 2 0 3 12 3 0 4 9 4 ...
1
2016-08-27T11:29:33Z
[ "python", "pandas", "matplotlib", "dataframe" ]
Python sort sprite dict into new dict sorted by name
39,178,366
<p>I have a dict which is part of a <code>SpriteSheet</code> class of the attribute <code>sprite_info</code>. <code>sprite info</code> holds the names and location and xd/yd of each sprite on the sheet, i.e. </p> <pre><code>{'stone_Wall' : { 'x': '781', 'xd': '70', 'y': '568', 'yd': '70'} ... } </code></pre> <p>What ...
1
2016-08-27T06:55:26Z
39,178,476
<p>You can't sort a <code>dict</code>, as it uses its own sorted tree structure internally to keep efficient.</p> <p>You can use <code>OrderedDict</code> which will keep track of the order elements are added.</p> <p>To created a sorted <code>OrderedDict</code> from a <code>dict</code>, sort the key/value pairs from t...
0
2016-08-27T07:10:15Z
[ "python", "python-2.7", "sorting", "dictionary", "pygame" ]
Exception Value: Cannot assign "x": "y" must be a "z" instance
39,178,406
<p>I have a script to pull in football fixtures into my mySQL database. If I do not try to pull in the seasonid it works. But when I put the seasonid in it breaks and I am unsure why. Any help would be appreciated.</p> <p>The models are as follows:</p> <pre><code>class StraightredSeason(models.Model): seasonid...
0
2016-08-27T07:01:12Z
39,178,514
<p>Try to replace <code>soccerseason = 1025</code> with <code>soccerseason_id = 1025</code>. <code>soccerseason</code> is a relationship to <code>StraightredSeason</code> so you should provide an instance of it when trying to set this attribute.</p>
0
2016-08-27T07:15:20Z
[ "python", "mysql", "django" ]
Exception Value: Cannot assign "x": "y" must be a "z" instance
39,178,406
<p>I have a script to pull in football fixtures into my mySQL database. If I do not try to pull in the seasonid it works. But when I put the seasonid in it breaks and I am unsure why. Any help would be appreciated.</p> <p>The models are as follows:</p> <pre><code>class StraightredSeason(models.Model): seasonid...
0
2016-08-27T07:01:12Z
39,178,524
<p>You can't set a <code>ForeignKey</code> object as <code>int</code>. You can instead set the <code>ForeignKey</code> <em>value</em> (id associated with the FK object) by appending <code>_id</code> to the field:</p> <pre><code>fixtureUpdate = StraightredFixture(fixtureid=fixture['Id'], ...
1
2016-08-27T07:16:42Z
[ "python", "mysql", "django" ]
how to run a python file 20 times with 1000 iterations
39,178,417
<p>i want to run a python file file.py 20 times with 1000 iterations with single run click so that i dont need to click run 20 times manually.</p> <pre><code>Init() globalBest=pop[0].chromosome # Saving Result fp=open(resultFileName,"w"); fp.write("Iteration,Fitness,Chromosomes\n") for i in range(0,iterations): ...
1
2016-08-27T07:02:24Z
39,178,510
<p>You can write another script which call your script 20 times. Make a loop and call the file.py 20 times in it.</p>
0
2016-08-27T07:15:02Z
[ "python", "optimization" ]
how to run a python file 20 times with 1000 iterations
39,178,417
<p>i want to run a python file file.py 20 times with 1000 iterations with single run click so that i dont need to click run 20 times manually.</p> <pre><code>Init() globalBest=pop[0].chromosome # Saving Result fp=open(resultFileName,"w"); fp.write("Iteration,Fitness,Chromosomes\n") for i in range(0,iterations): ...
1
2016-08-27T07:02:24Z
39,179,050
<p>try:</p> <pre><code>for iteration in range(20): Init() globalBest = pop[0].chromosome # Saving Result fp = open(resultFileName, "a") fp.write("Iteration,Fitness,Chromosomes\n") for i in range(0, iterations): Crossover() Mutation() MemoriseGlobalBest() if f...
0
2016-08-27T08:25:32Z
[ "python", "optimization" ]
Sublime Text 3-Anaconda openCV docstring not working?
39,178,460
<p>I'm using the Anaconda plugin in Sublime Text 3. Everything was working exactly as I expected. I love Docstring. It worked great and saved me a lot of time. </p> <p>But when I tried <code>import cv2</code>, cv2 was not on the autoComplete list. AutoComplete and docstring wouldn't work for anything that is in openCV...
0
2016-08-27T07:07:48Z
39,184,691
<p>This setting is not documented in the default <code>Anaconda.sublime-settings</code> file, but I found it once on the <a href="http://damnwidget.github.io/anaconda/anaconda_settings/#toc_5" rel="nofollow">Anaconda website</a>: <code>"extra_paths"</code>. Open your <code>.sublime-project</code> file, and add the foll...
0
2016-08-27T18:59:06Z
[ "python", "opencv", "sublimetext3", "sublime-anaconda" ]
pandas inner join performance issue
39,178,533
<p>I have two csv file and I load them into pandas data frame. One file is large, about 10M rows and 20 columns (all string type) and size is around 1G bytes, the other file is small, about 5k rows, and 5 columns and size is around 1M. I want to do inner join by a single common column between the two data frame.</p> <...
2
2016-08-27T07:17:54Z
39,192,848
<p>Check the cardinality of 'uid' column on both sides. It is most probable that your join is multiplying the data manyfold. For example, if you have uid with value 1 in 100 records of dataframe1 and in 10 records in dataframe2, your join would yield 1000 records.</p> <p>to check the cardinality, I would do the follow...
2
2016-08-28T15:25:35Z
[ "python", "performance", "python-2.7", "pandas", "dataframe" ]
Radiobutton Selection
39,178,537
<p>I am trying to make a game by combining Turtle and Tkinter. My code is working good but I have a problem with selection of <code>Radiobutton</code> part. When I try to select the "Black" (colored) radiobutton, I am not able to select it, however, there is no problem with other colors selection. Another problem is th...
1
2016-08-27T07:18:16Z
39,178,730
<p>For your second problem:</p> <pre><code>from tkinter import * root = Tk() selvar = StringVar() selvar.set(' ') rb1 = Radiobutton(root, variable=selvar, value='a') rb1.pack() rb2 = Radiobutton(root, variable=selvar, value='b') rb2.pack() </code></pre> <p>This is for <code>StringVar</code>. And for <code>IntVar</c...
2
2016-08-27T07:45:25Z
[ "python", "tkinter", "turtle-graphics" ]
Radiobutton Selection
39,178,537
<p>I am trying to make a game by combining Turtle and Tkinter. My code is working good but I have a problem with selection of <code>Radiobutton</code> part. When I try to select the "Black" (colored) radiobutton, I am not able to select it, however, there is no problem with other colors selection. Another problem is th...
1
2016-08-27T07:18:16Z
39,179,055
<p>Here is my code after correction</p> <pre><code>import tkinter from tkinter import * import turtle import sys sc=Tk() sc.geometry("1000x1000+100+100") var= IntVar() pensize=StringVar() angle=StringVar() radius=StringVar() lenght=StringVar() #FRAMES fr1=Frame(sc,height=200,width=200,bd=4,bg="light green",takefocus...
0
2016-08-27T08:25:58Z
[ "python", "tkinter", "turtle-graphics" ]
Tuple error (numpy)
39,178,550
<p>I padded my data using <code>np.pad(x,[(0,0)], mode='constant')</code> and got this error:</p> <pre><code>ValueError: Unable to create correctly shaped tuple from [(0, 0). </code></pre> <p>My <code>x</code> has shape (21, 4) and I want to pad it to get a shape of (22,4).</p> <p>Does anyone know what is happening...
1
2016-08-27T07:20:46Z
39,178,612
<p>The rank of the first argument has to match the number of pairs in the second argument.</p> <p>For example, observe that this gives the error that you see:</p> <pre><code>&gt;&gt;&gt; x = np.ones((21, 4)) &gt;&gt;&gt; np.pad(x, [(0,0)], mode='constant') Traceback (most recent call last): [...snip...] ValueError:...
0
2016-08-27T07:28:54Z
[ "python", "numpy" ]
Shipping python runtime with excel
39,178,624
<p>According to the xlwings website:-</p> <p>Easy deployment: The receiver of an xlwings-powered spreadsheets only needs Python with minimal dependencies — or nothing at all when shipped with the Python runtime.</p> <p>I have installed Anaconda and written some python code and run it from Excel using xlwings</p> <...
0
2016-08-27T07:30:19Z
39,179,972
<p>"When shipped with the Python runtime" is referring to the underdocumented approach of using a freezer (like py2exe or cx_Freeze) and creating a self-contained directory that includes the whole Python dependency.</p> <p>There is the standalone version of the <a href="https://github.com/ZoomerAnalytics/xlwings/tree/...
0
2016-08-27T10:16:02Z
[ "python", "xlwings" ]
How to filter a nested dictionary (pythonic way) for a specific value using map or filter instead of list comprehensions?
39,178,715
<p>I've a nested dictionary.</p> <pre><code>&gt;&gt;&gt; foo = {'m': {'a': 10}, 'n': {'a': 20}} &gt;&gt;&gt; </code></pre> <p>I'd like to filter specific values, based on the values of 'a'.</p> <p>I can use list comprehensions for the purpose.</p> <pre><code>&gt;&gt;&gt; [foo[n] for n in foo if foo[n]['a'] == 10] ...
1
2016-08-27T07:42:43Z
39,178,728
<p>A list comprehension can do this beautifully.</p> <pre><code>&gt;&gt;&gt; foo = {'m': {'a': 10}, 'n': {'a': 20}} &gt;&gt;&gt; [v for v in foo.values() if 10 in v.values()] [{'a': 10}] </code></pre> <p>You don't need the for loop or the list comprehension if you are matching against a known key in the dictionary.</...
2
2016-08-27T07:45:18Z
[ "python", "list", "dictionary", "list-comprehension", "python-3.5" ]
How to filter a nested dictionary (pythonic way) for a specific value using map or filter instead of list comprehensions?
39,178,715
<p>I've a nested dictionary.</p> <pre><code>&gt;&gt;&gt; foo = {'m': {'a': 10}, 'n': {'a': 20}} &gt;&gt;&gt; </code></pre> <p>I'd like to filter specific values, based on the values of 'a'.</p> <p>I can use list comprehensions for the purpose.</p> <pre><code>&gt;&gt;&gt; [foo[n] for n in foo if foo[n]['a'] == 10] ...
1
2016-08-27T07:42:43Z
39,183,551
<p>If you want to return the full nested dictionary if it contains <code>a</code>, a list comprehension is probably the cleanest way. Your initial list comprehension would work:</p> <pre><code>[foo[n] for n in foo if foo[n]['a'] == 10] </code></pre> <p>You can also avoid the lookup on <code>n</code> with:</p> <pre><...
1
2016-08-27T16:53:10Z
[ "python", "list", "dictionary", "list-comprehension", "python-3.5" ]
Access docker image through web server
39,178,736
<p>I am using a docker image and I can successfully access it and run it through a python script from my host machine. I am using sidomo for that purpose. The script works fine locally but doesn't give any output when I run it on server. Even the docker images command doesn't give correct output on server. The output i...
0
2016-08-27T07:45:39Z
39,178,812
<p>Accessing the docker daemon remotely is dangerous. It is equivalent to root access. This is why the daemon's socket can be accessed by root and on most setups the members of the <code>docker</code> group only.</p> <p>Now I'm at a point where I'm unsure to tell you how to allow access for your application. You don't...
0
2016-08-27T07:54:50Z
[ "python", "web", "docker", "server", "daemon" ]
Python Convert Bytes Literal To Image
39,178,896
<p>In Python3 I am working on a music playing application. I'm using a library called TinyTag to get metadata from the music files, like the title and artist. It also supports getting the album art. When the art is retrieved it loads it as what I believe is called a bytes literal (I'm unfamiliar with it). I was wonderi...
0
2016-08-27T08:05:18Z
39,179,061
<p>The string you see are the contents of an image file. You can just save the string directly to a file:</p> <pre><code>$ file /tmp/file.mp3 /tmp/file.mp3: Audio file with ID3 version 2.3.0, contains: MPEG ADTS, layer III, v1, 128 kbps, 44.1 kHz, JntStereo $ ipython Python 2.7.12 (default, Aug 9 2016, 15:48:18) Typ...
3
2016-08-27T08:26:43Z
[ "python", "python-3.x", "music-player" ]
Python sort (json) list by calculated value
39,178,905
<p>I have originally a JSON format with products and the challenge is to sort this list by the best price per unit (prdata3, prdata2, prdata1): </p> <pre><code>{'prdata3': {'variation': 'stand', 'price': '78 54', 'amount': '6', 'url': 'https://www.productwebaddress.com/3'}, 'prdata2': {'variation': 'stand', '...
-2
2016-08-27T08:06:11Z
39,179,105
<p>You can't sort a dictionary, as dictionary have no order. </p> <p>But you can do the following:</p> <pre><code>print sorted(a.items(),key=lambda x:float(x[1]['price'])/int(x[1]['amount'])) </code></pre> <p>Output:</p> <pre><code>[('prdata1', {'url': 'https://www.productwebaddress.com/1', 'price': '78.54', 'amoun...
0
2016-08-27T08:31:25Z
[ "python", "json", "sorting" ]
Python sort (json) list by calculated value
39,178,905
<p>I have originally a JSON format with products and the challenge is to sort this list by the best price per unit (prdata3, prdata2, prdata1): </p> <pre><code>{'prdata3': {'variation': 'stand', 'price': '78 54', 'amount': '6', 'url': 'https://www.productwebaddress.com/3'}, 'prdata2': {'variation': 'stand', '...
-2
2016-08-27T08:06:11Z
39,179,111
<p>Welcome to Stack Overflow.</p> <p>I would be nice if you could show us a code snippet, so we can look it over and see where you could be stuck.</p> <p>This might be a one liner, because of the clear specification, it would be something like (pseudo code, won't run): </p> <p><code>sorted(data, key=lambda x: float(...
0
2016-08-27T08:31:39Z
[ "python", "json", "sorting" ]
How do I adjust tooltip in Pygal?
39,178,949
<p>I tried to produce a bar chart that visualizes the most-starred projects on GitHub. I added <code>'label'</code> and <code>'xlink'</code> inside tooltips, however, <code>'label'</code> contents are not very well fit in for some items, also, some links are not shown up in certain projects' tooltip. See below,</p> <p...
2
2016-08-27T08:11:01Z
39,183,446
<p>I don't think there's a clean way to do this; I think you'd need to modify the .svg file directly. There's an <a href="https://github.com/Kozea/pygal/issues/324" rel="nofollow">open issue</a> on the Pygal project asking this question. Someone seems to have found <a href="https://github.com/Kozea/pygal/issues/258" re...
1
2016-08-27T16:42:12Z
[ "python", "pygal" ]
Crawl a wikipedia page in python and store it in a .csv file
39,178,984
<p>This is my python script code</p> <pre><code>from bs4 import BeautifulSoup import requests url='https://en.wikipedia.org/wiki/List_of_Pok%C3%A9mon' source_code=requests.get(url) print(url) plain_text=source_code.text soup=BeautifulSoup(plain_text,"html.parser") print("hello") f = open('pokemons.csv', 'w') for tabl...
0
2016-08-27T08:18:28Z
39,180,484
<p>The <em>tbody</em> is added by the browser so not in the actual source returned by requests so your code could never find anything using it.</p> <p>All you need to do is get every <em>anchor</em> with a <em>title</em> attribute in each row:</p> <pre><code>with open('pokemons.csv', 'w') as f: table = soup.selec...
1
2016-08-27T11:12:33Z
[ "python", "beautifulsoup", "web-crawler" ]
python loop x + 1 times in a list of list until number y
39,179,018
<p>What I want is the list in <code>num</code> loops <code>x + 1</code> everytime until <code>y</code> is generated(and loops is stoped), which is a large number.</p> <pre><code>def loop_num(y): num = [] num.append([1]) num.append([2,3]) num.append([4,5,6]) num.append([7,8,9,10]) ... #stop ap...
-1
2016-08-27T08:21:14Z
39,179,192
<p>I am not sure what is your question. But I am assuming that you have done something similar to this.</p> <pre><code>x=[[1], [2,3], [4,5,6]] b=[str(a)+' items' for a in [j for i in x for j in i]] </code></pre> <p>And what you are looking for is this.</p> <pre><code>c=max([j for i in x for j in i]) </code></pre> <...
0
2016-08-27T08:41:26Z
[ "python", "list", "loops", "random", "iteratee" ]
python loop x + 1 times in a list of list until number y
39,179,018
<p>What I want is the list in <code>num</code> loops <code>x + 1</code> everytime until <code>y</code> is generated(and loops is stoped), which is a large number.</p> <pre><code>def loop_num(y): num = [] num.append([1]) num.append([2,3]) num.append([4,5,6]) num.append([7,8,9,10]) ... #stop ap...
-1
2016-08-27T08:21:14Z
39,179,242
<p>Two <a href="https://docs.python.org/2/library/itertools.html#itertools.count" rel="nofollow"><code>itertools.count</code></a> objects should do what you want:</p> <pre><code>from itertools import count def loop_num(y): counter, x = count(1), count(1) n = 0 while n &lt; y: num = [] for ...
1
2016-08-27T08:49:00Z
[ "python", "list", "loops", "random", "iteratee" ]
python loop x + 1 times in a list of list until number y
39,179,018
<p>What I want is the list in <code>num</code> loops <code>x + 1</code> everytime until <code>y</code> is generated(and loops is stoped), which is a large number.</p> <pre><code>def loop_num(y): num = [] num.append([1]) num.append([2,3]) num.append([4,5,6]) num.append([7,8,9,10]) ... #stop ap...
-1
2016-08-27T08:21:14Z
39,180,159
<pre><code>def loop_num(x): i=1 cnt=0 sum=0 while sum&lt;x: sum+=i cnt=cnt+1 i=i+1 num=[ [] for x in range(cnt)] count=0 sz=1 init=1 while(count&lt;cnt): cur=1 while(cur&lt;=sz): num[count].append(init) init=init+1 ...
1
2016-08-27T10:36:43Z
[ "python", "list", "loops", "random", "iteratee" ]
Changing part of a message's color in tkinter messagebox
39,179,022
<p>I have a TKinter messagebox like the one below. I would like to change <strong>part</strong> of the message to a different color. For example in the messagebox below I would like the language to be <code>Blue</code>. Is this possible?</p> <p><a href="http://i.stack.imgur.com/wekJQ.png" rel="nofollow"><img src="http...
0
2016-08-27T08:21:26Z
39,180,519
<p>It's not possible to change such options of <a href="http://effbot.org/tkinterbook/tkinter-standard-dialogs.htm" rel="nofollow">Tkinter Standard Dialogs</a>. You need to create your own dialog. You'll also need to separate the text parts. I've tried to make something similar in the image that the <a href="http://sta...
2
2016-08-27T11:16:40Z
[ "python", "python-3.x", "tkinter" ]
How to detect HTTP response status code and set a proxy accordingly in scrapy?
39,179,041
<p>Is there a way to set a new proxy ip (e.g.: from a pool) according to the HTTP response status code? For example, start up with an IP form an IP list till it gets a 503 response (or another http error code), then use the next one till it gets blocked,and so on, something like:</p> <pre><code>if http_status_code i...
0
2016-08-27T08:23:59Z
39,179,534
<p>Scrapy has a downloader middleware which is enabled by default to handle proxies. It's called <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware" rel="nofollow">HTTP Proxy Middleware</a> and what it does is allows you to supply meta k...
0
2016-08-27T09:27:18Z
[ "python", "scrapy" ]
How to find permutations in a list then remove them?
39,179,226
<p>I'm trying to find a permutation of another number in this txt file and then add them to a list:</p> <pre><code>167 168 148 143 289 194 683 491 </code></pre> <p>In this file, the permutations are 491 and 194.</p> <p>This is my code:</p> <pre><code>numberList = [] file = open("file.txt", "r") for line in file: ...
1
2016-08-27T08:46:20Z
39,179,365
<p>Ok, let's do a bit of group theory:</p> <p>assume you can decompose your numbers x into digits X[i] (removing the <code>\n</code> is really trivial, and surely someone else will cover this). </p> <p>Then we know that, by how the decimal system works,</p> <p><img src="http://i.stack.imgur.com/9ut2V.png" alt="$$x =...
7
2016-08-27T09:04:07Z
[ "python", "permutation" ]
How to find permutations in a list then remove them?
39,179,226
<p>I'm trying to find a permutation of another number in this txt file and then add them to a list:</p> <pre><code>167 168 148 143 289 194 683 491 </code></pre> <p>In this file, the permutations are 491 and 194.</p> <p>This is my code:</p> <pre><code>numberList = [] file = open("file.txt", "r") for line in file: ...
1
2016-08-27T08:46:20Z
39,179,424
<p>There seem to be two problems: How to read numbers from a text file, and how to detect and filter out the duplicates w.r.t. permutations. For the first, you can use <code>strip</code> to get rid of the <code>\n</code> and convert to <code>int</code> to get actual numbers (although when using <code>int</code>, the fi...
4
2016-08-27T09:10:37Z
[ "python", "permutation" ]
How to find permutations in a list then remove them?
39,179,226
<p>I'm trying to find a permutation of another number in this txt file and then add them to a list:</p> <pre><code>167 168 148 143 289 194 683 491 </code></pre> <p>In this file, the permutations are 491 and 194.</p> <p>This is my code:</p> <pre><code>numberList = [] file = open("file.txt", "r") for line in file: ...
1
2016-08-27T08:46:20Z
39,179,633
<p>So, you can do this in just 3 additional lines of code:</p> <ol> <li>Sort each item in the list so that permutations will match</li> <li>Check each item on the list to see where there are permutations, and create a list of those indices</li> <li>Create the new list do not add the indices that were identified as per...
1
2016-08-27T09:38:28Z
[ "python", "permutation" ]
Counter within django loop
39,179,257
<p>I have the following django / html code:</p> <pre><code>{% for x in fixtures %} &lt;div id="match1" style="display:block"&gt;{{x.home_team.teamname}}&lt;/div&gt; {% endfor %} </code></pre> <p>The above simply displays all teams from a set of fixtures. It works perfectly as it stands. However, I would like ...
0
2016-08-27T08:51:01Z
39,179,296
<p>There's no need for javascript. You can use the <code>forloop.counter</code> variable:</p> <pre><code>{% for x in fixtures %} &lt;div id="match{{ forloop.counter }}" style="display:block"&gt;{{x.home_team.teamname}}&lt;/div&gt; {% endfor %} </code></pre> <p>The various variables available in a for loop are d...
3
2016-08-27T08:56:14Z
[ "javascript", "python", "django" ]
SQLAlchemy update neither works nor raises errors
39,179,260
<p>I want to update the <code>email</code> column of the <code>user</code> table where <code>id == 3</code>. Below code does not update any rows or even raise any errors. Where could the problem be?</p> <pre><code>from sqlalchemy import update @app.route('/testupdate/') def testupdate(): stmt = update(user).where(...
0
2016-08-27T08:51:18Z
39,184,526
<p>The problem is that no SQL was emitted to the database.</p> <pre><code> stmt = update(user).where(user.id==3).values(email='a@b') </code></pre> <p>Does not actually execute the statement, it just creates it. To actually execute it you have to pass it to</p> <pre><code> db.session.execute(stmt) </code></pre>...
0
2016-08-27T18:39:40Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
How to install firefoxdriver webdriver for python3 selenium on ubuntu 16.04?
39,179,320
<p>I installed python3-selenium apt package on Ubuntu 16.04. While installing, got a message:</p> <pre><code>Suggested packages: chromedriver firefoxdriver The following NEW packages will be installed: python3-selenium </code></pre> <p>When I try to run the following python code,</p> <pre><code>#! /usr/bin/python3.5...
1
2016-08-27T08:58:25Z
39,195,764
<p>You can either upgrade to 16.10 (it's in yakkety) or you can download the deb from <a href="http://pk.archive.ubuntu.com/ubuntu/ubuntu/pool/multiverse/s/selenium-firefoxdriver/" rel="nofollow">here</a> (it works - I tried it). Alternatively you can follow <a href="https://christopher.su/2015/selenium-chromedriver-ub...
0
2016-08-28T21:04:19Z
[ "python", "python-3.x", "selenium", "selenium-webdriver", "python-3.5" ]
How to install firefoxdriver webdriver for python3 selenium on ubuntu 16.04?
39,179,320
<p>I installed python3-selenium apt package on Ubuntu 16.04. While installing, got a message:</p> <pre><code>Suggested packages: chromedriver firefoxdriver The following NEW packages will be installed: python3-selenium </code></pre> <p>When I try to run the following python code,</p> <pre><code>#! /usr/bin/python3.5...
1
2016-08-27T08:58:25Z
39,548,509
<p>I'm not certain if this will fix the issue you're having, but you can give it a try. But first, to answer the question as to where you can download firefoxdriver, my answer would be <strong>maybe firefoxdriver is not available, because the file is now called geckodriver, but it's really called Marionette Driver.</s...
0
2016-09-17T15:26:05Z
[ "python", "python-3.x", "selenium", "selenium-webdriver", "python-3.5" ]
Is it possible in Python to decorate a function so that its begin and end are logged?
39,179,519
<p>For logging, I would like each function to log its own name at the start and end of the function.</p> <pre><code>def my_function(): print("Enter my_function") # ... print("Leave my_function") </code></pre> <p>If I change the name of the function, I have to update these print messages as well. I am look...
1
2016-08-27T09:25:29Z
39,179,602
<p>You are right, using a decorator is a perfect way to implement such behavior.</p> <p>What you need to know is <a class='doc-link' href="http://stackoverflow.com/documentation/python/229/decorators#t=201608270936002345573">how a decorator works</a>: it simply takes a function as an argument, and returns another func...
6
2016-08-27T09:35:00Z
[ "python", "python-decorators" ]
Is it possible in Python to decorate a function so that its begin and end are logged?
39,179,519
<p>For logging, I would like each function to log its own name at the start and end of the function.</p> <pre><code>def my_function(): print("Enter my_function") # ... print("Leave my_function") </code></pre> <p>If I change the name of the function, I have to update these print messages as well. I am look...
1
2016-08-27T09:25:29Z
39,179,611
<p>Sure, it's really simple with star args and star kwargs. <code>functools.wraps</code> is used to rewrite any metadata (<code>__name__</code>, <code>__doc__</code> etc.) from input function to wrapper. If function object string representation is too verbose to you, you may use <code>print("Enter", f.__name__)</code> ...
1
2016-08-27T09:35:54Z
[ "python", "python-decorators" ]
Handling Arabic text in Python
39,179,538
<p>I have the following Python 2.7 code:</p> <pre><code>mydoclist = ['جوليا تحبني اكثر من ليندا','جين تحبني اكثر من جوليا','احمد يحب كرة السلة اكثر من كرة الطاولة'] from collections import Counter for doc in mydoclist: tf = Counter() fo...
0
2016-08-27T09:27:54Z
39,179,763
<p>Python prints lists so that all items in them are passed through <code>repr</code> which in turn produces this stuff with "\u...". Also have a look at the tutorial section about <a href="https://docs.python.org/2.7/tutorial/introduction.html#unicode-strings" rel="nofollow">unicode-strings</a> or better the <a href="...
2
2016-08-27T09:54:52Z
[ "python", "arabic" ]
How to detect the number of threads i can & i should run?
39,179,607
<p>i have a 6th generation Intel i5 Processor (4 cores, 3 ghZ) and 8 gigabytes of RAM. Let's assume i need to create a text file which includes every number from 0 to 999999999. </p> <p>How can i make it faster? How many threads i should use? 4 or more than 4? How many threads i should run and why?</p>
1
2016-08-27T09:35:34Z
39,180,217
<p>Due to the fact you're writing into the same file, you will need a lock in order for the text not to get garbled. If you're using a lock however, multi-threading or multi-processing won't make a difference as it will be writing sequentially.</p> <p>Not using a lock will get a result much like this:</p> <pre><code>...
1
2016-08-27T10:43:10Z
[ "python", "multithreading" ]
How to detect the number of threads i can & i should run?
39,179,607
<p>i have a 6th generation Intel i5 Processor (4 cores, 3 ghZ) and 8 gigabytes of RAM. Let's assume i need to create a text file which includes every number from 0 to 999999999. </p> <p>How can i make it faster? How many threads i should use? 4 or more than 4? How many threads i should run and why?</p>
1
2016-08-27T09:35:34Z
39,180,370
<p>because of GIL you should use multiprocessing module. number of process should be:</p> <pre><code>multiprocessing.cpu_count() - 1 # -1 for other system process. </code></pre>
1
2016-08-27T11:00:36Z
[ "python", "multithreading" ]
How to detect the number of threads i can & i should run?
39,179,607
<p>i have a 6th generation Intel i5 Processor (4 cores, 3 ghZ) and 8 gigabytes of RAM. Let's assume i need to create a text file which includes every number from 0 to 999999999. </p> <p>How can i make it faster? How many threads i should use? 4 or more than 4? How many threads i should run and why?</p>
1
2016-08-27T09:35:34Z
39,183,116
<p>Thanks for the answers &amp; comments. I couldn't try the multiprocessing module because i am on a vacation and my computer has 2 cores, it would be the same (1 for system, 1 for python.). But i will add the results with the multiprocessing as soon as i get home. So, here is my test results with a Intel Pentium Dual...
0
2016-08-27T16:06:52Z
[ "python", "multithreading" ]
python to extract list match from email thread
39,179,672
<p>I m new to python. I need to retrieve the list of match </p> <p>for Example my text is below which is an email. I need to extract all To, From, Sent, Subject and body from a mail thread.</p> <p>Result need to From List</p> <p>From(1) = Crandall, Sean From(2) = Nettelton, Marcus </p> <p>To(1)= Crandall, Sean; B...
0
2016-08-27T09:43:00Z
39,180,211
<p>You can use <code>re.findall()</code> for this, see: <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow">https://docs.python.org/2/library/re.html#re.findall</a>. E.g.</p> <pre><code>re.findall("From: (.*) ", input_string); </code></pre> <p>would return a list of the From-names (<code>...
1
2016-08-27T10:42:38Z
[ "python", "regex", "match" ]
python to extract list match from email thread
39,179,672
<p>I m new to python. I need to retrieve the list of match </p> <p>for Example my text is below which is an email. I need to extract all To, From, Sent, Subject and body from a mail thread.</p> <p>Result need to From List</p> <p>From(1) = Crandall, Sean From(2) = Nettelton, Marcus </p> <p>To(1)= Crandall, Sean; B...
0
2016-08-27T09:43:00Z
39,180,246
<p>If you don't know how to use regex and as your problem is not that tough, you may consider to use the <code>split()</code> and <code>replace()</code> functions.</p> <p>Here are some lines of code that might be a good start:</p> <pre><code>mails = """-----Original Message----- From: Crandall, Sean Sent: Wedne...
1
2016-08-27T10:47:49Z
[ "python", "regex", "match" ]
Is there a way to get multiple ngram orders using NTLK instead of obtaining a iterating over a generator?
39,179,703
<p>I need ngrams. I know <code>nltk.utils.ngrams</code> can be used to obtain ngrams, but in practice, the ngrams function returns a generator object. I can always iterate over it and store the ngrams in a list. But is there another, more direct way to obtaining these ngrams in a list without having to iterate over the...
0
2016-08-27T09:47:09Z
39,179,853
<p>@georg's comment pretty much nails it.</p> <pre><code>In [12]: from nltk.util import ngrams In [13]: g = ngrams([1,2,3,4,5], 3) In [14]: list(g) Out[14]: [(1, 2, 3), (2, 3, 4), (3, 4, 5)] In [15]: g = ngrams([1,2,3,4,5], 3) In [16]: map(lambda x: x, g) Out[16]: [(1, 2, 3), (2, 3, 4), (3, 4, 5)] </code></pre>
2
2016-08-27T10:04:55Z
[ "python", "nlp", "generator", "nltk", "n-gram" ]
Is there a way to get multiple ngram orders using NTLK instead of obtaining a iterating over a generator?
39,179,703
<p>I need ngrams. I know <code>nltk.utils.ngrams</code> can be used to obtain ngrams, but in practice, the ngrams function returns a generator object. I can always iterate over it and store the ngrams in a list. But is there another, more direct way to obtaining these ngrams in a list without having to iterate over the...
0
2016-08-27T09:47:09Z
39,180,306
<p>or alternatively without <code>nltk</code>:</p> <pre><code>from itertools import chain def ngrams(L, n = 2): orders = [n] if type(n) is int else sorted(list(n)) return list(chain(*[zip(*[L[i:] for i in range(n)]) for n in orders])) &gt;&gt;&gt; ngrams([1,2,3,4,5], n = 3) [(1, 2, 3), (2, 3, 4), (3, 4, 5)] ...
0
2016-08-27T10:54:15Z
[ "python", "nlp", "generator", "nltk", "n-gram" ]
Is there a way to get multiple ngram orders using NTLK instead of obtaining a iterating over a generator?
39,179,703
<p>I need ngrams. I know <code>nltk.utils.ngrams</code> can be used to obtain ngrams, but in practice, the ngrams function returns a generator object. I can always iterate over it and store the ngrams in a list. But is there another, more direct way to obtaining these ngrams in a list without having to iterate over the...
0
2016-08-27T09:47:09Z
39,182,566
<p>There's actually a built-in function to get multiple orders of ngrams call <code>everygrams</code> ,see <a href="https://github.com/nltk/nltk/blob/develop/nltk/util.py#L504" rel="nofollow">https://github.com/nltk/nltk/blob/develop/nltk/util.py#L504</a></p> <pre><code>&gt;&gt;&gt; from nltk import everygrams &gt;&gt...
3
2016-08-27T15:06:45Z
[ "python", "nlp", "generator", "nltk", "n-gram" ]
Should I include this boilerplate code in every Python script I write?
39,179,738
<p>My boss asked me to put the following lines (from <a href="https://stackoverflow.com/questions/4374455/how-to-set-sys-stdout-encoding-in-python-3">this answer</a>) into a Python 3 script I wrote:</p> <pre><code>import sys import codecs sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) </code></pre> <p>H...
3
2016-08-27T09:51:03Z
39,179,986
<p>The answer provided <a href="http://stackoverflow.com/questions/11741574/how-to-print-utf-8-encoded-text-to-the-console-in-python-3">here</a> has a good excerpt from the Python mailing list regarding your question. I guess it is not necessary to do this.</p> <blockquote> <p>The only supported default encodings in...
4
2016-08-27T10:17:25Z
[ "python", "python-3.x", "unicode" ]
creating nested dicts in python 3
39,179,799
<p>I'm trying to create the following nested dict structure, <code>{0: {0: 1}, 1: {0: 1, 1: 1}}</code> with the following code:</p> <pre><code>feats = {} for i in range(2): feat = feats.get(i, {}) for j in range(i+1): feat[j] = 1 </code></pre> <p>but all I'm getting <code>feats = {}</code>. Why is tha...
1
2016-08-27T09:59:42Z
39,179,838
<p>The problem here is, you are not storing <code>feat</code> value in <code>feats</code>, so it is lost after every iteration. At the end of the iterations, <code>feats</code> is empty.</p> <p>You can fix your code like below: </p> <pre><code>feats = {} for i in range(2): feat = feats.get(i, {}) for j in ran...
3
2016-08-27T10:03:44Z
[ "python", "python-3.x", "dictionary" ]
creating nested dicts in python 3
39,179,799
<p>I'm trying to create the following nested dict structure, <code>{0: {0: 1}, 1: {0: 1, 1: 1}}</code> with the following code:</p> <pre><code>feats = {} for i in range(2): feat = feats.get(i, {}) for j in range(i+1): feat[j] = 1 </code></pre> <p>but all I'm getting <code>feats = {}</code>. Why is tha...
1
2016-08-27T09:59:42Z
39,180,214
<p>First of all I ran your program and I printed feats, it printed{0: 1, 1: 1} and not {}</p> <p>Second thing, what I can understand from your requirement is that, in a generic way, while looping through a range of numbers, you want to have that number as key and value as dictionary containing key value pairs, where n...
0
2016-08-27T10:42:45Z
[ "python", "python-3.x", "dictionary" ]
oddo can't adapt type 'hr.employee'
39,179,843
<p>I want to get value of field in my class that one2many to hr_employee:</p> <pre><code>class cashadvance(osv.osv): def get_employeeid(self, cr, uid, context=None): idemployee = "" employee_id = "" ids = self.search(cr, uid, [], context=context) # you probably want to search for all the re...
0
2016-08-27T10:04:04Z
39,180,347
<pre><code> for adv in self.browse(cr, uid, ids, context=context): employee_id = adv.id_employee </code></pre> <p>On this part of the code your are browsing the self model. Browse method returns a recordset, that means it returns a instance of the class that represents the model your browse runs to. If you w...
3
2016-08-27T10:58:30Z
[ "python", "openerp" ]
XLRD vs Win32 COM performance comparison
39,179,880
<p>I have this huge <code>Excel (xls)</code> file that I have to read data from. I tried using the <code>xlrd</code> library, but is pretty slow. I then found out that by converting the <code>Excel</code> file to <code>CSV</code> file manually and reading the <code>CSV</code> file is orders of magnitude faster.</p> <p...
-1
2016-08-27T10:07:25Z
39,360,812
<p>if you need to read the file frequently, I think it is better to save it as CSV. Otherwise, just read it on the fly. </p> <p>for performance issue, I think win32com outperforms. however, considering cross-platform compatibility, I think xlrd is better. win32com is more powerful. With it, one can handle Excel in all...
0
2016-09-07T03:32:21Z
[ "python", "excel", "csv", "win32com" ]
Can't *update* pycharm educational
39,180,027
<p>I am a Ubuntu 16 user and I installed pycharm educational 2 at my computer. A few days ago while starting the app I received the notification that there's am update : version 3 So I downloaded the file(.tgz) from from the developer website and tried to install the update. I can only extract the file instead of actua...
0
2016-08-27T10:21:55Z
39,185,756
<p>Unpack the archive, go to <code>bin</code> folder and run <code>.sh</code> script.</p>
0
2016-08-27T21:06:32Z
[ "python", "ide", "install", "pycharm" ]
Is there is any way to identify background of an image (indoor or outdoor)
39,180,041
<p>I am doing a research on object identification. I did it using tensorflow and it identified objects of an image well. It does not, however, have any idea how to identify the background of an image (indoor or outdoor).</p>
-1
2016-08-27T10:23:17Z
39,243,099
<p>It seems like for each image, you're interested in two classification results: what object appears in the image, and whether it's outdoors or indoors.</p> <p>A straightforward way of doing that would be to train and apply two different classifiers, one for object recognition and one for background classification. <...
0
2016-08-31T07:16:56Z
[ "python", "image-processing", "machine-learning", "neural-network" ]