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 |
|---|---|---|---|---|---|---|---|---|---|
Settin general defaults for named arguments in python | 39,139,935 | <p>I have the following problem:
I have to set some values for special entities (points, lines, faces, volumes, spheres,...), via an API into a database.</p>
<p>Some values are unique for every entity, others are always the same.
So my idea was to do something like (SetValues is the API command i have to use putting s... | 6 | 2016-08-25T08:10:48Z | 39,140,051 | <p>You can create a dictionary for storing default values.</p>
<pre><code>defaults = {"move": "no", "perimeter": 0.0, "gap":"yes"}
def CreatePointEntity(ID,Name,Solver,P1,Move=defaults["move"],Perimeter=defaults["perimeter"],Gap=defaults["gap"]):
SetValues(ID, {'Name':Name})
SetValues(ID, {'P1':P1})
SetV... | 2 | 2016-08-25T08:17:34Z | [
"python"
] |
Settin general defaults for named arguments in python | 39,139,935 | <p>I have the following problem:
I have to set some values for special entities (points, lines, faces, volumes, spheres,...), via an API into a database.</p>
<p>Some values are unique for every entity, others are always the same.
So my idea was to do something like (SetValues is the API command i have to use putting s... | 6 | 2016-08-25T08:10:48Z | 39,140,062 | <p>I usually keep a <code>constants.py</code> in all such projects.</p>
<p>Here:<br></p>
<p><strong>constant.py</strong></p>
<pre><code>MOVE = 'no'
</code></pre>
<p><strong>yourFile.py</strong></p>
<pre><code>from constants import MOVE # add as many constants as needed
def CreateLineEntity(ID,Name,Solver,P1,P2,Mo... | 3 | 2016-08-25T08:18:25Z | [
"python"
] |
Settin general defaults for named arguments in python | 39,139,935 | <p>I have the following problem:
I have to set some values for special entities (points, lines, faces, volumes, spheres,...), via an API into a database.</p>
<p>Some values are unique for every entity, others are always the same.
So my idea was to do something like (SetValues is the API command i have to use putting s... | 6 | 2016-08-25T08:10:48Z | 39,140,114 | <p>How about storing the default values in a separate file as Constants.</p>
<p>e.g:</p>
<p>constants.py:</p>
<pre><code>MOVE = "on"
PERIMETER = "xyz"
...
</code></pre>
<p>Your script:</p>
<pre><code>from constants import *
def CreateLineEntity(ID,Name,Solver,P1,P2,Move=MOVE,Perimeter=PERIMETER,Gap=GAP):
Set... | 2 | 2016-08-25T08:20:26Z | [
"python"
] |
How to distribute python application with all dependencies | 39,140,078 | <p>I want to distribute a python application with all its dependencies. Target machine doesn't have an outside connection so I can't <code>pip install</code> anything
and all packages must be included.</p>
<p>I'm using python 2.7 for my application and the target machine has a different python version. I would like t... | 3 | 2016-08-25T08:18:55Z | 39,140,123 | <p>If you want to distribute on Windows you can use py2exe: <a href="http://www.py2exe.org/" rel="nofollow">http://www.py2exe.org/</a>
or cross-platform <a href="http://www.pyinstaller.org/" rel="nofollow">http://www.pyinstaller.org/</a> </p>
<p>That way you convert your whole application to a single executable file, ... | 0 | 2016-08-25T08:20:47Z | [
"python",
"python-2.7",
"install"
] |
Python Lazy Loading | 39,140,348 | <p>The following code is going to lazily print the contents of the text file line by line, with each print stopping at '/n' .</p>
<pre><code> with open('eggs.txt', 'rb') as file:
for line in file:
print line
</code></pre>
<p>Is there any configuration to lazily print the contents of a text file,... | 3 | 2016-08-25T08:32:25Z | 39,140,601 | <p>I don't think there is a built-in way to achieve this. You will have to use <code>file.read(block_size)</code> to read the file block by block, split each block at commas, and rejoin strings that go across block boundaries manually.</p>
<p>Note that you still might run out of memory if you don't encounter a comma ... | 2 | 2016-08-25T08:44:39Z | [
"python",
"lazy-loading"
] |
Python Lazy Loading | 39,140,348 | <p>The following code is going to lazily print the contents of the text file line by line, with each print stopping at '/n' .</p>
<pre><code> with open('eggs.txt', 'rb') as file:
for line in file:
print line
</code></pre>
<p>Is there any configuration to lazily print the contents of a text file,... | 3 | 2016-08-25T08:32:25Z | 39,140,705 | <p>The following answer can be considered lazy since it is reading the file a character at a time:</p>
<pre><code>def commaBreak(filename):
word = ""
with open(filename) as f:
while True:
char = f.read(1)
if not char:
print "End of file"
yield wor... | 1 | 2016-08-25T08:51:00Z | [
"python",
"lazy-loading"
] |
Python Lazy Loading | 39,140,348 | <p>The following code is going to lazily print the contents of the text file line by line, with each print stopping at '/n' .</p>
<pre><code> with open('eggs.txt', 'rb') as file:
for line in file:
print line
</code></pre>
<p>Is there any configuration to lazily print the contents of a text file,... | 3 | 2016-08-25T08:32:25Z | 39,140,753 | <pre><code>with open('eggs.txt', 'rb') as file:
for line in file:
str_line = str(line)
words = str_line.split(', ')
for word in words:
print(word)
</code></pre>
<p>I'm not completely sure if I know what you are asking, is something like this what you mean?</p>
| -1 | 2016-08-25T08:53:09Z | [
"python",
"lazy-loading"
] |
Python Lazy Loading | 39,140,348 | <p>The following code is going to lazily print the contents of the text file line by line, with each print stopping at '/n' .</p>
<pre><code> with open('eggs.txt', 'rb') as file:
for line in file:
print line
</code></pre>
<p>Is there any configuration to lazily print the contents of a text file,... | 3 | 2016-08-25T08:32:25Z | 39,140,852 | <p>Using buffered reading from the file (Python 3):</p>
<pre><code>buffer_size = 2**12
delimiter = ','
with open(filename, 'r') as f:
# remember the characters after the last delimiter in the previously processed chunk
remaining = ""
while True:
# read the next chunk of characters from the file
... | 2 | 2016-08-25T08:58:23Z | [
"python",
"lazy-loading"
] |
Python Lazy Loading | 39,140,348 | <p>The following code is going to lazily print the contents of the text file line by line, with each print stopping at '/n' .</p>
<pre><code> with open('eggs.txt', 'rb') as file:
for line in file:
print line
</code></pre>
<p>Is there any configuration to lazily print the contents of a text file,... | 3 | 2016-08-25T08:32:25Z | 39,141,071 | <p>It yields each character from file at once, what means that there is no memory overloading.</p>
<pre><code>def lazy_read():
try:
with open('eggs.txt', 'rb') as file:
item = file.read(1)
while item:
if ',' == item:
raise StopIteration
... | 0 | 2016-08-25T09:08:07Z | [
"python",
"lazy-loading"
] |
How to get the rank of a column in numpy 2d array? | 39,140,490 | <p>suppose I have an array:</p>
<pre><code>a = np.array([[1,2,3,4],
[4,2,5,6],
[6,5,0,3]])
</code></pre>
<p>I want to get the rank of column 0 in each row(i.e. <code>np.array([0, 1, 3])</code>), Is there any short way to do this?</p>
<p>In 1d array I can use <code>np.sum(a < a[0])</cod... | 1 | 2016-08-25T08:39:36Z | 39,140,537 | <p><strong>Approach #1</strong></p>
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow"><code>np.argsort</code></a> along the rows and look for the index <code>0</code> corresponding to the first column to give us a mask of the same shape as the input array. Finally, ... | 1 | 2016-08-25T08:41:43Z | [
"python",
"arrays",
"numpy",
"ranking",
"numpy-broadcasting"
] |
Python why time increases 13 times when using list append instead of string concatenation? | 39,140,524 | <p>I have a script. Please find complete code at code review <a href="http://codereview.stackexchange.com/questions/139501/python-script-to-convert-asn-to-hpp">here</a></p>
<p>I have removed string concatenation & replaced it with list append as below </p>
<p>sample old code </p>
<pre><code>def comment_line(self... | 0 | 2016-08-25T08:40:59Z | 39,140,734 | <p>The second example contains a string concatenation (<code>"//"+self.line+"\n"</code>) <em>and</em> appending to a list.</p>
<p>That doesn't explain why it's suddenly so much slower; my guess is that the list contains many elements. Appending to long lists can be expensive since Python has to copy the list eventuall... | 1 | 2016-08-25T08:52:24Z | [
"python",
"python-3.x"
] |
Transparent interaction with console (sh,bash,cmd,powershell) | 39,140,632 | <p>Please help me to write simple console application in python. It should redirect all input to system shell (bash or windows cmd or powershell) and give all their output to the screen.
Simply I can say run terminal from python application.</p>
<p>The next code works with some strange behavior: first 3 times after a... | 0 | 2016-08-25T08:47:03Z | 39,145,596 | <p>I think you need</p>
<p><code>proc = subprocess.Popen(['bash'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)</code></p>
<p>From the <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="nofollow">docs</a>:</p>
<blockquote>
<p>PIPE indicates that a new pipe to the child should be c... | 0 | 2016-08-25T12:40:12Z | [
"python",
"python-3.x",
"terminal",
"subprocess"
] |
better way of doing dict comprehension | 39,140,658 | <pre><code>UG=[
{"group_member":"myGroup1","user_name":"tom"},
{"group_member":"myGroup2","user_name":"wilson"},
{"group_member":"myGroup1","user_name":"kevin"},
{"group_member":"myGroup2","user_name":"donna"},
{"group_member":"myGroup3","user_name":"john"},
{"group_member":"myGroup1","user_name... | 0 | 2016-08-25T08:48:20Z | 39,141,029 | <p>Yes, it can be done using a list comprehension. But first let's create a functional dict update function, since <code>dict</code>'s update method doesn't return a new dict (but, rather, updates the current one):</p>
<pre><code>def updt(d1, d2):
d3 = d1.copy()
d3.update(d2)
return d3
</code></pre>
<p>No... | 2 | 2016-08-25T09:06:16Z | [
"python",
"dictionary",
"dictionary-comprehension"
] |
better way of doing dict comprehension | 39,140,658 | <pre><code>UG=[
{"group_member":"myGroup1","user_name":"tom"},
{"group_member":"myGroup2","user_name":"wilson"},
{"group_member":"myGroup1","user_name":"kevin"},
{"group_member":"myGroup2","user_name":"donna"},
{"group_member":"myGroup3","user_name":"john"},
{"group_member":"myGroup1","user_name... | 0 | 2016-08-25T08:48:20Z | 39,141,345 | <p>If you have thousands of records here is generator</p>
<pre><code>from itertools import product
def produce():
for dg, pg, ug in product(DG, PG, UG):
if pg['device_name'] == dg['device_name'] and ug['group_member'] == pg['group_member']:
item = dg.copy()
item.update(pg)
... | 1 | 2016-08-25T09:21:41Z | [
"python",
"dictionary",
"dictionary-comprehension"
] |
AppEngine achieving strong consistency | 39,140,673 | <p>I am trying to achieve strong consistency. Let's call my model <code>PVPPlayer</code>:</p>
<pre><code>class PVPPlayer(ndb.Model):
points = ndb.IntegerProperty()
</code></pre>
<p>Every key for the model is created like this:</p>
<pre><code>pvp_player = PVPPlayer(key=ndb.Key(Profile, "test_id", PVPPlayer, "test... | 0 | 2016-08-25T08:48:56Z | 39,149,160 | <p>Is there a case you exceed the write limit per entity group, that is one update per second? I think this could break the strong consistency of the entity group as mentioned in the documentation. </p>
| 1 | 2016-08-25T15:25:28Z | [
"python",
"google-app-engine",
"eventual-consistency"
] |
AppEngine achieving strong consistency | 39,140,673 | <p>I am trying to achieve strong consistency. Let's call my model <code>PVPPlayer</code>:</p>
<pre><code>class PVPPlayer(ndb.Model):
points = ndb.IntegerProperty()
</code></pre>
<p>Every key for the model is created like this:</p>
<pre><code>pvp_player = PVPPlayer(key=ndb.Key(Profile, "test_id", PVPPlayer, "test... | 0 | 2016-08-25T08:48:56Z | 39,164,175 | <p>First check your logs, one of the updates must be failing with error, because your logic is basically correct.</p>
<p>Also double-check all your updates are wrapped in transactions to avoid races. <a href="http://stackoverflow.com/questions/38955748/cloud-datastore-ways-to-avoid-race-conditions">Cloud Datastore: wa... | 1 | 2016-08-26T10:30:41Z | [
"python",
"google-app-engine",
"eventual-consistency"
] |
Flask can't find the config module in parent directory | 39,140,679 | <p>I'm basing myself on the structure of a web app I found up on github, <a href="https://github.com/nickjj/build-a-saas-app-with-flask" rel="nofollow">here</a>.</p>
<p>My project's structure looks like this:</p>
<pre><code>~/Learning/flask-celery $ tree
.
âââ config
â  âââ __init__.py
â  ââ... | 0 | 2016-08-25T08:49:06Z | 39,141,145 | <p>Without adding the config directory to your path your Python package will not be able to see it.</p>
<p>Your code can only access what is in <code>web</code> by the looks of it.</p>
<p>You can add the config directory to the package like so:</p>
<pre><code>import os
import sys
import inspect
currentdir = os.path... | 2 | 2016-08-25T09:11:58Z | [
"python",
"web-applications",
"flask"
] |
Moving x-axis in matplotlib during real time plot (python) | 39,140,698 | <p>I want to manipulate the x-axis during a real time plot so that at most a number of 10 samples are seen at a time.
It seems like plt.axis() updates just once after the plot has been initialized. Any suggestions? Thanks in advance! </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
# Initialize
x_a... | 3 | 2016-08-25T08:50:20Z | 39,140,810 | <p>You have to update <code>x_axist_start</code> and <code>x_axis_end</code> in the <code>if</code> statement!</p>
<pre><code>if i%10 == 0 and i>1:
print("Axis should update now!")
x_axis_start += 10
x_axis_end += 10
plt.axis([x_axis_start, x_axis_end, 0, 1])
</code></pre>
<p>This does the trick! :... | 1 | 2016-08-25T08:56:01Z | [
"python",
"matplotlib",
"plot",
"real-time",
"axis"
] |
How to gather information from user input and apply it elsewhere | 39,140,838 | <p>Hi I am new to programming and I am trying to write a code that will gather information from the input and determine if it is a valid alphabet.</p>
<p>This is my code so far</p>
<pre><code>words = []
word = input('Character: ')
while word:
if word not in words:
words.append(word)
word = input('Character: ')... | 0 | 2016-08-25T08:57:35Z | 39,140,936 | <p>Use <code>str.isalpha()</code>
It is gives only true if all characters in the string are letters.</p>
<p>Example:</p>
<pre><code>>>> 'test'.isalpha()
True
>>> 'test44'.isalpha()
False
>>> 'test test'.isalpha()
False
</code></pre>
<p>In your code:</p>
<pre><code>words = []
word = input(... | 1 | 2016-08-25T09:01:51Z | [
"python"
] |
How to gather information from user input and apply it elsewhere | 39,140,838 | <p>Hi I am new to programming and I am trying to write a code that will gather information from the input and determine if it is a valid alphabet.</p>
<p>This is my code so far</p>
<pre><code>words = []
word = input('Character: ')
while word:
if word not in words:
words.append(word)
word = input('Character: ')... | 0 | 2016-08-25T08:57:35Z | 39,140,990 | <p>You can try this out :-</p>
<pre><code>words = []
while 1:
word = input('Character: ')
if word != '':
try:
if word.isalpha():
pass
if word not in words:
words.append(word)
except Exception:
print word, " is not in the alphab... | 1 | 2016-08-25T09:04:23Z | [
"python"
] |
How to gather information from user input and apply it elsewhere | 39,140,838 | <p>Hi I am new to programming and I am trying to write a code that will gather information from the input and determine if it is a valid alphabet.</p>
<p>This is my code so far</p>
<pre><code>words = []
word = input('Character: ')
while word:
if word not in words:
words.append(word)
word = input('Character: ')... | 0 | 2016-08-25T08:57:35Z | 39,154,251 | <p>You can use a <code>while</code> loop to collect input, then break out of the loop if either the input is empty (the user hit enter without inputting a character) or if the input is not in the alphabet.</p>
<pre><code>letters = []
while True:
letter = input('Character:')
if letter == '':
if letters:... | 1 | 2016-08-25T20:30:18Z | [
"python"
] |
SELECT columns from a variable in Python PYODBC | 39,140,963 | <p>my first question up here, please be kind.
I am new to both python and SQL so I am finding my way.
I am writing a function in python which should select columns from a table in the database with column names coming from a variable (list). Below is what I want the code to look like, obviously it does not work. Is th... | 0 | 2016-08-25T09:03:13Z | 39,142,118 | <p>You can use <code>format()</code> and <code>join()</code> to replace <code>column_list1</code> in your query string with the columns you want.</p>
<pre><code>c.execute('SELECT {} FROM myBD'.format(", ".join(column_list1)))
</code></pre>
<p><code>", ".join(column_list1)</code> creates a comma-separated string from ... | 1 | 2016-08-25T09:57:39Z | [
"python",
"sql",
"select",
"odbc"
] |
find text that match certain string using regex | 39,141,012 | <p>I would like to find whether the string contains a certain character(s). if it does then output into a file, if it doesn't then output into another file.
My input data looks like this:</p>
<pre><code>exchange security volume
TO AAA 193099
TO AAB 81000
TO AAH ... | 2 | 2016-08-25T09:05:12Z | 39,141,221 | <p>You may use <code>filter</code> with <code>lambda</code> function if only upper values are required.</p>
<pre><code>>>> x = 'PrinOnlyUpperCaseLetter'
>>> filter(lambda x: x.isupper(), x)
'POUCL'
</code></pre>
<p>If you want both but in different list:</p>
<pre><code>>>> x = 'PrinOnlyUpp... | 1 | 2016-08-25T09:15:46Z | [
"python",
"regex"
] |
find text that match certain string using regex | 39,141,012 | <p>I would like to find whether the string contains a certain character(s). if it does then output into a file, if it doesn't then output into another file.
My input data looks like this:</p>
<pre><code>exchange security volume
TO AAA 193099
TO AAB 81000
TO AAH ... | 2 | 2016-08-25T09:05:12Z | 39,141,283 | <p>try this:</p>
<pre><code>for i in row['security']:
if re.search(r"[a-z]", i):
#add to file 1
</code></pre>
<p>else:
#add to file 2</p>
| 0 | 2016-08-25T09:18:37Z | [
"python",
"regex"
] |
List most common members in Pandas group? | 39,141,080 | <p>I have a dataframe with columns like this:</p>
<pre><code> id lead_sponsor lead_sponsor_class
02837692 Janssen Research & Development, LLC Industry
02837679 Aarhus University Hospital Other
02837666 Universidad Autonoma de Ciudad Juar... | 2 | 2016-08-25T09:08:33Z | 39,141,139 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nlargest.html" rel="nofollow"><code>Series.nlargest</code></a>:</p>
<pre><code>print (df.groupby(['lead_sponsor', 'lead_sponsor_class']).size().nlargest(10))
</code></pre>
<p>In <a href="http://pandas.pydata.org/pandas... | 2 | 2016-08-25T09:11:48Z | [
"python",
"sorting",
"pandas",
"dataframe",
"series"
] |
Why the test case return True for this python 2.7 coding? | 39,141,173 | <pre><code>def antisymmetric(A):
#Write your code here
for i in range(3):
for j in range(3):
if A[i][j] == -A[j][i]:
return True
else:
return False
# Test Cases:
print antisymmetric([[0, 1, 2],
[-1, 0, -2],
... | -3 | 2016-08-25T09:13:08Z | 39,141,216 | <p>You return True at i=0 j=0 the loop are not executed until the end</p>
| 0 | 2016-08-25T09:15:31Z | [
"python",
"python-2.7"
] |
Why the test case return True for this python 2.7 coding? | 39,141,173 | <pre><code>def antisymmetric(A):
#Write your code here
for i in range(3):
for j in range(3):
if A[i][j] == -A[j][i]:
return True
else:
return False
# Test Cases:
print antisymmetric([[0, 1, 2],
[-1, 0, -2],
... | -3 | 2016-08-25T09:13:08Z | 39,141,244 | <p>I guess it is because you return from the function after the first test.
You would probably want to return only after you can rule out the possibility of the matrix being antisymmetric. Ie. onley return false within the loop, and return true after the loops have run through.</p>
| 1 | 2016-08-25T09:16:55Z | [
"python",
"python-2.7"
] |
Why the test case return True for this python 2.7 coding? | 39,141,173 | <pre><code>def antisymmetric(A):
#Write your code here
for i in range(3):
for j in range(3):
if A[i][j] == -A[j][i]:
return True
else:
return False
# Test Cases:
print antisymmetric([[0, 1, 2],
[-1, 0, -2],
... | -3 | 2016-08-25T09:13:08Z | 39,141,267 | <p>It is returning True at i = 0 and j =0 </p>
<p>Modified solution:</p>
<pre><code>def antisymmetric(A):
for i in range(3):
for j in range(3):
if A[i][j] != -A[j][i]:
return False
return True
</code></pre>
| 3 | 2016-08-25T09:18:12Z | [
"python",
"python-2.7"
] |
Why the test case return True for this python 2.7 coding? | 39,141,173 | <pre><code>def antisymmetric(A):
#Write your code here
for i in range(3):
for j in range(3):
if A[i][j] == -A[j][i]:
return True
else:
return False
# Test Cases:
print antisymmetric([[0, 1, 2],
[-1, 0, -2],
... | -3 | 2016-08-25T09:13:08Z | 39,141,879 | <p>Your test returns immediately after the first check. To test if the matrix is antisymmetric (skew-symmetric) you need to keep checking until you find a pair (i, j) with <code>A[i][j] != -A[j][i]</code>.</p>
<p>It's almost always better in Python to directly loop over the items in containers rather than using indice... | 1 | 2016-08-25T09:46:14Z | [
"python",
"python-2.7"
] |
Python multiprocessing - Return a dict | 39,141,236 | <p>I'd like to parallelize a function that returns a flatten list of values (called "keys") in a dict but I don't understand how to obtain in the final result. I have tried:</p>
<pre><code>def toParallel(ht, token):
keys = []
words = token[token['hashtag'] == ht]['word']
for w in words:
keys.append... | 1 | 2016-08-25T09:16:27Z | 39,141,643 | <pre><code>final_result = [pool.apply_async(toParallel, args=(ht,token,)) for ht in hashtag['hashtag']]
</code></pre>
<p>You can either use <code>Pool.apply()</code> and get the result right away (in which case you do not need <code>multiprocessing</code> hehe, the function is just there for completeness) or use <code... | 1 | 2016-08-25T09:34:54Z | [
"python",
"dictionary",
"multiprocessing"
] |
Slicing list with different string matching conditions | 39,141,251 | <p>I'd like to slice a list of strings based on substrings <em>possibly</em> contained into its elements:</p>
<pre><code>l = ['Some long text', 'often begins', ' with ',
'impenetrable fog ', 'which ends', ' somewhere further']
startIndex = [u for u, v in enumerate(l) if 'begins' in v)][0]
finalIndex = [u for u, v... | 3 | 2016-08-25T09:17:14Z | 39,141,922 | <p>Try:</p>
<pre><code>l = ['Some long text', 'often begins', 'with', 'impenetrable fog', 'which ends', 'somewhere further']
"""
return the index of the phase in 'phases' if phase contains 'word'
if not found, return 'default'
"""
def index(phases, word, default):
for i, s in enumerate(phases):
if word in... | 1 | 2016-08-25T09:48:21Z | [
"python",
"indexing",
"list-comprehension",
"slice"
] |
Slicing list with different string matching conditions | 39,141,251 | <p>I'd like to slice a list of strings based on substrings <em>possibly</em> contained into its elements:</p>
<pre><code>l = ['Some long text', 'often begins', ' with ',
'impenetrable fog ', 'which ends', ' somewhere further']
startIndex = [u for u, v in enumerate(l) if 'begins' in v)][0]
finalIndex = [u for u, v... | 3 | 2016-08-25T09:17:14Z | 39,142,006 | <p>Or with <a href="https://docs.python.org/2/library/functions.html#next" rel="nofollow"><code>next()</code></a>:</p>
<pre><code>l = ['Some long text', 'often begins', ' with ', 'impenetrable fog ',
'which ends', ' somewhere further']
startIndex = next((u for u, v in enumerate(l) if 'begins' in v), 0)
finalI... | 1 | 2016-08-25T09:52:03Z | [
"python",
"indexing",
"list-comprehension",
"slice"
] |
Slicing list with different string matching conditions | 39,141,251 | <p>I'd like to slice a list of strings based on substrings <em>possibly</em> contained into its elements:</p>
<pre><code>l = ['Some long text', 'often begins', ' with ',
'impenetrable fog ', 'which ends', ' somewhere further']
startIndex = [u for u, v in enumerate(l) if 'begins' in v)][0]
finalIndex = [u for u, v... | 3 | 2016-08-25T09:17:14Z | 39,142,075 | <pre><code>>>> l = ['Some long text', 'often begins', ' with ',
... 'impenetrable fog ', 'which ends', ' somewhere further']
>>> start, end = 'begins', 'ends'
>>> key_index = {'start': {'word': start, 'index': -1},
'end': {'word': end, 'index': -1}}
>>> for i, ... | 1 | 2016-08-25T09:55:26Z | [
"python",
"indexing",
"list-comprehension",
"slice"
] |
Python 2.7: TypeError: 'float' object has no attribute '__getitem__' | 39,141,466 | <p>I am new to programming and Python so please kindly excuse if this is a silly mistake.</p>
<p>I am trying to run a script where I want to generate sample data based on lognormal distribution and then plot a histogram of that data.</p>
<p>I keep getting error</p>
<p>Here's my code:</p>
<pre><code>import numpy as ... | 1 | 2016-08-25T09:26:46Z | 39,141,560 | <p>From the <a href="http://matplotlib.org/api/pyplot_api.html" rel="nofollow">matplotlib API</a>
<code>a</code> should be an array or sequence and if I'm right in your code it is a single number not an array</p>
| 0 | 2016-08-25T09:30:52Z | [
"python",
"python-2.7",
"python-3.x",
"numpy"
] |
Any better way to calculate product of multiple lists? | 39,141,616 | <p>I need to get all possible combinations based on n-number of input lists and do some stuff to them.</p>
<p>current code example:</p>
<pre><code>import itertools
# example inputs
list_small = [1, 2, 3]
list_medium = [444, 666, 242]
list_huge = [1680, 7559, 5573, 43658, 530, 11772, 284, 50078, 783, 37809, 6740, 377... | 0 | 2016-08-25T09:33:32Z | 39,141,872 | <p>Generating such nested lists could get you into trouble with memory limitations. Instead of repeatedly generating sublists, you can use just one super list generated from the largest number in the list. Just store the indices where smaller elements would have stopped.</p>
<p>For e.g., [1, 6, 10] - [0, 1, 2, 3, 4, 5... | 1 | 2016-08-25T09:45:56Z | [
"python",
"python-2.7",
"itertools",
"pypy",
"xrange"
] |
schema free solution to BigQuery Load job | 39,141,642 | <h3>Background</h3>
<p>I studied and found that bigQuery doesn't accept schemas defined by online tools (which have different formats, even though meaning is same).
So, I found that if I want to load data (where no. of columns keeps varying and increasing dynamically) into a table which has a fixed schema.</p>
<h3>Th... | 0 | 2016-08-25T09:34:52Z | 39,172,452 | <p>We are in the process of releasing a new feature that can update the schema of the destination table within a load/query job. With autodetect and the new feature you can directly load the new data to the existing table, and the schema will be updated as part of the load job. Please stay tuned. The current ETA is 2 w... | 1 | 2016-08-26T18:17:36Z | [
"python",
"google-analytics",
"google-bigquery",
"google-cloud-platform"
] |
Generate numbers from a set of digits | 39,141,782 | <p>I am trying to generate all possible combinations of three numbers derived from a set of numbers.<br>
Let's say I have the digits 1 to 9 (once each) I would like to generate a triple of numbers like <code>14, 983, 7256</code> (but all possible combinations). So every digit can only be used once and all digits have t... | 0 | 2016-08-25T09:42:02Z | 39,142,501 | <p>This is how I would do it, assuming order matters:</p>
<p>@ outcomes is a list of the desired options e.g. if you want a number with numerals 0-9, use output [0,1, . . ., 9].</p>
<p>@ length is the number of digits in each output number. You used up to 4 digits in your question, I assume there is some upper limit.... | 0 | 2016-08-25T10:14:18Z | [
"python",
"numbers"
] |
Generate numbers from a set of digits | 39,141,782 | <p>I am trying to generate all possible combinations of three numbers derived from a set of numbers.<br>
Let's say I have the digits 1 to 9 (once each) I would like to generate a triple of numbers like <code>14, 983, 7256</code> (but all possible combinations). So every digit can only be used once and all digits have t... | 0 | 2016-08-25T09:42:02Z | 39,143,435 | <p>We can assume one list like [14,983,2567] to be a number sequence 149832567,then we add two commas to it, one after 4 and the other after 3,so we generate a triple of numbers [14,983,2567].</p>
<p>So,how many number sequences can be generated?</p>
<pre><code>In [1]: import itertools
In [2]: a = range(1,10)
In [3... | 1 | 2016-08-25T10:58:03Z | [
"python",
"numbers"
] |
Use of Pandas to slice and create Lists | 39,141,791 | <p>After some research on csv / pandas / etc to manipulate a huge csv file I decide to use pandas to slice just the information I need.
Now I am able to get just what I need using a filter i.e. "Name"="Greg" where I just see rows when the column Name has Greg.
However I would like now to create a pyhton List with all i... | 1 | 2016-08-25T09:42:18Z | 39,141,817 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.tolist.html" rel="nofollow"><code>tolist</code></a>:</p>
<pre><code>#output is Series - column Cit... | 1 | 2016-08-25T09:43:27Z | [
"python",
"list",
"pandas",
"dataframe",
"condition"
] |
Capitalize first letter of each word in the column Python | 39,141,856 | <p>how do you capitalize the first letter of each word in the column? I am using python pandas by the way. For example, </p>
<pre><code> Column1
The apple
the Pear
Green tea
</code></pre>
<p>My desire result will be:</p>
<pre><code> Column1
The Apple
The P... | 1 | 2016-08-25T09:45:16Z | 39,141,892 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.title.html" rel="nofollow"><code>str.title</code></a>:</p>
<pre><code>print (df.Column1.str.title())
0 The Apple
1 The Pear
2 Green Tea
Name: Column1, dtype: object
</code></pre>
<p>Another very similar method is... | 2 | 2016-08-25T09:46:41Z | [
"python",
"string",
"pandas",
"dataframe",
"capitalization"
] |
Numpy---How to substitute by certain multi-elements in array at the same time? | 39,141,895 | <p>I have a problem during substitution with data in array:
say, </p>
<pre><code>a = [1, 0, 0]
b = [0, 0, 0]
c = [0, 0]
X = numpy.zeros((3, 3, 2))
</code></pre>
<p>and I have Matrix <code>Y</code> with shape (2,3,2) and it is non a zero matrix</p>
<p>Now; I want to equal these elements of X by Y directly;</p>
<pre>... | 1 | 2016-08-25T09:46:51Z | 39,142,599 | <p>You could use <a href="http://docs.scipy.org/doc/numpy-1.9.0/reference/generated/numpy.ix_.html" rel="nofollow"><code>np.ix_</code></a> to construct index arrays appropriate for indexing <code>X</code>:</p>
<pre><code>import numpy as np
np.random.seed(2016)
a=np.array([1, 0, 0])
b=np.array([0, 0, 0])
c=np.array([0,... | 1 | 2016-08-25T10:18:26Z | [
"python",
"arrays",
"numpy"
] |
order of unpacking *args in Python | 39,141,899 | <p>I wonder why variable <code>last</code>is <code>5</code>
when i do</p>
<pre><code>first, *rest, last = 1,2,3,4,5
</code></pre>
<p>I thought assignment goes from left to right, thus
<code>*rest</code> will be <code>[2,3,4,5]</code>, but it actualy is <code>[2,3,4]</code>
And I thought that last will be empty, or t... | 1 | 2016-08-25T09:47:07Z | 39,141,953 | <p>This is a valid syntax only in Python 3, is called "extended unpacking" and it is defined in PEP 3132 - <a href="https://www.python.org/dev/peps/pep-3132/" rel="nofollow">https://www.python.org/dev/peps/pep-3132/</a></p>
| 4 | 2016-08-25T09:49:50Z | [
"python",
"python-3.x",
"args"
] |
order of unpacking *args in Python | 39,141,899 | <p>I wonder why variable <code>last</code>is <code>5</code>
when i do</p>
<pre><code>first, *rest, last = 1,2,3,4,5
</code></pre>
<p>I thought assignment goes from left to right, thus
<code>*rest</code> will be <code>[2,3,4,5]</code>, but it actualy is <code>[2,3,4]</code>
And I thought that last will be empty, or t... | 1 | 2016-08-25T09:47:07Z | 39,141,978 | <p>Just because it's unpacking feature. </p>
<p><code>first</code> and <code>last</code> are just variables, when <code>*rest</code> are arguments, so they get everything between <code>first</code> and <code>last</code> value in tuple (1,2,3,4,5).</p>
<p>If you want to have you wrote:</p>
<pre><code>[2,3,4,5]
</code... | 0 | 2016-08-25T09:50:49Z | [
"python",
"python-3.x",
"args"
] |
Improve flatten function in python | 39,141,938 | <p>Given function needs some improvements:</p>
<pre class="lang-py prettyprint-override"><code>def flatten(d, parent_key=''):
items = []
for k, v in d.items():
try:
items.extend(flatten(v, '%s%s.' % (parent_key, k)).items())
except AttributeError:
items.append(('%s%s' % ... | 0 | 2016-08-25T09:49:09Z | 39,142,214 | <p>Try this,</p>
<pre><code>def flattern(dict_):
result = {}
for key in dict_:
for i,j in enumerate(dict_[key]):
result[key+'['+str(i)+']'] = j
return result
</code></pre>
<p>call function like this,</p>
<pre><code>In [40]: d
Out[40]: {'a': [1, 2, 3, 7], 'd': [1, 2, 3]}
In [41]: flat... | 0 | 2016-08-25T10:01:21Z | [
"python",
"list",
"dictionary",
"flatten"
] |
Python - method of a class with an optional argument and default value a class member | 39,141,993 | <p>I have something like this (I know this code doesn't work, but it's the closer to what I want to achieve):</p>
<pre><code>class A:
def __init__(self):
self.a = 'a'
def method(self, a=self.a):
print a
myClass = A()
myClass.method('b') # print b
myClass.method() # print a
</code></pre>
<p>... | 1 | 2016-08-25T09:51:33Z | 39,142,073 | <p>Default arguments are evaluated at <strong>definition time</strong>. By the time the class and method are defined <code>self.a</code> is not.</p>
<p>Your working code example is actually the only clean way of achieving this behavior.</p>
| 3 | 2016-08-25T09:55:17Z | [
"python"
] |
Python - method of a class with an optional argument and default value a class member | 39,141,993 | <p>I have something like this (I know this code doesn't work, but it's the closer to what I want to achieve):</p>
<pre><code>class A:
def __init__(self):
self.a = 'a'
def method(self, a=self.a):
print a
myClass = A()
myClass.method('b') # print b
myClass.method() # print a
</code></pre>
<p>... | 1 | 2016-08-25T09:51:33Z | 39,142,079 | <p>The default is evaluated at method definition time, i.e. when the interpreter executes the class body, which usually happens only once. Assigning a dynamic value as default can only happen within the method body, and the approach you use is perfectly fine.</p>
| 2 | 2016-08-25T09:55:46Z | [
"python"
] |
Why do I get different predict results between Xgboost's python and CLI version? | 39,142,015 | <p>Recently,when I try to use xgboost's CLI version to predict the inputs I found its results is much different from the python version.</p>
<p>With python,I predict it like this:</p>
<pre><code>data = xgb.DMatrix(X)
bst = xgb.Booster()
bst.load_model(modelfile)
leafindex = bst.predict(data, pred_leaf=False)
</code><... | 1 | 2016-08-25T09:52:26Z | 39,159,108 | <p>Solved!</p>
<p>It seems that the model file trained by the python and the cli can't be used by each other.
And when use the model trained by each self the results still have a little difference like these:</p>
<pre><code>by python by cli
0.169874 0.222063
0.999997 0.999554
0.00454239 0.000... | 0 | 2016-08-26T05:48:52Z | [
"python",
"shell",
"machine-learning",
"xgboost"
] |
Retain Messages until a Subscription is Made using Python + Stomp | 39,142,052 | <p>I am currently writing two scripts to subscribe to a message server using the <em>stomp</em> client library, <em>write.py</em> to write data and <em>read.py</em> to get data.</p>
<p>If I start <em>read.py</em> first and then run <em>write.py</em>, <em>write.py</em> receives the messages correctly. </p>
<p>However,... | 0 | 2016-08-25T09:54:39Z | 39,144,105 | <p>The problem is that the messages are being sent to a topic.</p>
<p>The <a href="https://activemq.apache.org/apollo/documentation/stomp-manual.html#Destination_Types" rel="nofollow">Apollo Documentation</a> describes the difference between topics and queues as follows:</p>
<blockquote>
<p>Queues hold on to uncons... | 1 | 2016-08-25T11:30:43Z | [
"python",
"python-2.7",
"message-queue",
"stomp"
] |
Solution to avoid hard coding python | 39,142,137 | <p>I want a solution to avoid hard coding in this if condition of my python script:</p>
<pre><code>if (x.get('name')=='location'):
</code></pre>
<p>this is to be used for extracting the location tag from an xml file . user must modify this according to the xml file being used.
so what i must do ?</p>
| -4 | 2016-08-25T09:58:16Z | 39,142,206 | <pre><code>check_tag = raw_input("Enter the tag you wish to search for: ")
if (x.get('name')==check_tag):
</code></pre>
<p>use <code>input()</code> instead of <code>raw_input()</code> if using python 3</p>
| 0 | 2016-08-25T10:01:11Z | [
"python"
] |
Python Grok Learning exception of type IndexError | 39,142,168 | <p>I just started learning python a few days ago and I have been using Grok Learning. For the challenge I have everything working as far as i can see but when i submit it i am told "Testing yet another case that starts with a vowel. Your submission raised an exception of type IndexError. This occurred on line 8 of your... | 0 | 2016-08-25T09:59:26Z | 39,142,368 | <p><strong>You have recieved only two letters string as input</strong> which means you cannot access <code>msg[2]</code> because there are no such index. To handle that case you can define third value as next:</p>
<pre><code>if len(msg) > 2:
third = msg[2]
else:
third = None
</code></pre>
<p>Or use one li... | 0 | 2016-08-25T10:08:18Z | [
"python"
] |
Python Grok Learning exception of type IndexError | 39,142,168 | <p>I just started learning python a few days ago and I have been using Grok Learning. For the challenge I have everything working as far as i can see but when i submit it i am told "Testing yet another case that starts with a vowel. Your submission raised an exception of type IndexError. This occurred on line 8 of your... | 0 | 2016-08-25T09:59:26Z | 39,142,389 | <p>Well, this probably means the entered message has a length less than 3.
You should check if the message is long enough before trying to access it's content, otherwise you'll indeed get an <code>IndexError</code></p>
<pre><code>length = len(msg)
if length > 2:
third = msg[2]
</code></pre>
| 0 | 2016-08-25T10:09:14Z | [
"python"
] |
Define 2D matrix with non-zero elements only in a rectangular subregion | 39,142,199 | <p>Given two specified dimensions <code>N1</code> and <code>N2</code>, and some boundaries <code>ymin, ymax, xmin, xmax</code>, I want to build an <code>N1xN2</code> matrix (be it a numpy array or a plain python list) which is zero everywhere, except in a rectangular subregion specified by its boundaries.</p>
<p>To be... | 1 | 2016-08-25T10:00:59Z | 39,142,337 | <pre><code>def rectangular_sparse_matrix(N1, N2, ymin, ymax, xmin, xmax):
m = np.zeros([N1, N2])
m[ymin:ymax+1, xmin:xmax+1] = 1
return m
</code></pre>
<p>In the function slicing numpy array is used.</p>
| 2 | 2016-08-25T10:07:08Z | [
"python",
"numpy",
"matrix",
"sparse-matrix"
] |
SyntaxError: encoding declaration in Unicode string | 39,142,304 | <p>If I try to use a magic comment like <code>#coding=utf-8</code> on top of a file, here's what happens:</p>
<pre><code>Traceback (most recent call last):
File <string>, line 0
SyntaxError: encoding declaration in Unicode string
</code></pre>
<p>I really haven't done anything wrong. Here is the code:</p>
<p... | 0 | 2016-08-25T10:05:48Z | 39,142,445 | <p>You omitted something from your question: You are using <code>exec</code> to execute this code. And you passed a <em>Unicode object</em> to exec, which means you already have stated that the source is Unicode text:</p>
<pre><code>>>> code = '''\
... # coding=utf8
... print 'hello world!'
... '''
>>&g... | 4 | 2016-08-25T10:11:40Z | [
"python",
"unicode"
] |
output on a new line in python curses | 39,142,340 | <p>I am using curses module in python to display output in real time by reading a file.
The string messages are output to the console using addstr() function
but I am not able to achieve printing to a newline wherever I need.</p>
<p>sample code: </p>
<pre><code>import json
import curses
w=curses.initscr()
try:
w... | 1 | 2016-08-25T10:07:20Z | 39,154,432 | <p>There's not enough program to offer more than general advice:</p>
<ul>
<li>you will get an error when printing to the end of the screen if your script does not enable scrolling (see <a href="https://docs.python.org/2/library/curses.html#curses.window.scroll" rel="nofollow"><code>window.scroll</code></a>).</li>
<li>... | 1 | 2016-08-25T20:43:45Z | [
"python",
"curses",
"python-curses"
] |
Merging Python Dictionaries and adding similar value of values | 39,142,369 | <p>I have a list of dictionaries like :</p>
<pre><code>[{'A': 2, 'B': u'cat'}, {'A': 1, 'B': u'dog'}, {'A': 3, 'B': u'rabbit'}, {'A': 4, 'B': u'cat'}, {'A': 4, 'B': u'dog'}, {'A': 8, 'B': u'rabbit'}]
</code></pre>
<p>I want to convert it into :</p>
<pre><code>[{'cat':'6'},{'dog':'5'}, {'rabbit':'11'}]
</code></pre>
... | -4 | 2016-08-25T10:08:19Z | 39,142,841 | <pre><code>>>> my_list = [{'A': 2, 'B': u'cat'}, {'A': 1, 'B': u'dog'}, {'A': 3, 'B': u'rabbit'}, {'A': 4, 'B': u'cat'}, {'A': 4, 'B': u'dog'}, {'A': 8, 'B': u'rabbit'}]
>>> new_dict = {}
>>> for item in my_list:
... new_dict[item['B']] = new_dict.get(item['B'], 0) + item['A']
...
>>... | 1 | 2016-08-25T10:29:26Z | [
"python",
"python-2.7",
"dictionary"
] |
Histogram with Python | 39,142,435 | <p>I have a dataframe df_Ratio with this structure </p>
<pre><code>class_energy ACT_TIME_AERATEUR_1_F1 ACT_TIME_AERATEUR_1_F3 ACT_TIME_AERATEUR_1_F5 ACT_TIME_AERATEUR_1_F6 ACT_TIME_AERATEUR_1_F7 ACT_TIME_AERATEUR_1_F8
high 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667
low 0.166964 0.167003 0.167081 0.166935 0... | 0 | 2016-08-25T10:11:23Z | 39,143,971 | <p>I'm not sure if I got everything right, but here is a working example:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.txt', sep=' ')
df = df.T # transpose dataframe
plt.bar(range(len(df.high)-1), df.high[1:], align='center')
plt.xticks(range(len(df.high)-1), df.in... | 0 | 2016-08-25T11:25:03Z | [
"python",
"matplotlib",
"plot",
"dataframe",
"histogram"
] |
How to render Form instance in Django CreateView & UpdateView? | 39,142,436 | <p>I'm trying to refactor my code into class-based views, and I'm having trouble understanding how to return/render at the end. I'm trying to render the form with the supplied POST data on success (or fail), with an appropriate confirmation message, so that it can be updated. Here's some example code, with comments sho... | 0 | 2016-08-25T10:11:24Z | 39,142,702 | <p>You shouldn't be doing any of that there. The view is already taking care of calling the validation methods and redisplaying the form if validation fails; <code>form_valid</code> is only called if the form is already valid. Your user check should go into the form itself:</p>
<pre><code>class ProductCreateForm(forms... | 1 | 2016-08-25T10:22:44Z | [
"python",
"django"
] |
Convert python code with sha to php | 39,142,539 | <p>got a problem with converting python to php. I've got the following code in python: </p>
<pre><code>user = "DdrkmK5uFKmaaeNqfqReMADSUJ4sVSLrV2A8Bvs8"
passing = "K9hvwANSBW5tLYzuWptWMByTtzZZKHzm"
sha = hashlib.sha256()
sha.update(user)
sha.update(passing)
sha_A = [ord(x) for x in sha.digest()]
</code></pre>
<p><co... | 0 | 2016-08-25T10:15:50Z | 39,143,015 | <p>I saw few errors in your PHP code.</p>
<p>This is a python snippet:</p>
<pre><code>>>> sha = hashlib.sha256()
>>> sha.update(user)
>>> sha.update(passing)
>>> sha_A = [ord(x) for x in sha.digest()]
[135, 146, 107, 215, 70, 126, 179, 21, 19, 177, 191, 236, 182, 136, 192, 53, 148,... | 0 | 2016-08-25T10:37:04Z | [
"php",
"python",
"hash",
"sha",
"digest"
] |
is Dataframe.toPandas always on driver node or on worker nodes? | 39,142,549 | <p>Imagine you are loading a large dataset by the SparkContext and Hive. So this dataset is then distributed in your Spark cluster. For instance a observations (values + timestamps) for thousands of variables.</p>
<p>Now you would use some map/reduce methods or aggregations to organize/analyze your data. For instance ... | 0 | 2016-08-25T10:16:12Z | 39,155,081 | <p>There is nothing special about Pandas <code>DataFrame</code> in this context.</p>
<ul>
<li>If <code>DataFrame</code> is created by using <code>toPandas</code> method on <code>pyspark.sql.dataframe.DataFrame</code> <a href="http://stackoverflow.com/a/30991297/1560062">this collects data and creates local Python obje... | 1 | 2016-08-25T21:35:57Z | [
"python",
"hadoop",
"pandas",
"apache-spark",
"pyspark"
] |
Python: How to determine the language? | 39,142,778 | <p>I want to get this: </p>
<pre><code>Input text: "ÑÑÌÑÑкий ÑзÑÌк"
Output text: "Russian"
Input text: "䏿"
Output text: "Chinese"
Input text: "ã«ã»ãã"
Output text: "Japanese"
Input text: "Ø§ÙØ¹ÙØ±ÙØ¨ÙÙÙÙØ©"
Output text: "Arabic"
</code></pre>
<p>How can I do it in python? Thanks.... | -1 | 2016-08-25T10:26:00Z | 39,143,059 | <p>Have you had a look at <a href="https://pypi.python.org/pypi/langdetect?" rel="nofollow">langdetect</a>?</p>
<pre><code>from langdetect import detect
lang = detect("Ein, zwei, drei, vier")
print lang
#output: de
</code></pre>
| 3 | 2016-08-25T10:38:59Z | [
"python",
"string",
"parsing"
] |
Python: How to determine the language? | 39,142,778 | <p>I want to get this: </p>
<pre><code>Input text: "ÑÑÌÑÑкий ÑзÑÌк"
Output text: "Russian"
Input text: "䏿"
Output text: "Chinese"
Input text: "ã«ã»ãã"
Output text: "Japanese"
Input text: "Ø§ÙØ¹ÙØ±ÙØ¨ÙÙÙÙØ©"
Output text: "Arabic"
</code></pre>
<p>How can I do it in python? Thanks.... | -1 | 2016-08-25T10:26:00Z | 39,143,700 | <p>You can try determining the Unicode group of chars in input string to point out type of language, (Cyrillic for Russian, for example), and then search for language-specific symbols in text.</p>
| 0 | 2016-08-25T11:10:34Z | [
"python",
"string",
"parsing"
] |
Accessing the dataLayer (JS variable) when scrapping with python | 39,142,846 | <p>I'm using beautiful soup to scrap a webpages. I want to access the dataLayer (a javascript variable) that is present on this <a href="http://www.allocine.fr/video/player_gen_cmedia=19561982&cfilm=144185.html" rel="nofollow">webpage</a>? How can I retrieve it using python?
<a href="http://i.stack.imgur.com/p1SeD.... | 1 | 2016-08-25T10:29:40Z | 39,146,127 | <p>The beautifulsoup is not a JavaScript emulator, so you can't execute JS and get the content of a var. But maybe this var is populated by an ajax request and if you send the same request with your python script you can get touch those data. </p>
<p>In the other hand, if this data is statically assigned, then you can... | 1 | 2016-08-25T13:03:08Z | [
"javascript",
"python",
"python-2.7",
"web-scraping",
"beautifulsoup"
] |
Accessing the dataLayer (JS variable) when scrapping with python | 39,142,846 | <p>I'm using beautiful soup to scrap a webpages. I want to access the dataLayer (a javascript variable) that is present on this <a href="http://www.allocine.fr/video/player_gen_cmedia=19561982&cfilm=144185.html" rel="nofollow">webpage</a>? How can I retrieve it using python?
<a href="http://i.stack.imgur.com/p1SeD.... | 1 | 2016-08-25T10:29:40Z | 39,153,525 | <p>You can parse it from the source with the help of <em>re</em> and <em>json.loads</em> to find the correct <em>script tag</em> that contains the json:</p>
<pre><code>from bs4 import BeautifulSoup
import re
from json import loads
url = "http://www.allocine.fr/video/player_gen_cmedia=19561982&cfilm=144185.html"
s... | 1 | 2016-08-25T19:42:14Z | [
"javascript",
"python",
"python-2.7",
"web-scraping",
"beautifulsoup"
] |
python shapely: check if a polygon is a multipolygon | 39,142,876 | <p>How can I check if a polygon entity is actually a multipolygon?
I've tried: </p>
<pre><code>if len(polygon)>1:
</code></pre>
<p>but then get the error:</p>
<pre><code>TypeError: object of type 'Polygon' has no len()
</code></pre>
<p>I've tried <code>Nill</code>, <code>None</code> and others, nothing worked.</... | 2 | 2016-08-25T10:30:47Z | 39,145,245 | <p>Ok, this worked for me:</p>
<pre><code>print ('type = ', type(poly))
</code></pre>
<p>outputs with:</p>
<pre><code>type = <class 'shapely.geometry.polygon.Polygon'>
</code></pre>
<p>in case of a polygon, and: </p>
<pre><code>type = <class 'shapely.geometry.multipolygon.MultiPolygon'>
</code></pre>... | 2 | 2016-08-25T12:23:34Z | [
"python",
"shapely"
] |
Can't load Flask config from parent directory | 39,142,928 | <p>I'm trying to follow the docs here on using configuration files: <a href="http://exploreflask.com/en/latest/configuration.html#the-simple-case" rel="nofollow">http://exploreflask.com/en/latest/configuration.html#the-simple-case</a></p>
<p>I want to use what they call "the simple case" but I want to load the <code>c... | 1 | 2016-08-25T10:33:09Z | 39,146,631 | <p>You can't load it from there because as the error message says:</p>
<blockquote>
<pre><code>- missing __init__.py in a package;
- package or module path not included in sys.path;
</code></pre>
</blockquote>
<p>It's not part of a package that is importable. This may have worked locally because you were running <co... | 2 | 2016-08-25T13:26:11Z | [
"python",
"flask"
] |
Read and wirte postgres script using python | 39,143,038 | <p>I have postgres tables and i want to run a <code>PostgreSQL</code> script file on these tables using python and then write the result of the queries in a csv file. The script file have multiple queries separated by semicolon <code>;</code>. Sample script is shown below</p>
<p><strong>Script file:</strong></p>
<pr... | 1 | 2016-08-25T10:37:47Z | 39,144,717 | <p>This is the simplest to output each query as a different file. <a href="http://initd.org/psycopg/docs/cursor.html#cursor.copy_expert" rel="nofollow"><code>copy_expert</code></a></p>
<pre><code>query = '''
select p.*, c.name
from
scale_polygons_v3 c
inner join
cartographic_v3 p on met... | 1 | 2016-08-25T11:59:08Z | [
"python",
"postgresql",
"csv"
] |
Read and wirte postgres script using python | 39,143,038 | <p>I have postgres tables and i want to run a <code>PostgreSQL</code> script file on these tables using python and then write the result of the queries in a csv file. The script file have multiple queries separated by semicolon <code>;</code>. Sample script is shown below</p>
<p><strong>Script file:</strong></p>
<pr... | 1 | 2016-08-25T10:37:47Z | 39,145,425 | <p>If you are able to change the SQL script a bit then here is a workaround:</p>
<pre><code>#!/usr/bin/env python
import psycopg2
script = '''
declare cur1 cursor for
select * from (values(1,2),(3,4)) as t(x,y);
declare cur2 cursor for
select 'a','b','c';
'''
print script
conn = psycopg... | 1 | 2016-08-25T12:32:26Z | [
"python",
"postgresql",
"csv"
] |
Launch a batch file stored in different directory from Python script in another directory | 39,143,132 | <p>I have created a Python script which needs to launch a <strong>.bat</strong> file based on some condition.</p>
<p>Python script location : <strong>\Component\myScript.py</strong></p>
<p>Batch file location : <strong>\Component\MS20160825\toExecute.bat</strong><br>
<em>The batch file internally uses some executable... | 0 | 2016-08-25T10:42:02Z | 39,143,492 | <p>Should solve all problems you are experiencing! </p>
<pre><code>import subprocess
p = subprocess.Popen('batch.bat', shell=True, stdin=subprocess.PIPE)
stdout, stderr = p.communicate()
</code></pre>
| 1 | 2016-08-25T11:00:50Z | [
"python",
"batch-file",
"subprocess",
"call",
"popen"
] |
Launch a batch file stored in different directory from Python script in another directory | 39,143,132 | <p>I have created a Python script which needs to launch a <strong>.bat</strong> file based on some condition.</p>
<p>Python script location : <strong>\Component\myScript.py</strong></p>
<p>Batch file location : <strong>\Component\MS20160825\toExecute.bat</strong><br>
<em>The batch file internally uses some executable... | 0 | 2016-08-25T10:42:02Z | 39,172,632 | <p>Thanks to all for their active suggestion.<br>
With small correction following code worked for me:</p>
<pre><code>import subprocess
batchFileLocation = 'Component\\MS20160825'
batchFileFullPath = os.path.join(batchFileLocation, 'toExecute.bat')
p = subprocess.Popen(os.path.abspath(batchFileFullPath), stdin=subpro... | 0 | 2016-08-26T18:27:08Z | [
"python",
"batch-file",
"subprocess",
"call",
"popen"
] |
Pandas: multiple condition to strings | 39,143,199 | <p>I try to change my dataframe.
Usually I use something like</p>
<pre><code>df1= df[df.url.str.contains("avito.ru/*/telefony/")]
</code></pre>
<p>But if I want a lot of condition?
I want to write to <code>contains</code> more than 100 strings.
How can I do that?</p>
<p>Dataframe</p>
<pre><code>Ð°Ð½Ð¾Ð½Ñ ÐºÐ¸Ð½Ð¾Ñ... | 2 | 2016-08-25T10:46:01Z | 39,143,517 | <p>You can create a pattern by joining <code>|</code> with all your list items and pass this to <code>str.contains</code>:</p>
<pre><code>In [31]:
lst = ['iphone', 'sony', 'alcatel', 'galaxy', 'samsumg','None']
pat = '|'.join(lst)
df[df['url'].str.contains(pat)]
Out[31]:
url
10 apple iphone
11 sam... | 0 | 2016-08-25T11:01:49Z | [
"python",
"pandas"
] |
Getting specific indexed distinct values in nested lists | 39,143,204 | <p>I have a nested list of around 1 million records like:</p>
<pre><code>l = [['a', 'b', 'c', ...], ['d', 'b', 'e', ...], ['f', 'z', 'g', ...],...]
</code></pre>
<p>I want to get the distinct values of inner lists on second index, so that my resultant list be like:</p>
<pre><code>resultant = ['b', 'z', ...]
</code><... | 2 | 2016-08-25T10:46:14Z | 39,143,255 | <p>Would that work for you? </p>
<pre><code>result = set([inner_list[1] for inner_list in l])
</code></pre>
| 0 | 2016-08-25T10:48:19Z | [
"python",
"nested-lists"
] |
Getting specific indexed distinct values in nested lists | 39,143,204 | <p>I have a nested list of around 1 million records like:</p>
<pre><code>l = [['a', 'b', 'c', ...], ['d', 'b', 'e', ...], ['f', 'z', 'g', ...],...]
</code></pre>
<p>I want to get the distinct values of inner lists on second index, so that my resultant list be like:</p>
<pre><code>resultant = ['b', 'z', ...]
</code><... | 2 | 2016-08-25T10:46:14Z | 39,143,334 | <p>Since you want the unique items you can use <code>collections.OrderedDict.fromkeys()</code> in order to keep the order and unique items (because of using hashtable fro keys) and use <code>zip()</code> to get the second items.</p>
<pre><code>from collections import OrderedDict
list(OrderedDict.fromkeys(zip(my_lists... | 1 | 2016-08-25T10:52:15Z | [
"python",
"nested-lists"
] |
Getting specific indexed distinct values in nested lists | 39,143,204 | <p>I have a nested list of around 1 million records like:</p>
<pre><code>l = [['a', 'b', 'c', ...], ['d', 'b', 'e', ...], ['f', 'z', 'g', ...],...]
</code></pre>
<p>I want to get the distinct values of inner lists on second index, so that my resultant list be like:</p>
<pre><code>resultant = ['b', 'z', ...]
</code><... | 2 | 2016-08-25T10:46:14Z | 39,143,533 | <p>I can think of two options. </p>
<p>Set comprehension:</p>
<pre><code>res = {x[1] for x in l}
</code></pre>
<p>I think numpy arrays work faster than list/set comprehensions, so converting this list to an array and then using array functions can be faster. Here:</p>
<pre><code>import numpy as np
res = np.unique(... | 0 | 2016-08-25T11:02:55Z | [
"python",
"nested-lists"
] |
Getting specific indexed distinct values in nested lists | 39,143,204 | <p>I have a nested list of around 1 million records like:</p>
<pre><code>l = [['a', 'b', 'c', ...], ['d', 'b', 'e', ...], ['f', 'z', 'g', ...],...]
</code></pre>
<p>I want to get the distinct values of inner lists on second index, so that my resultant list be like:</p>
<pre><code>resultant = ['b', 'z', ...]
</code><... | 2 | 2016-08-25T10:46:14Z | 39,143,721 | <p>You can unzip the list of lists then choice the second tuple with set like below :
This code take 4.05311584473e-06 millseconds, in my laptop </p>
<pre><code>list(set(zip(*lst)[1]))
</code></pre>
<p>Input : </p>
<pre><code>lst = [['a', 'b', 'c'], ['d', 'b', 'e'], ['f', 'z', 'g']]
</code></pre>
<p>Out put :</p>
... | 1 | 2016-08-25T11:12:06Z | [
"python",
"nested-lists"
] |
Prevent adding duplicate data from excel forms imported into db | 39,143,221 | <p>I have a model on which data imported from an excel files are saved.
I want to prevent having duplicate entries,it will check the already existing data to see if they match with the ones .</p>
<p>My model</p>
<pre><code>from django.db import models
class UserData(models.Model):
GENDER_CHOICES = (
('M... | 0 | 2016-08-25T10:46:47Z | 39,241,437 | <p>1.Create one model form</p>
<pre><code>class UserDataForm(forms.ModelForm):
// code here
class Meta:
model = UserData
</code></pre>
<p>2. make the excel sheet data to dictionary format using.</p>
<pre><code>from pandas import *
xls = ExcelFile('path_to_file.xls')
df = xls.parse(xls.sheet_names[0])... | 1 | 2016-08-31T05:30:17Z | [
"python",
"django",
"django-forms"
] |
How to print the console to a text file AFTER the program finishes (Python)? | 39,143,417 | <p>I have a program that outputs many calculations and results to the console through the print statement. I want to write some code to export (or save) all the contents of the console to a simple text file. </p>
<p>I searched StackOverflow and other sites but I found some methods to redirect the print statement to pr... | 4 | 2016-08-25T10:57:07Z | 39,143,606 | <p>Ok, so normally to get it done, you have to rewrite python <code>print</code> built-in function. But... There is ipython, which provides some hooks.</p>
<p>First you need to have <code>ipython</code> installed:</p>
<pre><code>#bash
sudo pip install ipython
</code></pre>
<p>(I'm using sudo to simple locate then fo... | 2 | 2016-08-25T11:06:01Z | [
"python",
"console",
"save",
"text-files"
] |
How to print the console to a text file AFTER the program finishes (Python)? | 39,143,417 | <p>I have a program that outputs many calculations and results to the console through the print statement. I want to write some code to export (or save) all the contents of the console to a simple text file. </p>
<p>I searched StackOverflow and other sites but I found some methods to redirect the print statement to pr... | 4 | 2016-08-25T10:57:07Z | 39,143,624 | <p>There is a very obvious but not very elegant solution.</p>
<p>instead of:</p>
<pre><code>print statement 1
calculation
print statement 2
</code></pre>
<p>you can make something like</p>
<pre><code>sexport =''
calculation
print statement 1
sexport += statement1 + "\n"
calculaztion
print statement 2
sexport += sta... | -1 | 2016-08-25T11:06:57Z | [
"python",
"console",
"save",
"text-files"
] |
How to print the console to a text file AFTER the program finishes (Python)? | 39,143,417 | <p>I have a program that outputs many calculations and results to the console through the print statement. I want to write some code to export (or save) all the contents of the console to a simple text file. </p>
<p>I searched StackOverflow and other sites but I found some methods to redirect the print statement to pr... | 4 | 2016-08-25T10:57:07Z | 39,143,791 | <p>I am unsure how you could receive the contents of a console for any editor however this can be achieved quite simply by replacing your <code>print()</code> statements with <code>.write</code></p>
<pre><code>class Writer(object):
def __init__(self, out_file, overwrite=False):
self.file_name = out_file
... | 1 | 2016-08-25T11:15:15Z | [
"python",
"console",
"save",
"text-files"
] |
How to print the console to a text file AFTER the program finishes (Python)? | 39,143,417 | <p>I have a program that outputs many calculations and results to the console through the print statement. I want to write some code to export (or save) all the contents of the console to a simple text file. </p>
<p>I searched StackOverflow and other sites but I found some methods to redirect the print statement to pr... | 4 | 2016-08-25T10:57:07Z | 39,143,822 | <p>Maybe you should create a variable that will log the outputs and then put it into a file.</p>
<p>For ex:</p>
<pre><code>print statement
logger += statement+"\n" #a new line char so each statement is on a new line
with open('file.txt', 'a') as f:
f.write(statement)
</code></pre>
| 0 | 2016-08-25T11:17:08Z | [
"python",
"console",
"save",
"text-files"
] |
How to print the console to a text file AFTER the program finishes (Python)? | 39,143,417 | <p>I have a program that outputs many calculations and results to the console through the print statement. I want to write some code to export (or save) all the contents of the console to a simple text file. </p>
<p>I searched StackOverflow and other sites but I found some methods to redirect the print statement to pr... | 4 | 2016-08-25T10:57:07Z | 39,145,632 | <p>After I know understood your question I think you search the tee command</p>
<pre><code>python your_program | tee output.txt
</code></pre>
<p>This will show you the output both, in the console and in output.txt</p>
<p>PS: Since you did not answer to my comment which OS you use I assumed that you use either Linux ... | 1 | 2016-08-25T12:41:39Z | [
"python",
"console",
"save",
"text-files"
] |
How to print the console to a text file AFTER the program finishes (Python)? | 39,143,417 | <p>I have a program that outputs many calculations and results to the console through the print statement. I want to write some code to export (or save) all the contents of the console to a simple text file. </p>
<p>I searched StackOverflow and other sites but I found some methods to redirect the print statement to pr... | 4 | 2016-08-25T10:57:07Z | 39,147,116 | <p>You could override the <code>print</code> function which will still be accessible through the <code>builtins</code> module</p>
<pre><code>import builtins
f = open("logs.txt", "w")
def print(*args, sep=' ', end='\n', **kwargs):
builtins.print(*args, sep=sep, end=end, **kwargs)
f.write(sep.join(*args) + end... | 1 | 2016-08-25T13:47:53Z | [
"python",
"console",
"save",
"text-files"
] |
How to print the console to a text file AFTER the program finishes (Python)? | 39,143,417 | <p>I have a program that outputs many calculations and results to the console through the print statement. I want to write some code to export (or save) all the contents of the console to a simple text file. </p>
<p>I searched StackOverflow and other sites but I found some methods to redirect the print statement to pr... | 4 | 2016-08-25T10:57:07Z | 39,190,845 | <p>With all thanks and respect to all who contributed to this question. I have finally found a solution to this problem with minimal modifications to my original code. The solution is provided by the member @Status and <a href="http://stackoverflow.com/a/24583265/5820024">here is its link</a> .</p>
<p>Although I searc... | 0 | 2016-08-28T11:37:07Z | [
"python",
"console",
"save",
"text-files"
] |
OOP - Accessing Object Data | 39,143,577 | <p>Apologies if this is a repeated or simple question.</p>
<p>I have recently been learning Python (having spent many years writing simple MATLAB scripts). I've started exploring Object Oriented Programming and JSON.</p>
<p>I am trying to use an API to collect data from a server. When the objects are returned I'm mos... | 0 | 2016-08-25T11:04:45Z | 39,143,697 | <p>Please try:</p>
<pre><code>rowId = row['results'][0]['objectId']
</code></pre>
| 1 | 2016-08-25T11:10:22Z | [
"python",
"oop",
"smartsheet-api"
] |
OOP - Accessing Object Data | 39,143,577 | <p>Apologies if this is a repeated or simple question.</p>
<p>I have recently been learning Python (having spent many years writing simple MATLAB scripts). I've started exploring Object Oriented Programming and JSON.</p>
<p>I am trying to use an API to collect data from a server. When the objects are returned I'm mos... | 0 | 2016-08-25T11:04:45Z | 39,148,925 | <p>Your library code clearly says, that <code>SearchResultItem</code> has <a href="https://github.com/smartsheet-platform/smartsheet-python-sdk/blob/master/smartsheet/models/search_result_item.py#L108" rel="nofollow">a property <code>.object_id</code></a>.</p>
<pre><code>print(reportingRow.results[0].object_id) # thi... | 0 | 2016-08-25T15:13:26Z | [
"python",
"oop",
"smartsheet-api"
] |
Is there a way to look up by index value without handling errors? | 39,143,640 | <p>I have a dataframe that looks like this:</p>
<pre><code> pmid
id
NCT02835976 NaN
NCT02835885 1235
NCT02835560 1270
NCT02835118 NaN
</code></pre>
<p>Now I want to find the row that matches a particular key. I can do <code>df.loc(x)</c... | 1 | 2016-08-25T11:07:35Z | 39,144,408 | <p>You can try something like following:</p>
<pre><code>df[df.index == 'NCT01001741']
</code></pre>
<p>This will return no error</p>
| 0 | 2016-08-25T11:45:34Z | [
"python",
"pandas"
] |
run two thread concurrently and both of them manipulate single variable | 39,143,671 | <p>it's my code:</p>
<pre><code>import threading
x=0
class a(threading.thread)
def run(self):
global x
for i in range(1000000):
x+=1
class b(threading.thread)
def run(self):
global x
for i in range(1000000):
x-=1
def run():
a().start()
b().star... | 1 | 2016-08-25T11:08:58Z | 39,143,815 | <p>Race conditions. The actual operation of <code>x += 1</code> is roughly:</p>
<ol>
<li>Load the value of <code>x</code></li>
<li>Compute <code>x + 1</code></li>
<li>Store the computed value to <code>x</code></li>
</ol>
<p>Except with threading, you might get preempted by the other thread after step 1 and before ste... | 5 | 2016-08-25T11:16:40Z | [
"python",
"multithreading",
"concurrency",
"race-condition"
] |
Google Analytics Reporting API (Python) - How can I obtain previous and next page path? | 39,143,682 | <p>Using the google analytics portal, i can check the previous and next page path for a given path (for an example, see below) [ Behavior > Site Content > All Pages > Navigation Summary)</p>
<p><a href="http://i.stack.imgur.com/7Gxx4.png" rel="nofollow"><img src="http://i.stack.imgur.com/7Gxx4.png" alt="enter image de... | 0 | 2016-08-25T11:09:28Z | 39,151,871 | <p>As <a href="http://stackoverflow.com/users/1841839/daimto">DalmTo</a> mentioned just query for the combination of <code>ga:pagePath</code> and <code>ga:previousPagePath</code> <a href="https://developers.google.com/analytics/devguides/reporting/core/dimsmets" rel="nofollow">Dimensions</a>.</p>
<pre><code>DIMENSIONS... | 0 | 2016-08-25T17:56:40Z | [
"python",
"navigation",
"google-analytics-api"
] |
how to check whether a list element is in another list but also at the same index | 39,143,692 | <p>I need to check whether two lists have any same elements, but these same elements must also be at same index positions.</p>
<p>I came up with a following ugly solution:</p>
<pre><code>def check_any_at_same_index(list_input_1, list_input_2):
# set bool value
check_if_any = 0
for index, element in enumer... | 3 | 2016-08-25T11:10:04Z | 39,143,723 | <p>You can use <code>zip()</code> function and a generator expression within <code>any()</code> if you want to check if there are any equal items in same index.</p>
<pre><code>any(i == j for i, j in zip(list_input_1, list_input_2))
</code></pre>
<p>If you want to return that item (the first occurrence) you can use <c... | 5 | 2016-08-25T11:12:24Z | [
"python",
"python-2.7"
] |
Fetching parent's function from parent | 39,143,715 | <p>I override a function, but would like to get hold of the parent's function from within the parent.</p>
<pre><code>>>> class a:
... def __init__(self):
... print(self.f)
... def f(self):
... pass
...
>>> class b(a):
... def __init__(self):
... super(b... | -1 | 2016-08-25T11:11:47Z | 39,144,280 | <pre><code>class a(object):
def __init__(self):
pass
def f(self):
print 'Parent Method...'
class b(a):
def __init__(self):
super(b, self).__init__()
a.f(self) #referance the parent class rather than the child class, because the child overrides the parent method.
sel... | 0 | 2016-08-25T11:38:59Z | [
"python",
"python-3.x",
"inheritance"
] |
Fetching parent's function from parent | 39,143,715 | <p>I override a function, but would like to get hold of the parent's function from within the parent.</p>
<pre><code>>>> class a:
... def __init__(self):
... print(self.f)
... def f(self):
... pass
...
>>> class b(a):
... def __init__(self):
... super(b... | -1 | 2016-08-25T11:11:47Z | 39,144,471 | <p>You could use <a href="https://docs.python.org/3/tutorial/classes.html#private-variables" rel="nofollow">name mangling</a> to make <code>self.__f</code> refer to <code>A.__f</code> from within <code>A</code>'s class definition.</p>
<blockquote>
<p>Name mangling is helpful for letting subclasses override methods w... | 1 | 2016-08-25T11:48:29Z | [
"python",
"python-3.x",
"inheritance"
] |
What is the point of re-raising exceptions? | 39,143,878 | <p>So I've seen mention elsewhere of using the following to re-raise an exception.</p>
<pre><code>try:
whatever()
except:
raise
</code></pre>
<p>What is the purpose re-raising an exception? Surely an uncaught exception will just raise to the top anyway? i.e:</p>
<pre><code>try:
int("bad")
except:
rai... | 2 | 2016-08-25T11:19:36Z | 39,143,930 | <p>Your example code is pointless, but if you wanted to perform logging or cleanup that only occurs on failure, you could put that between the <code>except:</code> and the <code>raise</code> and you'd do that work and then proceed as if the original exception was bubbling normally.</p>
| 2 | 2016-08-25T11:22:52Z | [
"python",
"exception"
] |
What is the point of re-raising exceptions? | 39,143,878 | <p>So I've seen mention elsewhere of using the following to re-raise an exception.</p>
<pre><code>try:
whatever()
except:
raise
</code></pre>
<p>What is the purpose re-raising an exception? Surely an uncaught exception will just raise to the top anyway? i.e:</p>
<pre><code>try:
int("bad")
except:
rai... | 2 | 2016-08-25T11:19:36Z | 39,144,452 | <p>Imagine the following code.</p>
<p>A little setup: You are responsible for maintaining a huge database of information for example, and any loss of data would be catastrophic!</p>
<pre><code>huge_dictionary = {'lots_of_important':['stuffs']}
try:
check_data(new_data) #make sure the data is in the correct format... | 1 | 2016-08-25T11:47:47Z | [
"python",
"exception"
] |
Querying usb device by DeviceID with WQL | 39,143,972 | <p>I can get deviceID from WMI, then I want to use that deviceID to check weather device is in enabled\disabled state and if it's status is OK or not, basically I want to use WQL to query that device later on using this usb device unique DeviceID. Here is a code example that I used and got exception with</p>
<pre><cod... | 0 | 2016-08-25T11:25:04Z | 39,150,317 | <p><code>\</code> is a <a href="https://msdn.microsoft.com/en-us/library/aa394054(v=vs.85).aspx" rel="nofollow">special character</a> in WQL and must be escaped with a backslash so your <code>devid</code> should be this:</p>
<pre><code>devid = "'USB\\VID_04F2&PID_B315\\6&EF94D1A&0&6'"
</code></pre>
<p... | 0 | 2016-08-25T16:23:56Z | [
"python",
"wmi",
"wql"
] |
python request post doesn't submit | 39,144,120 | <p>I have a problem with request.post, instead of returning the html code with the results I get back the html code of the starting side. </p>
<pre><code>import requests
def test(pdb):
URL = "http://capture.caltech.edu/"
r = requests.post(URL,files={"upfile": open( pdb)})
content=r.text
print(content)
p... | 1 | 2016-08-25T11:31:17Z | 39,144,535 | <p>1 - You are posting to the wrong url, it should be <code>http://capture.caltech.edu/capture_ul.cgi</code>.</p>
<p>2 - There's an hidden field (<code>name='note'</code>) that must be sent (value of an empty string will be enough).</p>
<pre><code>...
def test(pdb):
URL = "http://capture.caltech.edu/capture_ul.cgi... | 2 | 2016-08-25T11:51:14Z | [
"python"
] |
Python write to ram file when using command line, ghostscript | 39,144,281 | <p>I want to run this command from python:<br>
<code>gs.exe -sDEVICE=jpeg -dTextAlphaBits=4 -r300 -o a.jpg a.pdf</code><br>
Using ghostscript, to convert pdf to series of images. How do I use the RAM for the input and output files? Is there something like <code>StringIO</code> that gives you a file path?</p>
<p>I noti... | 1 | 2016-08-25T11:39:00Z | 39,147,540 | <p>You can't use RAM for the input and output file using the Ghostscript demo code, it doesn't support it. You <strong>can</strong> pipe input from stdin and out to stdout but that's it for the standard code.</p>
<p>You can use the Ghostscript API to feed data from any source, and you can write your own device (or co-... | 1 | 2016-08-25T14:07:37Z | [
"python",
"file",
"cmd",
"ghostscript",
"ram"
] |
In this short recursive function `list_sum(aList)`, the finish condition is `if not aList: return 0`. I see no logic in why this condition works | 39,144,343 | <p>I am learning the recursive functions. I completed an exercise, but in a different way than proposed.</p>
<p>"Write a recursive function which takes a list argument and returns the sum of its integers."</p>
<pre><code>L = [0, 1, 2, 3, 4] # The sum of elements will be 10
</code></pre>
<p>My solution is:</p>
<pre... | 0 | 2016-08-25T11:41:54Z | 39,144,457 | <pre><code>not aList
</code></pre>
<p>return True if there is no elements in aList. That if statement in the solution covers edge case and checks if input parameter is not empty list.</p>
| 1 | 2016-08-25T11:48:01Z | [
"python",
"python-2.7",
"recursion"
] |
In this short recursive function `list_sum(aList)`, the finish condition is `if not aList: return 0`. I see no logic in why this condition works | 39,144,343 | <p>I am learning the recursive functions. I completed an exercise, but in a different way than proposed.</p>
<p>"Write a recursive function which takes a list argument and returns the sum of its integers."</p>
<pre><code>L = [0, 1, 2, 3, 4] # The sum of elements will be 10
</code></pre>
<p>My solution is:</p>
<pre... | 0 | 2016-08-25T11:41:54Z | 39,144,494 | <p>On the call of the function, <code>aList</code> will have no elements. Or in other words, the only element it has is <code>null</code>. A list is like a string or array. When you create a variable you reserve some space in the memory for it. Lists and such have a <code>null</code> on the very last position which mar... | 1 | 2016-08-25T11:49:26Z | [
"python",
"python-2.7",
"recursion"
] |
In this short recursive function `list_sum(aList)`, the finish condition is `if not aList: return 0`. I see no logic in why this condition works | 39,144,343 | <p>I am learning the recursive functions. I completed an exercise, but in a different way than proposed.</p>
<p>"Write a recursive function which takes a list argument and returns the sum of its integers."</p>
<pre><code>L = [0, 1, 2, 3, 4] # The sum of elements will be 10
</code></pre>
<p>My solution is:</p>
<pre... | 0 | 2016-08-25T11:41:54Z | 39,144,641 | <p>Python considers as False multiple values:</p>
<ul>
<li>False (of course)</li>
<li>0</li>
<li>None</li>
<li>empty collections (dictionaries, lists, tuples)</li>
<li>empty strings ('', "", '''''', """""", r'', u"", etc...)</li>
<li>any other object whose <a href="https://docs.python.org/2/reference/datamodel.html?hi... | 1 | 2016-08-25T11:55:40Z | [
"python",
"python-2.7",
"recursion"
] |
In this short recursive function `list_sum(aList)`, the finish condition is `if not aList: return 0`. I see no logic in why this condition works | 39,144,343 | <p>I am learning the recursive functions. I completed an exercise, but in a different way than proposed.</p>
<p>"Write a recursive function which takes a list argument and returns the sum of its integers."</p>
<pre><code>L = [0, 1, 2, 3, 4] # The sum of elements will be 10
</code></pre>
<p>My solution is:</p>
<pre... | 0 | 2016-08-25T11:41:54Z | 39,144,684 | <p>You are counting the items in the list, and the proposed one check if it's empty with <code>if not aList</code> this is equals to <code>len(aList) == 0</code>, so both of you use the same logic.</p>
<p>But, you're doing <code>count -= 1</code>, this has no sense since when you use recursion, you pass the list quiti... | 1 | 2016-08-25T11:57:18Z | [
"python",
"python-2.7",
"recursion"
] |
In this short recursive function `list_sum(aList)`, the finish condition is `if not aList: return 0`. I see no logic in why this condition works | 39,144,343 | <p>I am learning the recursive functions. I completed an exercise, but in a different way than proposed.</p>
<p>"Write a recursive function which takes a list argument and returns the sum of its integers."</p>
<pre><code>L = [0, 1, 2, 3, 4] # The sum of elements will be 10
</code></pre>
<p>My solution is:</p>
<pre... | 0 | 2016-08-25T11:41:54Z | 39,144,703 | <p>For understand this function, let's run it step by step :
step 0 :</p>
<pre><code>L=[0,1,2,3,4]
proposed_sum([0,1,2,3,4])
L != []
return l[0] + proposed_sum([1,2,3,4])
</code></pre>
<p>step 1 calcul proposed_sum([1,2,3,4]):</p>
<pre><code>proposed_sum([1,2,3,4])
L != []
return l[0] + sum([2,3,4])
</code></pre>
... | 1 | 2016-08-25T11:58:21Z | [
"python",
"python-2.7",
"recursion"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.