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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Function only prints the correct statement for the last item in the list? | 38,338,969 | <p>So the question asks:</p>
<blockquote>
<p>Write a function <code>is_member()</code> that takes a value (i.e. a number, string, etc) <code>x</code> and a list of values <code>a</code>, and returns <code>True</code> if <code>x</code> is a member of <code>a</code>, <code>False</code> otherwise. (Note that this is ex... | 0 | 2016-07-12T21:12:30Z | 38,339,051 | <pre><code>def is_member(value, list1):
for e in list1:
if e == value:
return 'Yes, the value ' + str(value) + ' is in the list'
return 'No, the value ' + str(value) + ' is not in the list'
</code></pre>
<p>Would work as well as the other proposed answers.</p>
| 2 | 2016-07-12T21:17:59Z | [
"python",
"list",
"iteration"
] |
Function only prints the correct statement for the last item in the list? | 38,338,969 | <p>So the question asks:</p>
<blockquote>
<p>Write a function <code>is_member()</code> that takes a value (i.e. a number, string, etc) <code>x</code> and a list of values <code>a</code>, and returns <code>True</code> if <code>x</code> is a member of <code>a</code>, <code>False</code> otherwise. (Note that this is ex... | 0 | 2016-07-12T21:12:30Z | 38,339,055 | <p>You need to <em>return</em> in the for loop when you get a match or unless <em>value</em> is equal to the last element then you will always get ans set to what is in your else block even when getting a previous match:</p>
<pre><code>def is_member(value, list1):
for e in list1:
if e == value:
... | 2 | 2016-07-12T21:18:42Z | [
"python",
"list",
"iteration"
] |
Function only prints the correct statement for the last item in the list? | 38,338,969 | <p>So the question asks:</p>
<blockquote>
<p>Write a function <code>is_member()</code> that takes a value (i.e. a number, string, etc) <code>x</code> and a list of values <code>a</code>, and returns <code>True</code> if <code>x</code> is a member of <code>a</code>, <code>False</code> otherwise. (Note that this is ex... | 0 | 2016-07-12T21:12:30Z | 38,346,313 | <p>The question you've asked states </p>
<blockquote>
<p>"Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise.</p>
</blockquote>
<pre><code>def is_member(x, a):
for list_item in a:
if list_item == ... | 0 | 2016-07-13T08:24:14Z | [
"python",
"list",
"iteration"
] |
Creating a 3D surface plot with matplotlib in python | 38,339,076 | <p>I am trying to plot a 3D surface but I am having some trouble because the documentation for <code>matplotlib</code> does not appear to be very thorough and is lacking in examples. Anyways the program I have written is to solve the Heat Equation Numerically via Method of Finite Differences. Here is my code:</p>
<pre... | 1 | 2016-07-12T21:20:08Z | 38,339,608 | <p>Use this code (look at the comments):</p>
<pre><code># plot 3d surface
# create a meshgrid of (x,t) points
# T and X are 2-d arrays
T, X = np.meshgrid(t,x)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Use X and T arrays to plot u
# shape of X, T and u must to be the same
# but shape of u is [40,... | 1 | 2016-07-12T22:05:38Z | [
"python",
"matplotlib",
"plot"
] |
Creating a 3D surface plot with matplotlib in python | 38,339,076 | <p>I am trying to plot a 3D surface but I am having some trouble because the documentation for <code>matplotlib</code> does not appear to be very thorough and is lacking in examples. Anyways the program I have written is to solve the Heat Equation Numerically via Method of Finite Differences. Here is my code:</p>
<pre... | 1 | 2016-07-12T21:20:08Z | 38,339,634 | <p>It's helpful to print out the shapes of the variables <code>x</code>, <code>t</code>, and <code>u</code>:</p>
<pre><code>x.shape == (40,)
t.shape == (1600,)
u.shape == (40, 1601)
</code></pre>
<p>So there are two problems here.
The first one is that <code>x</code> and <code>t</code> are 1-dimensional, even though ... | 2 | 2016-07-12T22:07:33Z | [
"python",
"matplotlib",
"plot"
] |
Regex to replace ( ) with [ ] around function arguments | 38,339,116 | <p>So I have this huge math expressions stored in a string that I got out of SymPy, and I'm trying to format it so that I can use it in Mathematica.</p>
<p>I want to change everything that looks like <code>'sin(arg)'</code> to <code>Sin[arg]</code> but I also need to make it work for cosine. <code>arg</code> can be an... | 2 | 2016-07-12T21:23:31Z | 38,339,191 | <pre><code>def replacer(m):
return m.group(1).capitalize()+"["+m.group(2)+"]"
re.sub("([a-z]+)\(([a-zA-Z0-9 ]*)\)",replacer,"cos(Theta1)")
</code></pre>
<p>I guess ... maybe ...</p>
| 3 | 2016-07-12T21:29:06Z | [
"python",
"regex"
] |
Regex to replace ( ) with [ ] around function arguments | 38,339,116 | <p>So I have this huge math expressions stored in a string that I got out of SymPy, and I'm trying to format it so that I can use it in Mathematica.</p>
<p>I want to change everything that looks like <code>'sin(arg)'</code> to <code>Sin[arg]</code> but I also need to make it work for cosine. <code>arg</code> can be an... | 2 | 2016-07-12T21:23:31Z | 38,339,237 | <p>Given that your only arguments can be <code>theta1</code> through <code>theta5</code>, you can simply do the replacement</p>
<pre><code>sin\((theta[1-5])\)
</code></pre>
<p>with</p>
<pre><code>Sin[\1]
</code></pre>
<p>and</p>
<pre><code>cos\((theta[1-5])\)
</code></pre>
<p>with</p>
<pre><code>Cos[\1]
</code><... | 1 | 2016-07-12T21:32:35Z | [
"python",
"regex"
] |
Regex to replace ( ) with [ ] around function arguments | 38,339,116 | <p>So I have this huge math expressions stored in a string that I got out of SymPy, and I'm trying to format it so that I can use it in Mathematica.</p>
<p>I want to change everything that looks like <code>'sin(arg)'</code> to <code>Sin[arg]</code> but I also need to make it work for cosine. <code>arg</code> can be an... | 2 | 2016-07-12T21:23:31Z | 38,339,242 | <pre><code>import re
if __name__ == '__main__':
test = 'sin (theta1)'
regex = (
r'(sin|cos)' # group # 1: sin or cos
r'\s*' # zero or more spaces
r'\(' # opening bracket
r'\s*' # zero or more spaces
r'(theta[1-5])' # group #2 with your... | 1 | 2016-07-12T21:32:59Z | [
"python",
"regex"
] |
Regex to replace ( ) with [ ] around function arguments | 38,339,116 | <p>So I have this huge math expressions stored in a string that I got out of SymPy, and I'm trying to format it so that I can use it in Mathematica.</p>
<p>I want to change everything that looks like <code>'sin(arg)'</code> to <code>Sin[arg]</code> but I also need to make it work for cosine. <code>arg</code> can be an... | 2 | 2016-07-12T21:23:31Z | 38,339,279 | <p>you can specify parts of the pattern that will not be consumed (replaced) with look behinds <code>(?<=...)</code> and lookaheads <code>(?=...)</code>:</p>
<pre><code>S = "cos(theta1)"
S = S.replace("cos","Cos").replace("sin","Sin")
S = re.sub(r"(?<=Sin|Cos)\((?=theta1|theta2|theta3|theta4|theta5)", "[", S)
... | 0 | 2016-07-12T21:36:24Z | [
"python",
"regex"
] |
Checking if index in list exists | 38,339,204 | <p><em>I would like to note that I'm using Discord.py and some of it's included libs.</em></p>
<p>So I'm trying to check if an index in a list exists but I keep getting the <code>ValueError</code> saying that the index does not exist in my list.</p>
<p>Here's my code:</p>
<pre><code>def deal_card(self):
U = ... | 1 | 2016-07-12T21:30:11Z | 38,339,250 | <p><code>list.index()</code> should be used for finding the index of a list's member. To check <em>whether an item <strong>is</strong> in a list</em>, simply use <code>in</code>: </p>
<pre><code>if not U:
# do stuff
elif randCard in U:
# do other stuff
</code></pre>
| 4 | 2016-07-12T21:33:33Z | [
"python"
] |
Checking if index in list exists | 38,339,204 | <p><em>I would like to note that I'm using Discord.py and some of it's included libs.</em></p>
<p>So I'm trying to check if an index in a list exists but I keep getting the <code>ValueError</code> saying that the index does not exist in my list.</p>
<p>Here's my code:</p>
<pre><code>def deal_card(self):
U = ... | 1 | 2016-07-12T21:30:11Z | 38,339,255 | <p>You don't need to use the index function:</p>
<p><code>elif randCard in U:</code></p>
| 1 | 2016-07-12T21:34:03Z | [
"python"
] |
Checking if index in list exists | 38,339,204 | <p><em>I would like to note that I'm using Discord.py and some of it's included libs.</em></p>
<p>So I'm trying to check if an index in a list exists but I keep getting the <code>ValueError</code> saying that the index does not exist in my list.</p>
<p>Here's my code:</p>
<pre><code>def deal_card(self):
U = ... | 1 | 2016-07-12T21:30:11Z | 38,339,302 | <p>This is probably a terrible way to deal your cards, because then you have the cards both in your discard pile <em>and</em> in your deck.</p>
<p>Why not just move the cards around?</p>
<pre><code>import random
cards = ['H{}'.format(val) for val in range(1, 11)]
print(cards)
discard_pile = []
while cards:
rand... | 2 | 2016-07-12T21:38:44Z | [
"python"
] |
Checking if index in list exists | 38,339,204 | <p><em>I would like to note that I'm using Discord.py and some of it's included libs.</em></p>
<p>So I'm trying to check if an index in a list exists but I keep getting the <code>ValueError</code> saying that the index does not exist in my list.</p>
<p>Here's my code:</p>
<pre><code>def deal_card(self):
U = ... | 1 | 2016-07-12T21:30:11Z | 38,339,374 | <p>If you would still like to use the <code>.index</code> function for some reason and not follow the above suggestions you could use the <code>try</code> statement as follows:</p>
<pre><code>try:
c = U.index(randCard)
randCard = randchoice(list(self.cards))
U.append(randCard)
except ValueError:
U.appe... | 1 | 2016-07-12T21:45:39Z | [
"python"
] |
How to distinguish known local parameters from global parameters in lmfit? | 38,339,241 | <p>I am working with the lmfit python package <a href="https://lmfit.github.io/lmfit-py/" rel="nofollow">https://lmfit.github.io/lmfit-py/</a> for fitting data to a specified non-linear function within certain permitted ranges of variation for some parameters (which is mainly why I found lmfit attractive).</p>
<p>Gene... | 0 | 2016-07-12T21:32:56Z | 38,341,968 | <p>It's a little hard to get all the details without an actual example code, but I can try to address a few of the topics you raise. </p>
<p>First, <code>fcn2min()</code> needs to be passed the <code>y_data</code> (and <code>x_data</code> for that matter) arrays because from the point of view of <code>minimize()</cod... | 0 | 2016-07-13T03:01:19Z | [
"python",
"numpy",
"spyder",
"lmfit"
] |
Pivot pandas dataframe with dates and showing counts per date | 38,339,307 | <p>I have the following pandas DataFrame: (currently ~500 rows):</p>
<pre>
merged_verified =
Last Verified Verified by
0 2016-07-11 John Doe
1 2016-07-11 John Doe
2 2016-07-12 John Doe
3 2016-07-11 Mary Smith
4 2016-07-12 Mary Smith
</pre>
<p>I am attempting to <cod... | 2 | 2016-07-12T21:39:08Z | 38,339,338 | <p>You can add parameter <code>columns</code> and aggragate by <code>len</code>:</p>
<pre><code>merged_verified = merged_verified.pivot_table(index=['Verified by'],
columns=['Last Verified'],
values=['Last Verified'],
... | 3 | 2016-07-12T21:42:25Z | [
"python",
"numpy",
"pandas"
] |
Pivot pandas dataframe with dates and showing counts per date | 38,339,307 | <p>I have the following pandas DataFrame: (currently ~500 rows):</p>
<pre>
merged_verified =
Last Verified Verified by
0 2016-07-11 John Doe
1 2016-07-11 John Doe
2 2016-07-12 John Doe
3 2016-07-11 Mary Smith
4 2016-07-12 Mary Smith
</pre>
<p>I am attempting to <cod... | 2 | 2016-07-12T21:39:08Z | 38,339,347 | <p>Use <code>groupby</code>, <code>value_counts</code>, and <code>unstack</code>:</p>
<pre><code>merged_verified.groupby('Last Verified')['Verified by'].value_counts().unstack(0)
</code></pre>
<p><a href="http://i.stack.imgur.com/LikUO.png" rel="nofollow"><img src="http://i.stack.imgur.com/LikUO.png" alt="enter image... | 2 | 2016-07-12T21:43:17Z | [
"python",
"numpy",
"pandas"
] |
ASCII encode error while writing columns in a file | 38,339,355 | <pre><code>rows = zip(recallid, recalldate, recallnums, name, model, ptype, categoryid, numberofunits)
with open('WIP.csv'.encode('utf-8'), 'wb') as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row) #line 46
</code></pre>
<p>This program gives me an error as - "UnicodeEncodeErro... | 0 | 2016-07-12T21:43:53Z | 38,339,502 | <p>You need to encode the data, not the filename:</p>
<pre><code>with open('WIP.csv', 'w') as f:
writer = csv.writer(f)
for row in rows:
writer.writerow([s.encode("utf-8") for s in row])
</code></pre>
<p>If some of your data are not strings:</p>
<pre><code> writer.writerow([s.encode("utf-8") if isins... | 0 | 2016-07-12T21:57:19Z | [
"python",
"python-2.7"
] |
Pyexcel changing a cell value | 38,339,369 | <p>So I was using <code>openpyxl</code> for all my Excel projects, but now I have to work with <code>.xls</code> files, so I was forced to change library. I've chosen <code>pyexcel</code> cuz it seemed to be fairly easy and well documented. So I've gone through hell with creating hundreds of variables, cuz there is no ... | 0 | 2016-07-12T21:45:08Z | 38,498,656 | <p>I didn't get it, wouldn't it be the most simple thing?</p>
<pre><code>column_name = 'Quantity'
value_to_find = 12
sheets1 = pe.get_book(file_name='Sheet1.xls')
sheets1[0].name_columns_by_row(0)
row = sheets1[0].column[column_name].index(value_to_find)
sheets2 = pe.get_book(file_name='Sheet2.xls')
sheets2[0].name_c... | 1 | 2016-07-21T08:15:11Z | [
"python",
"excel",
"pyexcel"
] |
Pyexcel changing a cell value | 38,339,369 | <p>So I was using <code>openpyxl</code> for all my Excel projects, but now I have to work with <code>.xls</code> files, so I was forced to change library. I've chosen <code>pyexcel</code> cuz it seemed to be fairly easy and well documented. So I've gone through hell with creating hundreds of variables, cuz there is no ... | 0 | 2016-07-12T21:45:08Z | 38,516,329 | <p>Excel uses 2 sets of references to a cell. Cell name ("A1") and cell vector (Row, Column).</p>
<p>The <a href="https://pythonhosted.org/pyexcel/tutorial.html" rel="nofollow">PyExcel documentation tutorial</a> states it supports both methods. caiohamamura's method tries to build the cell name - you don't need to if ... | 0 | 2016-07-22T00:20:11Z | [
"python",
"excel",
"pyexcel"
] |
how does python interact with linux? | 38,339,387 | <p>I use <code>commands.getstatusoutput('some_terminal_command')</code> to store output of some terminal command in a variable. But am curious to know how does python actually get the output from the terminal? does python has some part of 'Shell' or something? </p>
| 1 | 2016-07-12T21:46:48Z | 38,339,469 | <p>Ultimately, your call to run a command uses the <a href="https://en.wikipedia.org/wiki/Fork%E2%80%93exec" rel="nofollow">fork and exec</a> system calls. These are functions provided by the OS and exposed to most programming languages, which allows the language to start a new process and get its output. It's one of t... | 5 | 2016-07-12T21:53:46Z | [
"python",
"linux",
"shell",
"ubuntu",
"terminal"
] |
how does python interact with linux? | 38,339,387 | <p>I use <code>commands.getstatusoutput('some_terminal_command')</code> to store output of some terminal command in a variable. But am curious to know how does python actually get the output from the terminal? does python has some part of 'Shell' or something? </p>
| 1 | 2016-07-12T21:46:48Z | 38,339,569 | <p>If you <a href="https://github.com/python/cpython/blob/2.7/Lib/commands.py#L56" rel="nofollow">read the source</a> You'll see that it uses the <code>os.popen</code> call. What's intriguing, however, is that <code>os.popen</code> isn't defined in the <code>os.py</code> module that I can find.</p>
<p>Eventually and w... | 1 | 2016-07-12T22:02:51Z | [
"python",
"linux",
"shell",
"ubuntu",
"terminal"
] |
Python RegEx Replace - Inverting the Search removing too much | 38,339,417 | <p>Working in Python 2.7. I'm attempting to remove from a string all things not databases and tablename combinations. I'm using regex for this, and unintentionally removing all the whitespace (which I need to keep to separate the values)</p>
<pre><code>s = "replace view dw1.tbl1_st as select dw2.tbl1_st.col1, dw2.tb... | 0 | 2016-07-12T21:49:15Z | 38,339,710 | <p>One option, which will work if you know the structure of your string and it is fairly regular, is instead of useing <code>.</code> to match everything, using negation to match anything BUT a space or comma:</p>
<pre><code>>>> replaced = re.sub(r'((?!\w+\.\w+)[^, ])', '', s)
>>> replaced
' dw1 d... | 0 | 2016-07-12T22:13:12Z | [
"python",
"regex-negation"
] |
Pandas: write dataframe to json | 38,339,523 | <p>I have dataframe:</p>
<pre><code> date id
0 12-12-2015 123
1 13-12-2015 123
2 15-12-2015 123
3 16-12-2015 123
4 18-12-2015 123
5 12-12-2015 456
6 13-12-2015 456
7 15-12-2015 456
</code></pre>
<p>I need to count <code>date</code> to <code>id</code>
I try <code>df.groupby('id')['date'].coun... | 1 | 2016-07-12T21:58:41Z | 38,339,603 | <p>First use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a>:</p>
<pre><code>df['date'] = pd.to_datetime(df.date)
df.set_index('date', inplace=True)
df = df.groupby('id').resample('D').size().reset_index(name='val')
print (df)
... | 1 | 2016-07-12T22:05:06Z | [
"python",
"json",
"pandas",
"dataframe",
"resampling"
] |
Mock patch not replacing function correctly | 38,339,560 | <p>I have a tastypie REST API resource, let's say called <code>Resource</code>, that imports and uses a function called <code>get_token</code> from <code>libs.utils</code> in its <code>obj_get</code> method.</p>
<p>So to test this resource, in my test class I have created a test like what follows:</p>
<pre><code>mock... | 0 | 2016-07-12T22:02:01Z | 38,339,988 | <p>Take a look at known <a href="http://alexmarandon.com/articles/python_mock_gotchas/" rel="nofollow">gotchas</a>. It might be that you're trying to patch wrong place... </p>
| 0 | 2016-07-12T22:41:22Z | [
"python",
"django",
"unit-testing",
"mocking",
"django-testing"
] |
Mock patch not replacing function correctly | 38,339,560 | <p>I have a tastypie REST API resource, let's say called <code>Resource</code>, that imports and uses a function called <code>get_token</code> from <code>libs.utils</code> in its <code>obj_get</code> method.</p>
<p>So to test this resource, in my test class I have created a test like what follows:</p>
<pre><code>mock... | 0 | 2016-07-12T22:02:01Z | 38,361,921 | <p>We couldn't figure out the exact solution, but a workaround was that since most of the logic in the <code>obj_get</code> method was handled by another function <code>api_call()</code>, we mocked the call to the <code>api_call</code> function instead.</p>
<p>So the issue appeared to be some import issue as <code>api... | 0 | 2016-07-13T21:22:36Z | [
"python",
"django",
"unit-testing",
"mocking",
"django-testing"
] |
Regular expressions moving substrings in front of specific character | 38,339,681 | <p>Hi I am trying to move the apostrophes in this string using regular expressions if possible.</p>
<p>string = " R8 R16 R8 E'4 G'4. G16 R8. C2 R16 A4 D4 R2 D'16 B8 R16 C4 R8. E'8 C8 C'16 C'4 "</p>
<p>so the output would be like this</p>
<p>" R8 R16 R8 E4' G4.' G16 R8. C2 R16 A4 D4 R2... | 0 | 2016-07-12T22:11:04Z | 38,339,711 | <p>Read this as "Replace an apostrophe followed by one or more non-space characters with those non-space characters and then the apostrophe."</p>
<pre><code>>>> re.sub(r"'(\S+)", r"\1'", " R8 R16 R8 E'4 G'4. G16 R8. C2 R16 A4 D4 R2 D'16 B8 R16 C4 R8. E'8 C8 C'16 C'4 ")
" R8 R16 R8 E4' G4.' G16 R8. C2 R16 A4 D... | 0 | 2016-07-12T22:13:22Z | [
"python",
"regex",
"string"
] |
Missing /bin folder from MinGW-W64 installation | 38,339,722 | <p>Right now I am working through <a href="https://www.ibm.com/developerworks/community/blogs/jfp/entry/Installing_XGBoost_For_Anaconda_on_Windows?lang=en" rel="nofollow">this walk-through</a> on how to get the xgboost package for python. I'm running on Windows 10. </p>
<p>I've just added <code>C:\Program Files\mingw-... | -1 | 2016-07-12T22:14:00Z | 38,789,559 | <p>I've tried to do the same walk-through but with the <a href="http://tdm-gcc.tdragon.net/download" rel="nofollow">tdm-gcc as mingw</a> and it worked</p>
<p>I suggest you look at the more general answer of <a href="http://stackoverflow.com/a/35119904/2269733">Disco4Ever here, on stackoverflow</a> on how to install XG... | 1 | 2016-08-05T12:43:54Z | [
"python",
"windows",
"git",
"xgboost"
] |
Plot data returned from groupby function in Pandas using Matplotlib | 38,339,753 | <p>So I am using the groupby function in pandas to get mean of two columns using conditions based on two other columns. I am having trouble creating the matplotlib plots</p>
<p>An example table is</p>
<pre><code>data_temp = pd.DataFrame([
[3, 16, 0, 0, 10],
[3, 20, 0, 1, 11],
[3, 25, 0, 2, 11]... | 2 | 2016-07-12T22:17:22Z | 38,340,436 | <p>How about something like this:</p>
<pre><code>import matplotlib.pyplot as pp
data = A.groupby(['D','A'])['E','B'].mean().reset_index()
#For the plot of B vs A
fig, ax = pp.subplots()
for value, groups in data.groupby('D'):
ax.plot(group.A,group.B)
pp.show()
</code></pre>
| 0 | 2016-07-12T23:35:08Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
Plot data returned from groupby function in Pandas using Matplotlib | 38,339,753 | <p>So I am using the groupby function in pandas to get mean of two columns using conditions based on two other columns. I am having trouble creating the matplotlib plots</p>
<p>An example table is</p>
<pre><code>data_temp = pd.DataFrame([
[3, 16, 0, 0, 10],
[3, 20, 0, 1, 11],
[3, 25, 0, 2, 11]... | 2 | 2016-07-12T22:17:22Z | 38,340,438 | <p>Use <code>unstack</code> on result:</p>
<pre><code>result2 = result.unstack()
reuslt2
</code></pre>
<p><a href="http://i.stack.imgur.com/2lJ5w.png" rel="nofollow"><img src="http://i.stack.imgur.com/2lJ5w.png" alt="enter image description here"></a></p>
<p>Then <code>B.plot()</code></p>
<pre><code>result2.B.plot(... | 2 | 2016-07-12T23:35:21Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
linking user profile with other class in django (in postgresql db) | 38,339,815 | <p>I am pretty new to django and I am trying to get 2 classes to work together in the database. More precisely, I want users to be able to create devices, and then link the user and the device in the database (I'm using postgresql database)</p>
<p>models.py</p>
<pre><code>class Device(models.Model):
deviceNb = mo... | 0 | 2016-07-12T22:23:36Z | 38,340,983 | <p>When you call 'save' in a modelform then the model is saved in database and returned.
But in your code you create and instance of UserProfileForm without a previous created device.
Here one way to solve the problem</p>
<pre><code>...
if request.method == 'POST':
device_form = DeviceForm(request.POST, instance =... | 1 | 2016-07-13T00:47:21Z | [
"python",
"django",
"postgresql"
] |
linking user profile with other class in django (in postgresql db) | 38,339,815 | <p>I am pretty new to django and I am trying to get 2 classes to work together in the database. More precisely, I want users to be able to create devices, and then link the user and the device in the database (I'm using postgresql database)</p>
<p>models.py</p>
<pre><code>class Device(models.Model):
deviceNb = mo... | 0 | 2016-07-12T22:23:36Z | 38,356,947 | <p>I used wilkus solution, but with a small twist, </p>
<p>added the following lines</p>
<pre><code>if form.is_valid():
prof = form.save(commit=False)
prof.device_id = device
prof.save()
</code></pre>
<p>This allows you to return an object from the form.save(commit=false) without sending it to the ... | 1 | 2016-07-13T16:19:28Z | [
"python",
"django",
"postgresql"
] |
NumPy - Dot Product along 3rd dimension without copying | 38,339,876 | <p>I am trying to vectorize a function that takes as its input a 3-Component vector "x" and a 3x3 "matrix" and produces the scalar</p>
<pre><code>def myfunc(x, matrix):
return np.dot(x, np.dot(matrix, x))
</code></pre>
<p>However this needs to be called "n" times, and the vector x has different components each ti... | 1 | 2016-07-12T22:29:19Z | 38,339,950 | <p>Let <code>x</code> be the 3xN array and <code>y</code> be the 3x3 array. You're looking for</p>
<pre><code>z = numpy.einsum('ji,jk,ki->i', x, y, x)
</code></pre>
<p>You also could have built that 3x3xN array you were talking about as a view of <code>y</code> to avoid copying, but it isn't necessary.</p>
| 2 | 2016-07-12T22:37:15Z | [
"python",
"numpy",
"vectorization"
] |
Prioritizing objects using valued filters (Django) | 38,340,083 | <p>I have an interesting programming question which I'm sure has many very interesting solutions and I'm hoping someone has some insight into a good direction I can take.</p>
<p>I'm working in Django and I have a QuerySet of objects and a set of filters. I want to find a subset of objects that survive all the filters,... | 2 | 2016-07-12T22:52:20Z | 38,357,926 | <pre><code>from django.db.models import CharField, IntegerField, Case, When, Q
from django.db.models.functions import Length
# You can register function as a transform
CharField.register_lookup(Length, 'length')
filters = [
(Q(name__startswith='A'), 10),
(Q(name__endswith='E'), 5),
(Q(name__length=6), 3),... | 2 | 2016-07-13T17:14:31Z | [
"python",
"django",
"postgresql",
"filter",
"weight"
] |
Why in scapy packet.payload.proto == 17 is UDP and packet.payload.proto ==6 TCP? | 38,340,205 | <p>I saw this code in github.
I dont uderstand why packet.payload.proto == 17 is UDP and packet.payload.proto ==6 TCP.</p>
<p>packets = scapy.all.rdpcap('data/dns.cap')</p>
<p>for packet in packets:
print('----------')
print('src_mac: {0}'.format(packet.src))
print('dst_mac: {0}'.format(packet.dst))</p>... | 0 | 2016-07-12T23:06:52Z | 38,340,257 | <p>Because <a href="http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml" rel="nofollow">the IANA says so</a>.</p>
<blockquote>
<pre><code> ...
6 TCP Transmission Control [RFC793]
...
17 UDP User Datagram [RFC768][Jon_Postel]
...
</code></pre>
</blockquote>
| 2 | 2016-07-12T23:12:26Z | [
"python",
"scapy"
] |
Why in scapy packet.payload.proto == 17 is UDP and packet.payload.proto ==6 TCP? | 38,340,205 | <p>I saw this code in github.
I dont uderstand why packet.payload.proto == 17 is UDP and packet.payload.proto ==6 TCP.</p>
<p>packets = scapy.all.rdpcap('data/dns.cap')</p>
<p>for packet in packets:
print('----------')
print('src_mac: {0}'.format(packet.src))
print('dst_mac: {0}'.format(packet.dst))</p>... | 0 | 2016-07-12T23:06:52Z | 38,401,593 | <p>The answer provided by Ignacio is correct. The RFCs and IANA designate those values. </p>
<p>As for what a payload is, that is relative to what packet (PDU more specifically) layer you are talking about.</p>
<p>Take the following example:</p>
<pre><code>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++... | 1 | 2016-07-15T17:02:32Z | [
"python",
"scapy"
] |
Handle invalid arguments with argparse in Python | 38,340,252 | <p>I am using <a href="https://docs.python.org/2/library/argparse.html" rel="nofollow"><code>argparse</code></a> to parse command line arguments and by default on receiving invalid arguments it prints help message and exit. Is it possible to customize the behavior of argparse when it receives invalid arguments? </p>
<... | 2 | 2016-07-12T23:11:52Z | 38,340,296 | <p>You might want to use <a href="https://docs.python.org/dev/library/argparse.html#partial-parsing" rel="nofollow"><code>parse_known_args</code></a> and then take a look at the second item in the tuple to see what arguments were not understood.</p>
<p>That said, I believe this will only help with <em>extra</em> argum... | 3 | 2016-07-12T23:18:45Z | [
"python",
"argparse"
] |
Handle invalid arguments with argparse in Python | 38,340,252 | <p>I am using <a href="https://docs.python.org/2/library/argparse.html" rel="nofollow"><code>argparse</code></a> to parse command line arguments and by default on receiving invalid arguments it prints help message and exit. Is it possible to customize the behavior of argparse when it receives invalid arguments? </p>
<... | 2 | 2016-07-12T23:11:52Z | 38,340,458 | <p>You can try subclassing <code>argparse.ArgumentParser(</code>) and overriding the <code>error</code> method. </p>
<p>From the argparse source:</p>
<pre><code>def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
I... | 1 | 2016-07-12T23:37:54Z | [
"python",
"argparse"
] |
Handle invalid arguments with argparse in Python | 38,340,252 | <p>I am using <a href="https://docs.python.org/2/library/argparse.html" rel="nofollow"><code>argparse</code></a> to parse command line arguments and by default on receiving invalid arguments it prints help message and exit. Is it possible to customize the behavior of argparse when it receives invalid arguments? </p>
<... | 2 | 2016-07-12T23:11:52Z | 38,340,629 | <p>Some previous questions:</p>
<p><a href="http://stackoverflow.com/questions/5943249/python-argparse-and-controlling-overriding-the-exit-status-code">Python argparse and controlling/overriding the exit status code</a></p>
<p><a href="http://stackoverflow.com/questions/14728376/i-want-python-argparse-to-throw-an-exc... | 1 | 2016-07-12T23:59:29Z | [
"python",
"argparse"
] |
Can't connect to MySQL server(Connection refused) , trying to install connection between Django and MySQL | 38,340,262 | <p>I am trying to install connection between MySQL and Django, as far as the old method is only applicable to 2.x python, I use Python 3.4 and mysql.connector.django module <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html" rel="nofollow">https://dev.mysql.com/doc/connector-pyt... | 0 | 2016-07-12T23:13:03Z | 38,340,275 | <p>The default port for MySQL is <code>3306</code>.</p>
<p>Your Django app is running on port <code>8000</code>, change that value in your DB config.</p>
<p>It should look like this:</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'mysql.connector.django',
'NAME': 'closerdb',
'HOSTNAM... | 2 | 2016-07-12T23:14:42Z | [
"python",
"mysql",
"django"
] |
Celery doesn't recognize environment variable BROKER_URL | 38,340,266 | <p>currently I am trying to run a Celery task within a pyramid file using pycelery with a Redis url which itself is an environment variable, so I try declaring it as follows<br>
<code>[celery]</code><br>
<code>BROKER_URL = ${REDIS_URL}</code></p>
<p>but when I run it I get the error
<a href="http://i.stack.imgur.c... | 1 | 2016-07-12T23:13:24Z | 38,414,128 | <p>Unfortunately INI setting parsing is not harmonized across Python applications and libaries. The environment variable expansion usually happens on library level, not on INI parsing level.</p>
<p>Thus, <code>pyramid_redis</code> supports environment variables. But unless <code>pyramid_celery</code> adds explicit env... | 1 | 2016-07-16T18:09:51Z | [
"python",
"celery",
"pyramid"
] |
Python Selenium Message: Unable to locate element | 38,340,278 | <p>Im developing a web scraper in Python which only take user and password from a mysql database and then it goes to a web page and fill out the form to login, until here everything works fine, the problem is when I have more than 1 user in my database, it logs in and fully complete the script but when it passes to the... | 0 | 2016-07-12T23:15:32Z | 38,340,517 | <p>It looks like the name of the button you are trying to click is not called "submit", so there seems to be no element with that name so it fails. Can you find the name using the browser dev tools? </p>
| -1 | 2016-07-12T23:45:29Z | [
"python",
"forms",
"web",
"web-scraping",
"screen-scraping"
] |
Getting the filename using python Watchdog | 38,340,362 | <p>I am trying to get the name of a file that changes periodically.
I am using watchdog to do this. </p>
<pre><code>import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
timestr = time.strftime("%Y.%m.%d-%H.%M.%S")
class MyHandler(FileSystemEventHandler):
def on_... | 0 | 2016-07-12T23:26:21Z | 38,340,961 | <p>It looks like the event object that is sent to your handler includes the information that you seek:
<a href="http://pythonhosted.org/watchdog/api.html#watchdog.events.FileSystemEvent" rel="nofollow">http://pythonhosted.org/watchdog/api.html#watchdog.events.FileSystemEvent</a></p>
<p>Use the <code>src_path</code> pr... | 0 | 2016-07-13T00:44:59Z | [
"python",
"variables",
"filesystems",
"output",
"watchdog"
] |
Java AES Encryption, Python Decryption not working | 38,340,451 | <p>I have tried multiple ways to do this, for three days now and many hours. I have gotten NO WHERE. I am using Java to encrypt certain data using AES/CBC/PKCS7Padding, and trying to decrypt using the same in Python but it just won't work. I am using this Python aes.py library <a href="http://anh.cs.luc.edu/331/code/ae... | 0 | 2016-07-12T23:37:15Z | 38,360,910 | <p>The problem was that for some reason Java was padding the first byte of the resulting String. Why? I don't have the slightest clue but after stripping it off in Python all was well. Both the PyCrypto code and the Aes.py code work fine.</p>
| -1 | 2016-07-13T20:13:19Z | [
"java",
"python",
"cryptography"
] |
Add constraints to scipy.optimize.curve_fit? | 38,340,477 | <p>I have the option to add bounds to sio.curve_fit. Is there a way to expand upon this bounds feature that involves a function of the parameters? In other words, say I have an arbitrary function with two or more unknown constants. And then let's also say that I know the sum of all of these constants is less than 10. I... | 3 | 2016-07-12T23:39:59Z | 38,348,115 | <p>curve_fit and least_squares only accept box constraints. In scipy.optimize, SLSQP can deal with more complicated constraints.
For curve fitting specifically, you can have a look at lmfit package.</p>
| 0 | 2016-07-13T09:46:29Z | [
"python",
"numpy",
"scipy",
"curve-fitting"
] |
Add constraints to scipy.optimize.curve_fit? | 38,340,477 | <p>I have the option to add bounds to sio.curve_fit. Is there a way to expand upon this bounds feature that involves a function of the parameters? In other words, say I have an arbitrary function with two or more unknown constants. And then let's also say that I know the sum of all of these constants is less than 10. I... | 3 | 2016-07-12T23:39:59Z | 38,351,262 | <p>With lmfit, you would define 4 parameters (<code>a</code>, <code>b</code>, <code>c</code>, and <code>delta</code>). <code>a</code> and <code>b</code> can vary freely. <code>delta</code> is allowed to vary, but has a maximum value of 10 to represent the inequality. <code>c</code> would be constrained to be <code>del... | 1 | 2016-07-13T12:04:21Z | [
"python",
"numpy",
"scipy",
"curve-fitting"
] |
Listen for push notification on url - Odoo | 38,340,559 | <p>Is there any way of listening for a POST on a certain url within a custom module in Odoo?</p>
<p>Or would this have to be done with nginx redirecting the request to another python script? </p>
| 0 | 2016-07-12T23:51:01Z | 38,346,342 | <p>Sure you can</p>
<pre><code>from openerp import http
@http.route('/home', auth="public", website=True)
def cart(self, **kwargs):
return 'This is the index page'
</code></pre>
<p>it's pretty straight forward, we define a url route that points to <code>/home</code> and then a python method that returns ... | 1 | 2016-07-13T08:25:44Z | [
"python",
"post",
"openerp"
] |
Python3: TypeError: 'NoneType' object is not subscriptable | 38,340,567 | <p>On this line</p>
<pre><code>...
print('1','0')['-'in y or(int(y)-int(x[z]))*d.find('I')<=0])]
...
</code></pre>
| -2 | 2016-07-12T23:52:14Z | 38,340,763 | <p>if you're in python3 put your code in brackets</p>
<pre><code>print( ('1','0')['-'in y or(int(y)-int(x[z]))*d.find('I')<=0])] )
</code></pre>
| 1 | 2016-07-13T00:16:02Z | [
"python",
"python-3.x"
] |
Python heapq vs sorted speed for pre-sorted lists | 38,340,588 | <p>I have a reasonably large number n=10000 of sorted lists of length k=100 each. Since merging two sorted lists takes linear time, I would imagine its cheaper to recursively merge the sorted lists of length O(nk) with <code>heapq.merge()</code> in a tree of depth log(n) than to sort the entire thing at once with <code... | 2 | 2016-07-12T23:55:13Z | 38,340,655 | <p><code>sorted</code> uses an <a href="https://en.wikipedia.org/wiki/Timsort" rel="nofollow">adaptive mergesort</a> that detects sorted runs and merges them efficiently, so it gets to take advantage of all the same structure in the input that <code>heapq.merge</code> gets to use. Also, <code>sorted</code> has a really... | 2 | 2016-07-13T00:02:47Z | [
"python",
"list",
"sorting",
"merge"
] |
Python heapq vs sorted speed for pre-sorted lists | 38,340,588 | <p>I have a reasonably large number n=10000 of sorted lists of length k=100 each. Since merging two sorted lists takes linear time, I would imagine its cheaper to recursively merge the sorted lists of length O(nk) with <code>heapq.merge()</code> in a tree of depth log(n) than to sort the entire thing at once with <code... | 2 | 2016-07-12T23:55:13Z | 38,340,755 | <p>CPython's <code>list.sort()</code> uses an adaptive merge sort, which identifies natural runs in the input, and then merges them "intelligently". It's very effective at exploiting many kinds of pre-existing order. For example, try sorting <code>range(N)*2</code> (in Python 2) for increasing values of <code>N</code... | 3 | 2016-07-13T00:15:13Z | [
"python",
"list",
"sorting",
"merge"
] |
Counting no. of characters between headers in python | 38,340,636 | <p>I have the following dataset, my code below will identify each line with the word 'Query_' search for an '*' and print the letters under it until the next line with 'Query_' </p>
<pre><code>Query_10 206 IVVTGPHKFNRCPLKKLAQSFTMPTSTFVDI*GLNFDITEQHFVKEKP**SSEEAQFFAK 385
010718494 193 LLVTGPLVVNRVPLRRAHQKFV... | 0 | 2016-07-13T00:00:41Z | 38,340,822 | <p>Break it down into steps</p>
<p>First find all the lines with headers, and mark whether they contain asterisks:</p>
<pre><code>headers = [[i,"*" in l.split()[2]] for i,l in enumerate(lines)
if l.startswith("Query_")]
</code></pre>
<p>So now you have a list of lists, each containing two values</p>
<ul... | 1 | 2016-07-13T00:24:50Z | [
"python"
] |
How to return the probability of each classified instance? | 38,340,663 | <p>Let's say that I already fitted <a href="http://scikit-learn.org/stable/modules/sgd.html#sgd" rel="nofollow">scikit's SGDC</a>, from the documentation I read that <code>predict_proba()</code> function return a vector of probability estimates, Thus I did the follwing:</p>
<pre><code>In:
proba = clf.predict_proba(X_t... | 0 | 2016-07-13T00:04:01Z | 38,340,794 | <p>I guess 39 is the number of different classes a sample could belong to.As you have done predict_proba. Its going to give you a probability of belonging to each particular class.</p>
<p><strong>There is never going to be a single probability associated with each sample.</strong></p>
<p>So, the error metric generall... | 0 | 2016-07-13T00:21:08Z | [
"python",
"python-3.x",
"numpy",
"machine-learning",
"scikit-learn"
] |
How to return the probability of each classified instance? | 38,340,663 | <p>Let's say that I already fitted <a href="http://scikit-learn.org/stable/modules/sgd.html#sgd" rel="nofollow">scikit's SGDC</a>, from the documentation I read that <code>predict_proba()</code> function return a vector of probability estimates, Thus I did the follwing:</p>
<pre><code>In:
proba = clf.predict_proba(X_t... | 0 | 2016-07-13T00:04:01Z | 38,346,706 | <p><code>predict_proba</code> returns a vector of form P(y=y_i|x) for each y_i (class). Consequently, you can extract many measures from it. For example, if you are asking "how probable is my model's current classification" (thus your model's certainty in its own prediction) all you have to do is to index this array ro... | 1 | 2016-07-13T08:42:24Z | [
"python",
"python-3.x",
"numpy",
"machine-learning",
"scikit-learn"
] |
Pip install python-tds error code 1 | 38,340,684 | <p>I am trying to install python-tds and I cannot figure out where to go from here. I have very limited experience with python so any help would be much appreciated.</p>
<p><img src="http://i.stack.imgur.com/ZdIAx.png" /></p>
| 0 | 2016-07-13T00:06:40Z | 38,340,739 | <p>You are trying to install a package that will need to write files under system directories and your [current] user does not have enough privileges to do so:</p>
<pre><code>error: could not create '/Library/Python/2.7/site-packages/pytds': Permission denied
</code></pre>
<p>You need to install it as superuser:</p>
... | 0 | 2016-07-13T00:13:13Z | [
"python",
"osx",
"pip"
] |
Trouble with progressbar in tkinter | 38,340,695 | <p>This is my code</p>
<pre><code>janela_barra=Toplevel()
janela_barra.title("Processando...")
janela_barra["bg"]="light grey"
janela_barra.minsize(width=400, height=80)
janela_barra.maxsize(width=400, height=80)
comprimento = janela_barra.winfo_screenwidth()
altura = janela_barra.winfo_screenheight()
x = (comprimento... | 0 | 2016-07-13T00:08:13Z | 38,375,642 | <p>Just add <code>sleep</code> (from module <code>time</code>) in your loop, you will see the progression. Here is an example:</p>
<pre><code>from tkinter import Tk, Button, Toplevel
from tkinter import ttk
from time import sleep
root = Tk()
def fct_run_for():
top=Toplevel(root)
top.title("Progression")
... | 0 | 2016-07-14T13:30:53Z | [
"python",
"tkinter",
"progress-bar"
] |
Determine if script is being piped to in Python 3 | 38,340,729 | <p>If my script needs to behave differently when it is being piped to versus when it is being called normally, how can I determine whether or not it is being piped to? This is necessary for avoiding hanging. I am not talking about merely checking whether or not <code>stdin</code> is empty or not.</p>
| 0 | 2016-07-13T00:12:18Z | 38,340,837 | <p>You can test if your program's input is connected to a tty, which may help, depending on your use case:
<code>
$ python -c 'import sys; print(sys.stdin.isatty())'
True
$ echo hi | python -c 'import sys; print(sys.stdin.isatty())'
False
$ python -c 'import sys; print(sys.stdin.isatty())' < foo
False
</code></p>
| -1 | 2016-07-13T00:26:32Z | [
"python",
"python-3.x",
"stdin",
"piping"
] |
I don't understand this error when I try to use operators on %s on Python 2.7 | 38,340,738 | <p>I started out programming a few days ago. I did some course on the internet and I was now looking to make a simple program to solve a rule of three (cross multiplication)
it goes as follow : </p>
<pre><code> # Def variables
print "a/b = c/d"
print "Put in the values you know. Leave the one that you don... | 0 | 2016-07-13T00:13:10Z | 38,340,753 | <p><code>"%s * %s / %s" % (c, b, d) = "a"</code> is invalid syntax. You can't have an operator like that on the left hand side of an assignment because you're trying to assign something to the result of an expression -- But that doesn't really make sense ...</p>
<p>did you mean:</p>
<pre><code>a = "%s * %s / %s" % (... | 1 | 2016-07-13T00:14:58Z | [
"python",
"python-2.7"
] |
I don't understand this error when I try to use operators on %s on Python 2.7 | 38,340,738 | <p>I started out programming a few days ago. I did some course on the internet and I was now looking to make a simple program to solve a rule of three (cross multiplication)
it goes as follow : </p>
<pre><code> # Def variables
print "a/b = c/d"
print "Put in the values you know. Leave the one that you don... | 0 | 2016-07-13T00:13:10Z | 38,340,799 | <p>Your code</p>
<pre><code>"%s * %s / %s" % (c, b, d) = "a"
</code></pre>
<p>is invalid because you're trying to assign a string "<em>a</em>" to another string. Everything inside quotation marks is a string. The operation <code>"%s * %s / %s" % (c, b, d)</code> creates a string where <em>%s</em> is substituted with ... | 0 | 2016-07-13T00:21:37Z | [
"python",
"python-2.7"
] |
Concatenation of unicode and byte strings | 38,340,781 | <p>From what I understand, when concatenating a string and Unicode string, Python will automatically decode the string based on the default encoding and convert to Unicode before concatenating.</p>
<p>I'm assuming something like this if default is <code>'ascii'</code> (please correct if mistaken):</p>
<p>string -> AS... | 0 | 2016-07-13T00:19:03Z | 38,343,254 | <blockquote>
<p>Wouldn't it be easier and raise less UnicodeDetectionError if, for example, <code>u'a' + 'Ó¸'</code> is converted to <code>u'a' + u'Ó¸'</code> directly before concatenating?</p>
</blockquote>
<p>It could probably do that with literals, but not string characters at runtime. Imagine a string that cont... | 3 | 2016-07-13T05:24:48Z | [
"python",
"unicode",
"ascii"
] |
Matplotlib produces a black image from an array full of ones | 38,340,813 | <p><strong>Intro</strong></p>
<p>I am doing some tests with <code>matplotlib.pyplot</code>. When I tried to save artificial images, I encoutered a strange behavior. Here is the very simple function I created to save images : </p>
<pre><code>import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def sav... | 1 | 2016-07-13T00:23:41Z | 38,344,451 | <p>I think you want to set the <code>vmin</code> and <code>vmax</code> when you call <code>imsave</code>. If you don't, it will be automatically determined from the array. From the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imsave" rel="nofollow">docs</a>:</p>
<blockquote>
<p>vmin/vmax: [ ... | 1 | 2016-07-13T06:48:05Z | [
"python",
"image-processing",
"matplotlib"
] |
Convert bytes data inside a string to a true bytes object | 38,340,817 | <p>In Python 3, I have a string like the following:</p>
<pre><code>mystr = "\x00\x00\x01\x01\x80\x02\xc0\x02\x00"
</code></pre>
<p>This string was read from a file and it is the bytes representation of some text. To be clear, <strong>this is a unicode string</strong>, not a <code>bytes</code> object.</p>
<p>I need t... | 0 | 2016-07-13T00:24:04Z | 38,341,170 | <p><code>mystr.encode("latin-1")</code> is what you want.</p>
| 2 | 2016-07-13T01:17:29Z | [
"python",
"character-encoding"
] |
How to make multiline graph with matplotlib subplots and pandas? | 38,340,855 | <p>I'm fairly new at coding (completely self taught), and have started using it at at my job as a research assistant in a cancer lab. I need some help setting up a few line graphs in matplot lab.</p>
<p>I have a dataset that includes nextgen sequencing data for about 80 patients. on each patient, we have different tim... | 3 | 2016-07-13T00:29:26Z | 38,363,702 | <p>I wrote a subplot function that may give you a hand. I modified the data a tad to help illustrate the plotting functionality. </p>
<pre><code>gene,yaxis,xaxis,pt #,gene #
ASXL1-3,34,1,3,1
ASXL1-3,3,98,3,1
IDH1-3,24,1,3,11
IDH1-3,7,98,3,11
RUNX1-3,38,1,3,21
RUNX1-3,2,98,3,21
U2AF1-3,33,1,3,26
U2AF1-3,0,98,3,26
ASXL1... | 1 | 2016-07-14T00:24:02Z | [
"python",
"pandas",
"matplotlib",
"plot",
"subplot"
] |
How to get target OS type in Testinfra when running a test remotely? | 38,340,906 | <p>Within <a href="https://github.com/philpep/testinfra" rel="nofollow">Testinfra</a>, how can I create a test condition for the target operating system (if at all)?</p>
<p>I'd like to run the test on <code>target</code> host through:</p>
<pre><code>$ testinfra -v --host=target test.py
</code></pre>
<p>I tried:</p>
... | 0 | 2016-07-13T00:36:57Z | 38,377,677 | <p>I had kinda the same problem, but solved it like this when I took a better look at this part: <a href="http://testinfra.readthedocs.io/en/latest/examples.html#test-docker-images" rel="nofollow">http://testinfra.readthedocs.io/en/latest/examples.html#test-docker-images</a></p>
<p>I have in my test file:
<strike>
... | 1 | 2016-07-14T15:00:58Z | [
"python",
"automated-tests",
"py.test"
] |
Removing duplicates: python results differ from sort -u | 38,340,914 | <p>I have a very long text file (2GB) and I removed duplicates using:</p>
<pre><code>sort -u filename > outfile1
</code></pre>
<p>and</p>
<pre><code>>>> data = open('filename', 'r').readlines()
>>> u = list(set(data))
>>> open('outfile2', 'w').writelines(u)
</code></pre>
<p>However the... | 2 | 2016-07-13T00:38:26Z | 38,340,957 | <p>Without seeing the actual output (or at least the 'extra' lines, we can only guess.</p>
<p>But it will come down to how much preprocessing is done by <code>sort</code>, which is finding more duplicates than <code>set()</code>.</p>
<p>Possible causes might be </p>
<ul>
<li>Trailing spaces on some lines. They might... | 3 | 2016-07-13T00:44:44Z | [
"python",
"list",
"set",
"duplicates"
] |
Removing duplicates: python results differ from sort -u | 38,340,914 | <p>I have a very long text file (2GB) and I removed duplicates using:</p>
<pre><code>sort -u filename > outfile1
</code></pre>
<p>and</p>
<pre><code>>>> data = open('filename', 'r').readlines()
>>> u = list(set(data))
>>> open('outfile2', 'w').writelines(u)
</code></pre>
<p>However the... | 2 | 2016-07-13T00:38:26Z | 38,355,906 | <p>if you combine them and create them into a list you could do this:</p>
<pre><code>non_duplicates= [a for i,a in enumerate(l) if i == l.index(a)]
</code></pre>
<p>this also keeps the order of the items it contains</p>
| 0 | 2016-07-13T15:28:18Z | [
"python",
"list",
"set",
"duplicates"
] |
Creating a dictionary type column in dataframe | 38,340,968 | <p>Consider the following dataframe:</p>
<pre><code>------------+--------------------+
|id| values
+------------+--------------------+
| 39|a,a,b,b,c,c,c,c,d
| 520|a,b,c
| 832|a,a
</code></pre>
<p>I want to convert it into the following DataFrame:</p>
<pre><code>------------+-------... | 0 | 2016-07-13T00:45:34Z | 38,356,594 | <p>I could not get exactly the output you need, but I was really close. This is what I could get:</p>
<pre><code>from pyspark.sql.functions import explode, split
counts = (df.select("id", explode(split("values", ",")).alias("value")).groupby("id", "value").count())
counts.show()
</code></pre>
<p>Output:</p>
<pre><co... | 0 | 2016-07-13T16:01:32Z | [
"python",
"pyspark",
"spark-dataframe"
] |
Creating a dictionary type column in dataframe | 38,340,968 | <p>Consider the following dataframe:</p>
<pre><code>------------+--------------------+
|id| values
+------------+--------------------+
| 39|a,a,b,b,c,c,c,c,d
| 520|a,b,c
| 832|a,a
</code></pre>
<p>I want to convert it into the following DataFrame:</p>
<pre><code>------------+-------... | 0 | 2016-07-13T00:45:34Z | 38,359,285 | <p>I ended up using this; if you feel there is a better approach do let me know.</p>
<pre><code>def split_test(str_in):
a = str_in.split(',')
b = {}
for i in a:
if i not in b:
b[i] = 1
else:
b[i] += 1
return str(b)
udf_value_count = udf(split_test, StringType() )
value_count_df = value_d... | 0 | 2016-07-13T18:32:05Z | [
"python",
"pyspark",
"spark-dataframe"
] |
Taking an existing private image and flash to another server | 38,340,995 | <p>I'm trying to figure out a way to take an existing private exported standard image template to flash to another server / instance. Looking through the API, I haven't been able to find anything, i've only found way to look up the private images on has. (Doing this via python / custom module ansible)</p>
| 0 | 2016-07-13T00:49:24Z | 38,353,383 | <p>You need to make sure that the image template is being listed here: <a href="https://control.softlayer.com/devices/images" rel="nofollow">https://control.softlayer.com/devices/images</a></p>
<p>if you can see the imagetemplate so you can use the reload method, see the code example <a href="http://stackoverflow.com/... | 0 | 2016-07-13T13:39:32Z | [
"python",
"softlayer"
] |
python hash events based on time into buckets | 38,341,013 | <p>My program is handling events that appear periodically. I want to hash them into buckets by their arrival time, in other words, truncate the event time by an arbitrary amount of seconds.</p>
<p>There are a lot of date and timestamp related questions, but I didn't find the answer to this. I figured out a way that ... | 0 | 2016-07-13T00:51:20Z | 38,341,014 | <p>Divide the event time by the bucket size, then multiply that (the bucket count) by the bucket size. This just removes remainder. Now an event can use that for the event time.</p>
<p>Here is a script and it's output to demonstrate how simple this is using python:</p>
<pre><code>from datetime import datetime
impor... | 0 | 2016-07-13T00:51:20Z | [
"python",
"hash",
"timestamp"
] |
List task in Python | 38,341,104 | <p>I have a tuple, let's say (2,5,8).</p>
<pre><code>a = (2,5,8)
</code></pre>
<p>Each element of the tuple can take a range of values. For example, the first position can range from 0 to 4, the second from 0 to 6 and the third from 0 to 10. What I want to do is to keep fixed positions 2 and 3 and make a list with al... | -1 | 2016-07-13T01:06:25Z | 38,341,712 | <p>What do you mean by efficient? If you mean it in terms of processing power, you should use 3 loops to append what you want to the list.</p>
<pre><code>result = []
for i in range(5):
result.append((i, 5, 8))
for i in range(7):
result.append((2, i, 8))
for i in range(9):
result.append((2, 5, i))
</code></... | 1 | 2016-07-13T02:28:48Z | [
"python",
"list",
"tuples"
] |
List task in Python | 38,341,104 | <p>I have a tuple, let's say (2,5,8).</p>
<pre><code>a = (2,5,8)
</code></pre>
<p>Each element of the tuple can take a range of values. For example, the first position can range from 0 to 4, the second from 0 to 6 and the third from 0 to 10. What I want to do is to keep fixed positions 2 and 3 and make a list with al... | -1 | 2016-07-13T01:06:25Z | 38,359,157 | <p>Although @Ariestinak gave a good solution, here is a generalized function you could use:</p>
<pre><code>def getCombinations( a, b, c ):
result = [(i, b, c) for i in range(5)] + \
[(a, i, c) for i in range(7)] + \
[(a, b, i) for i in range(9)]
return result
</code></pre>
<p>Then to... | 0 | 2016-07-13T18:23:40Z | [
"python",
"list",
"tuples"
] |
Pandas dataframe wrong number of rows | 38,341,133 | <p>I've got a reasonably large json file of log data that I'm trying to convert into XLS or CSV.
Something in the process is taking only the first 1000 rows, and I can't figure out what could be causing this.</p>
<pre><code>import json
import pprint
import pandas as pd
from pandas.io.json import json_normalize
f = op... | 1 | 2016-07-13T01:12:03Z | 38,341,510 | <p>Worked it out - ended up using ijson to load the json file and only the result values that I wanted.
Example code is here:</p>
<pre><code>import csv
import ijson
import pprint
import pandas as pd
from pandas.io.json import json_normalize
#print flattenjson(x)
#pprint.pprint
f = open('GetLog.json', 'r')
writer = p... | 0 | 2016-07-13T02:02:55Z | [
"python",
"json",
"csv",
"pandas"
] |
Trying to run this program but I'm getting 'invalid syntax' | 38,341,174 | <p>This program says hello and asks for my name.</p>
<pre><code>print('Hello world!')
print('What is your name?') #ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') #ask for their age
myAge = input(... | -1 | 2016-07-13T01:18:13Z | 38,341,225 | <p>You need to define your variables <code>myName</code> and <code>myAge</code>. Also you have a <code>SyntaxError</code> in the last line of your script where you have omitted a right parenthesis.</p>
<p>Try to erase the whole line and re-typing it all from scratch.</p>
| 0 | 2016-07-13T01:24:40Z | [
"python",
"python-3.x",
"syntax-error"
] |
Trying to run this program but I'm getting 'invalid syntax' | 38,341,174 | <p>This program says hello and asks for my name.</p>
<pre><code>print('Hello world!')
print('What is your name?') #ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') #ask for their age
myAge = input(... | -1 | 2016-07-13T01:18:13Z | 38,341,987 | <p>The last line should read</p>
<pre><code>print('You will be ' + str(int(myAge) + 1 'in a year.'))
</code></pre>
<p>You were missing a closing parentheses.</p>
<p>Also, for future reference, in the <code>input()</code> function you can put in the string specifying to the user what they should type in, something li... | 1 | 2016-07-13T03:03:08Z | [
"python",
"python-3.x",
"syntax-error"
] |
How to add an image and clock to a kv file | 38,341,180 | <p>I am trying to implement the template of the <a href="https://www.packtpub.com/packtlib/book/Application-Development/9781785286926/1/ch01lvl1sec13/Our%20project%20%20Comic%20Creator" rel="nofollow">ComicCreator</a> GUI sample as a template for my own project. The <a href="https://www.packtpub.com/packtlib/book/Appli... | 0 | 2016-07-13T01:19:34Z | 38,361,961 | <p>Some playing arround with BoxLayout's and Image or AsyncImage if your image is from the web.</p>
<p>So the python code could look like this.</p>
<pre><code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivy.clock import Clock
import time
class M... | 1 | 2016-07-13T21:25:33Z | [
"python",
"kivy",
"kivy-language"
] |
Change the way Python's multiprocessing raise errors | 38,341,186 | <p>I am using multiprocessing in Python using the <code>pool.apply_async</code>, to simultaneously run a function with various different arguments.</p>
<p>The relevant extract of the code is:</p>
<pre><code>import multiprocessing as mp
all_details_to_process_full = [[x,y.z], [x2,y2.z2]]
def loop_over_desired_sub(a... | 1 | 2016-07-13T01:20:04Z | 38,370,090 | <p>Each of your process are here independent as you use <code>apply_async</code>. Thus the default behavior of python is to process them independantly, meaning that one failing does not affect the other'</p>
<p>The issue here is that you process the results of your function <code>loop_over_desired_content</code> in an... | 2 | 2016-07-14T09:10:46Z | [
"python",
"multithreading",
"python-3.x",
"multiprocessing"
] |
day of the week error handling | 38,341,197 | <p>I'm new to pandas and trying to get the day of the week from a time stamp.</p>
<p>I have the following DF</p>
<pre><code> Date Open High
0 2015-07-13 532.880005 547.109985
1 2015-07-14 546.760010 565.848999
2 2015-07-15 560.130005 566.502991
3 2015-07-16 565.119995 580.679993
4 2015-07-1... | 3 | 2016-07-13T01:21:10Z | 38,341,237 | <p>So <code>df['Date'].dt.dayofweek</code> returns a Series. Instead do:</p>
<pre><code>df['weekday'] = df['Date'].dt.dayofweek
</code></pre>
<pre>
>>> df
Date Open High weekday
0 2015-07-13 532.880005 547.109985 0
1 2015-07-14 546.760010 565.848999 1
2 2015-07-15 560.130005 ... | 2 | 2016-07-13T01:26:03Z | [
"python",
"datetime",
"pandas"
] |
How to print AIC or BIC from ARIMA Model | 38,341,221 | <p>I've created an ARIMA model, but I am unable to find a way to print the AIC or BIC results. I need these numbers for model comparison. Unfortunately the documentation on sourceforge is down, and I cannot find my answer when looking at the statsmodel github repository. </p>
<p>Here's my code: </p>
<pre><code>import... | 0 | 2016-07-13T01:24:22Z | 38,357,938 | <p>I figured out the solution here. You need to import the ARMAResults class from statsmodels.tsa.arima_model. </p>
<pre><code>from statsmodels.tsa.arima_model import ARMAResults
</code></pre>
<p>Once this is complete you can insert</p>
<pre><code>print(ARMAResults.summary(results_ARIMA))
</code></pre>
<p>This wil... | 0 | 2016-07-13T17:15:07Z | [
"python",
"regression",
"statsmodels"
] |
Customize templates in a third party Django app | 38,341,254 | <p>I'm using a third party app (django-social-share) in my Django project but I need to customize the templates. I'm not sure how to go about doing that--everything I try keeps using the default templates. </p>
<p>The current default template is stored in:</p>
<pre><code>django-social-share/django_social_share/temp... | 0 | 2016-07-13T01:27:58Z | 38,353,582 | <p>To just change templates you don't have to fork an app. Just make sure you have set up your template loaders correctly. Usually you'd like something as: (<a href="https://docs.djangoproject.com/en/1.9/ref/settings/#templates" rel="nofollow">documentation</a>)</p>
<pre><code>'loaders': [
'django.template.loaders... | 2 | 2016-07-13T13:48:46Z | [
"python",
"django"
] |
Customize templates in a third party Django app | 38,341,254 | <p>I'm using a third party app (django-social-share) in my Django project but I need to customize the templates. I'm not sure how to go about doing that--everything I try keeps using the default templates. </p>
<p>The current default template is stored in:</p>
<pre><code>django-social-share/django_social_share/temp... | 0 | 2016-07-13T01:27:58Z | 38,717,384 | <p>The documentation states:</p>
<blockquote>
<p>Templates are in django_social_share/templatetags/post_to_twitter.html,
django_social_share/templatetags/post_to_facebook.html and
django_social_share/templatetags/post_to_gplus.html. You can override them
to suit your mileage.</p>
</blockquote>
<p>so you ca... | 0 | 2016-08-02T10:02:26Z | [
"python",
"django"
] |
Customize templates in a third party Django app | 38,341,254 | <p>I'm using a third party app (django-social-share) in my Django project but I need to customize the templates. I'm not sure how to go about doing that--everything I try keeps using the default templates. </p>
<p>The current default template is stored in:</p>
<pre><code>django-social-share/django_social_share/temp... | 0 | 2016-07-13T01:27:58Z | 38,725,452 | <p>You can put the template in a separate app within your project. Django looks for templates in your apps in the order they are defined in <code>INSTALLED_APPS</code>, and uses the first match:</p>
<blockquote>
<p>The order of INSTALLED_APPS is significant! For example, if you want
to customize the Django admin, ... | 2 | 2016-08-02T16:03:25Z | [
"python",
"django"
] |
combining two regex - lambda functions into one | 38,341,275 | <p>I'd like to combine two regex functions to clean up my data frame. Assume I've the following dataframe.</p>
<pre><code>import pandas as pd
time = ["09:00", "10:00", "11:00", "12:00", "13:00", "33:00"]
result = ["+52", "+62", "+44 - 10a10", "+44", "+30 - $1200", "110"]
data = pd.DataFrame({'time' : time, 'result' : ... | 2 | 2016-07-13T01:30:04Z | 38,341,316 | <p>You can use the or (<code>|</code>) in the RegEx and do both the operations in one shot, like this</p>
<pre><code>>>> import re
>>> re.sub(r'\+|-.*', '', 'a+b+c-d+f-g')
'abc'
</code></pre>
<p>So, in your case, the lambda function would be</p>
<pre><code>data['result'] = data['result'].map(lambda... | 3 | 2016-07-13T01:35:03Z | [
"python",
"regex",
"lambda"
] |
Python XML Parser that tracks line number in XML document | 38,341,321 | <p>Are there any XML parsing libraries in Python that track the line number of each element? I am writing a script to verify XML settings, and it would be useful to print line numbers if my script detects an invalid line.</p>
| 1 | 2016-07-13T01:35:47Z | 38,341,375 | <p>I think what you really need to do is to <em>validate the XML file against an expected XML schema</em>. <code>lxml</code> <a href="http://lxml.de/validation.html" rel="nofollow">can do that for you</a>. The validation log would contain all the information you need to locate the problem in the XML file.</p>
| 2 | 2016-07-13T01:43:50Z | [
"python",
"xml"
] |
Python XML Parser that tracks line number in XML document | 38,341,321 | <p>Are there any XML parsing libraries in Python that track the line number of each element? I am writing a script to verify XML settings, and it would be useful to print line numbers if my script detects an invalid line.</p>
| 1 | 2016-07-13T01:35:47Z | 38,354,155 | <p><a href="http://lxml.de/" rel="nofollow">lxml</a> can be used to parse xml and retain line numbers. Here is a simple example:</p>
<pre><code>from lxml import etree
xml = '''
<foo>
<bar baz="1">hello</bar>
<bar baz='2'>world</bar>
</foo>
'''
root = etree.... | 2 | 2016-07-13T14:13:43Z | [
"python",
"xml"
] |
Django Embed Admin Form | 38,341,325 | <p>I am trying to embed the exact form that appears in the Django admin when I edit a model in a different page on my website. My plan is to have an Edit button that, when clicked, displays a modal with the edit page inside of it.</p>
<p>The issue with using a ModelForm is that this particular model has two generic fo... | 0 | 2016-07-13T01:36:16Z | 38,363,690 | <p>I fixed the issue by using an <code>iframe</code> to embed the page itself. I used the <code>?_popup=1</code> argument so that the navbar and other parts of the admin site wouldn't show up.</p>
| 0 | 2016-07-14T00:22:31Z | [
"python",
"django",
"django-forms",
"django-admin"
] |
Accessing values that are appended to a list in a recursive function | 38,341,372 | <p>I want to generate different permutations of the weight list that I have and add all the permutations to an outer list. This code generates the permutations correctly but even if i add it to the outer list, it is empty when I print it in the end. </p>
<p>I thought this was call by reference since lists are mutable... | 3 | 2016-07-13T01:43:41Z | 38,341,477 | <p>You are correct that the list is modified. One thing you seem to have missed: you appended <code>inner_list</code> to <code>outer_list</code>, but you didn't copy it first. It is still mutable, and all of the <code>inner_list</code>s that you appended are the same object. Just use a copy instead:</p>
<pre><code>... | 4 | 2016-07-13T01:58:18Z | [
"python",
"recursion",
"immutability"
] |
Using a dictionary as a key in a dictionary | 38,341,400 | <p>Is there any way to use a dictionary as the key in a dictionary. Currently I am using two lists for this but it would be nice to use a dictionary. Here is what I currently am doing:</p>
<pre><code>dicts = [{1:'a', 2:'b'}, {1:'b', 2:'a'}]
corresponding_name = ['normal', 'switcheroo']
if {1:'a', 2:'b'} in dicts:
... | 3 | 2016-07-13T01:47:38Z | 38,341,479 | <p>I guess this will help you</p>
<pre><code>dicts = {
'normal' : "we could initialize here, but we wont",
'switcheroo' : None,
}
dicts['normal'] = {
1 : 'a',
2 : 'b',
}
dicts['switcheroo'] = {
1:'b',
2:'a'
}
if dicts.has_key('normal'):
if dicts['normal'].has_key(1):
print dicts['n... | 0 | 2016-07-13T01:58:26Z | [
"python",
"dictionary"
] |
Using a dictionary as a key in a dictionary | 38,341,400 | <p>Is there any way to use a dictionary as the key in a dictionary. Currently I am using two lists for this but it would be nice to use a dictionary. Here is what I currently am doing:</p>
<pre><code>dicts = [{1:'a', 2:'b'}, {1:'b', 2:'a'}]
corresponding_name = ['normal', 'switcheroo']
if {1:'a', 2:'b'} in dicts:
... | 3 | 2016-07-13T01:47:38Z | 38,341,505 | <p>A dictionary key has to be immutable. A dictionary is mutable, and hence can't be used as a dictionary key. <a href="https://docs.python.org/2/faq/design.html#why-must-dictionary-keys-be-immutable" rel="nofollow">https://docs.python.org/2/faq/design.html#why-must-dictionary-keys-be-immutable</a></p>
<p>If you can g... | 3 | 2016-07-13T02:01:56Z | [
"python",
"dictionary"
] |
Using a dictionary as a key in a dictionary | 38,341,400 | <p>Is there any way to use a dictionary as the key in a dictionary. Currently I am using two lists for this but it would be nice to use a dictionary. Here is what I currently am doing:</p>
<pre><code>dicts = [{1:'a', 2:'b'}, {1:'b', 2:'a'}]
corresponding_name = ['normal', 'switcheroo']
if {1:'a', 2:'b'} in dicts:
... | 3 | 2016-07-13T01:47:38Z | 38,341,982 | <p>As other answers have noted you can't use dictionaries as keys since keys need to be immutable. What you can do though is to turn a dictionary to a <a href="https://docs.python.org/2/library/stdtypes.html#frozenset" rel="nofollow"><code>frozenset</code></a> of <code>(key, value)</code> tuples which you can use as a ... | 3 | 2016-07-13T03:02:44Z | [
"python",
"dictionary"
] |
Filter rows if column is within a certain range | 38,341,535 | <p>How do I filter rows into specific csv files depending on if the number in that column is within a defined range?</p>
<pre><code>input.csv
1.23
2.43
5.28
6.42
6.42
6.42
8.98
</code></pre>
<p>I'm trying to get anything between <code>0.01</code> and <code>8.99</code> to output to <code>low.csv</code> but nothing hap... | 0 | 2016-07-13T02:06:00Z | 38,341,557 | <p>Use Pandas</p>
<pre><code>import pandas as pd
df = pd.read_csv("input.csv")
df = df[(df > 0.01) & (df < 8.99)]
df.to_csv("input.csv", index=False)
</code></pre>
| 1 | 2016-07-13T02:08:35Z | [
"python",
"csv",
"lambda"
] |
Filter rows if column is within a certain range | 38,341,535 | <p>How do I filter rows into specific csv files depending on if the number in that column is within a defined range?</p>
<pre><code>input.csv
1.23
2.43
5.28
6.42
6.42
6.42
8.98
</code></pre>
<p>I'm trying to get anything between <code>0.01</code> and <code>8.99</code> to output to <code>low.csv</code> but nothing hap... | 0 | 2016-07-13T02:06:00Z | 38,341,598 | <p>From what I see, your <code>low</code> variable has <a href="https://docs.python.org/2/tutorial/floatingpoint.html" rel="nofollow">float point inaccuracy</a>. See this output:</p>
<pre><code>>>> low = [x * 0.01 for x in range(0, 900)]
>>> low
[0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0... | 1 | 2016-07-13T02:14:41Z | [
"python",
"csv",
"lambda"
] |
Filter rows if column is within a certain range | 38,341,535 | <p>How do I filter rows into specific csv files depending on if the number in that column is within a defined range?</p>
<pre><code>input.csv
1.23
2.43
5.28
6.42
6.42
6.42
8.98
</code></pre>
<p>I'm trying to get anything between <code>0.01</code> and <code>8.99</code> to output to <code>low.csv</code> but nothing hap... | 0 | 2016-07-13T02:06:00Z | 38,341,616 | <p>This line is wrong:</p>
<pre><code>filtered = filter(lambda p:low == p[0], reader)
</code></pre>
<p><code>low</code> is a <code>list</code>. <code>p[0]</code> is a <code>float</code>. The lambda expression will never be <code>True</code>, since no <code>list</code> can ever equal a <code>float</code>.</p>
<p>Try... | 1 | 2016-07-13T02:17:30Z | [
"python",
"csv",
"lambda"
] |
Python - Plotting from data file with errorbars? | 38,341,572 | <p>I've got a data file (data.txt) that has 6 columns:
Column 1 and 4 are the x and y data with column 2 and 3 being the (unsymmetrical) error bars for column 1 and columns 4 and 5 being the (unsymmetrical) error bars for column 6: </p>
<pre><code>100 0.77 1.22 3 0.11 0.55
125 0.28 1.29 8 0.15 0.53
150 0.43 1.11 1... | 0 | 2016-07-13T02:11:32Z | 38,375,968 | <p>Using <code>numpy.loadtxt</code> works perfectly:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("data.txt")
x = data[:, 0]
y = data[:, 3]
# errorbar expects array of shape 2xN and not Nx2 (N = len(x)) for xerr and yerr
xe = data[:, 1:3].T
ye= data[:, 4:].T
plt.errorbar(x, y, ... | 0 | 2016-07-14T13:46:05Z | [
"python",
"matplotlib",
"errorbar"
] |
Read db.StringListProperty from ndb | 38,341,578 | <p>I have a DB model in AppEngine that looks something like this:</p>
<pre><code>class MyModel(db.Model):
my_list = db.StringListProperty()
</code></pre>
<p>There are entities written to datastore with this data populated, I can pull them out via DB and I see the in the entity viewer. I've been working to migrate ... | 0 | 2016-07-13T02:11:47Z | 38,341,913 | <p>I don't have 50 rep yet so I can't ask in a comment, but if you have copy-pasted your code across, I am pretty sure your issue is that you are still prefixing with "db"</p>
<p>It should be </p>
<pre><code>my_list = ndb.StringProperty(repeated=True)
</code></pre>
<p><a href="https://cloud.google.com/appengine/docs... | 1 | 2016-07-13T02:53:56Z | [
"python",
"google-app-engine",
"app-engine-ndb",
"google-app-engine-python"
] |
pyodbc SQL Query to Numpy array typeerror: bytes-like object required | 38,341,594 | <p>I've been trying to pull data from SQL database using pyodbc and want to place it into numpy.array. However I found difficulty in inputting multiple data-type for np.fromiter() argument.</p>
<pre><code>import pyodbc as od
import numpy as np
con = od.connect('DSN=dBASE; UID=user; PWD=pass')
cursor = con.cursor()
SQ... | 0 | 2016-07-13T02:14:03Z | 38,341,920 | <p>You are attempting to pass one iterable, specifically the first column of query, with multiple dtypes. <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html" rel="nofollow">Numpy.iter()</a> takes only one object and type. Consider passing each column of query resultset as a one-dimensional... | 0 | 2016-07-13T02:54:40Z | [
"python",
"sql",
"arrays",
"numpy"
] |
ValueError: Invalid control character at: line 115076 column 173 | 38,341,646 | <p>I have problem to parse json file in python.</p>
<p>my code is here :</p>
<pre><code>import json
from pprint import pprint
with open('review_sample.json') as data_file:
data = json.load(data_file)
pprint(data)
</code></pre>
<p>json file format is here :</p>
<pre><code> {
"table": "TempTable",
"rows":... | 1 | 2016-07-13T02:21:08Z | 38,342,496 | <p>you can NOT json.loads a file handle, you should loads string instead.</p>
<p>I have your content in a.txt</p>
<p>[root@ebs-49393 tmp]# python test.py</p>
<p>{u'table': u'TempTable', u'rows': [{u'comment': u"This is an excellent TV at an excellent price. For those who say that you can't tell the difference betwee... | 0 | 2016-07-13T04:04:08Z | [
"python",
"json"
] |
Tensorflow Error: Incompatible Shapes for Broadcasting | 38,341,649 | <p>I am currently developing a program in Tensorflow that reads data 1750 by 1750 pixels. I ran it through a convolutional network:</p>
<pre><code>import os
import sys
import tensorflow as tf
import Input
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer('batch_size', 100, "hello")
tf.app.flags.DEFINE_string('... | 0 | 2016-07-13T02:21:19Z | 38,354,316 | <p>I've found the following problems:</p>
<ol>
<li><p>Your <code>labels</code> input is a simple 1-dimensional array of label identifiers, but it needs to be one-hot encoded to be a matrix with size <code>[batch_size, 4]</code> that's filled with either 1s or 0s.</p></li>
<li><p>Your max pooling operation needs to hav... | 1 | 2016-07-13T14:20:33Z | [
"python",
"machine-learning",
"neural-network",
"tensorflow"
] |
Editing elements of a list of tuples based on hamming distance | 38,341,664 | <p>I have a list of tuples:</p>
<pre><code>f_list = [('AGCTCCCCGTTTTC', 34), ('TTCATTCCTCTCTC', 1), ('AGCTCCCCGGTTTC', 1)]
</code></pre>
<p>If the hamming distance between any two strings is less than 3, I would like to merge the elements by adding the second entries of each element. If the above condition is not sat... | 0 | 2016-07-13T02:23:20Z | 38,347,689 | <p>My assumptions are that once an element has been merged, it doesn't need to be checked. I've added three extra elements, one that should match and another that will not match any, and one that will match the first element (so there is an element that has more than one match) to make the test a little bit more robust... | 0 | 2016-07-13T09:27:24Z | [
"python"
] |
IndexError: list index out of range (Python 3.5) | 38,341,665 | <p>I am trying to print pieces of an email (from, subject, body) with Python 3.5. I get a weird index error:</p>
<pre><code>Traceback (most recent call last):
File "/home/user/PycharmProjects/email/imaplib_fetch_rfc822.py", line 21, in <module>
subject_, from_, to_, body_, = ' ' + email[0], email[1], email[2], '... | -2 | 2016-07-13T02:23:24Z | 38,356,877 | <p>You've got a few issues with your indexing/splitting. I think you don't need to convert <code>raw_email</code> from a tuple to string, just process the tuple.</p>
<p>Then, your <code>split('\\r\\n')</code> is incorrect, it should be <code>split('\r\n')</code></p>
<p>I think this will resolve it:</p>
<pre><code> ... | 1 | 2016-07-13T16:15:55Z | [
"python",
"python-3.x",
"python-3.5",
"imaplib"
] |
Python regular expression sub | 38,341,678 | <p>I am using this sub:</p>
<pre><code>def camelize(key):
print re.sub(r"[a-z0-9]_[a-z0-9]", underscoreToCamel, key)
</code></pre>
<p>Which calls this function</p>
<pre><code>def underscoreToCamel(match):
return match.group()[0] + match.group()[2].upper()
</code></pre>
<p>When I call <code>camelize('sales_p... | 0 | 2016-07-13T02:25:09Z | 38,341,796 | <p>You could use look-behind so that each match does not overlap with the previous one.</p>
<pre><code>def camelize(key):
return re.sub('(?<=[a-z0-9])_[a-z0-9]', lambda m: m.group()[1].upper(), key)
</code></pre>
| 0 | 2016-07-13T02:40:16Z | [
"python",
"regex"
] |
Python regular expression sub | 38,341,678 | <p>I am using this sub:</p>
<pre><code>def camelize(key):
print re.sub(r"[a-z0-9]_[a-z0-9]", underscoreToCamel, key)
</code></pre>
<p>Which calls this function</p>
<pre><code>def underscoreToCamel(match):
return match.group()[0] + match.group()[2].upper()
</code></pre>
<p>When I call <code>camelize('sales_p... | 0 | 2016-07-13T02:25:09Z | 38,341,812 | <p>Your code matches as so:</p>
<pre><code>s_p
j_3
s_a
</code></pre>
<p>As you can see, <code>_3_</code> is not matched because it was previously matched.
So you can actually just match one character:</p>
<pre><code>def camelize(key):
print re.sub(r"_[a-z0-9]", underscoreToCamel, key)
def underscoreToCamel(matc... | 0 | 2016-07-13T02:42:14Z | [
"python",
"regex"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.