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 |
|---|---|---|---|---|---|---|---|---|---|
Argparse Reopening file. | 39,333,854 | <p>I'm using the argparse module and I have a log file which is continuously appended to. I want to open args.file, do something with the content, then close it and opening it again after some time. </p>
<p>An example piece of code:</p>
<pre><code>import argparse
import time
parser = argparse.ArgumentParser()
parser.... | 0 | 2016-09-05T15:36:25Z | 39,333,897 | <p>you can open it again using</p>
<pre><code>args.file = open(args.file.name)
</code></pre>
| 0 | 2016-09-05T15:39:59Z | [
"python",
"io",
"argparse"
] |
Argparse Reopening file. | 39,333,854 | <p>I'm using the argparse module and I have a log file which is continuously appended to. I want to open args.file, do something with the content, then close it and opening it again after some time. </p>
<p>An example piece of code:</p>
<pre><code>import argparse
import time
parser = argparse.ArgumentParser()
parser.... | 0 | 2016-09-05T15:36:25Z | 39,334,519 | <pre><code>parser.add_argument('file',type=file)
</code></pre>
<p>does not mean, <code>the argument is to be a file</code>. It means</p>
<pre><code>value = file(astring)
args.file = value
</code></pre>
<p>The <code>type</code> parameter is a function that operates on a string. In Python3 <code>file</code> has been... | 1 | 2016-09-05T16:25:43Z | [
"python",
"io",
"argparse"
] |
Python: Pandas: making a dictionary from dataframe | 39,333,881 | <p>I am trying to convert a dataframe to dictionary:</p>
<pre><code>xtest_cat = xtest_cat.T.to_dict().values()
</code></pre>
<p>but it gives a warning :</p>
<blockquote>
<p>Warning: DataFrame columns are not unique, some columns will be omitted python</p>
</blockquote>
<p>I checked the columns names of the datafr... | 1 | 2016-09-05T15:38:49Z | 39,334,000 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> for create <code>unique</code> index:</p>
<pre><code>xtest_cat = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[... | 1 | 2016-09-05T15:48:20Z | [
"python",
"pandas",
"dictionary",
"dataframe",
"multiple-columns"
] |
Python 3 - Cant get data to display when called | 39,333,882 | <p>This is the function defined in class "Roster"</p>
<pre><code>class Roster:
def __init__(self, name, phone, jersy):
self.name = name
self.phone = phone
self.jersy = jersy
def setName(self, name):
self.name = name
def setPhone(self, phone):
self.phone = phone
d... | -2 | 2016-09-05T15:38:50Z | 39,333,986 | <p>Your code has a number of conceptual problems that you need to solve before you can start trying to run it and start asking for help with compiler errors. Here are three, to get you started.</p>
<p>(1) Your <code>Roster</code> class is designed to be instantiated, but you never create an instance. Whenever you writ... | 3 | 2016-09-05T15:46:31Z | [
"python",
"attributeerror"
] |
Exporting a random sample from CSV file to a new CSV file - output is messy | 39,333,994 | <p>I am trying to export a random subset of a CSV file to a new CSV file using the following code:</p>
<pre><code>with open("DepressionEffexor.csv", "r") as effexor:
lines = [line for line in effexor]
random_choice = random.sample(lines, 229)
with open("effexorSample.csv", "w") as sample:
sample.write("\n"... | 0 | 2016-09-05T15:47:15Z | 39,334,078 | <p>Assuming you had a CSV read into pandas:</p>
<pre><code>df = pandas.read_csv("csvfile.csv")
sample = df.sample(n)
sample.to_csv("sample.csv")
</code></pre>
<p>You could make it even shorter:</p>
<pre><code>df.sample(n).to_csv("csvfile.csv")
</code></pre>
<p>The <a href="http://pandas.pydata.org/pandas-docs/stabl... | 3 | 2016-09-05T15:54:07Z | [
"python",
"csv",
"pandas",
"random"
] |
Exporting a random sample from CSV file to a new CSV file - output is messy | 39,333,994 | <p>I am trying to export a random subset of a CSV file to a new CSV file using the following code:</p>
<pre><code>with open("DepressionEffexor.csv", "r") as effexor:
lines = [line for line in effexor]
random_choice = random.sample(lines, 229)
with open("effexorSample.csv", "w") as sample:
sample.write("\n"... | 0 | 2016-09-05T15:47:15Z | 39,334,082 | <p>Using pandas, this translates to:</p>
<pre><code>import pandas as pd
#Read the csv file and store it as a dataframe
df = pd.read_csv('DepressionEffexor.csv')
#Shuffle the dataframe and store it
df_shuffled = df.iloc[np.random.permutation(len(df))]
#You can reset the index with the following
df_shuffled.reset_ind... | 0 | 2016-09-05T15:54:40Z | [
"python",
"csv",
"pandas",
"random"
] |
How to keep track of whether all strings in a list have a specific string present in them? | 39,334,049 | <p>I have a list of strings within which I need to search for a specific sub-string and return a result only when the sub-string is present in every string that is in the list. My first idea was to create a list of boolean values that correspond with whether the sub-string is present in each larger string in my list, a... | 1 | 2016-09-05T15:52:27Z | 39,334,089 | <p>you can use <a href="https://docs.python.org/2/library/functions.html#all" rel="nofollow"><code>all()</code></a> and <a href="https://docs.python.org/2/reference/expressions.html#in" rel="nofollow"><code>in</code></a>:</p>
<pre><code>l = ["pie", "lie", "die"]
all( ['ie' in x for x in l] )
</code></pre>
<p>The abov... | 2 | 2016-09-05T15:55:16Z | [
"python",
"list",
"boolean"
] |
How to keep track of whether all strings in a list have a specific string present in them? | 39,334,049 | <p>I have a list of strings within which I need to search for a specific sub-string and return a result only when the sub-string is present in every string that is in the list. My first idea was to create a list of boolean values that correspond with whether the sub-string is present in each larger string in my list, a... | 1 | 2016-09-05T15:52:27Z | 39,334,942 | <p>I would use the built-in <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all</code></a> function along with <a href="https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions" rel="nofollow">generator expression</a> to avoid creating a throw-awa... | 0 | 2016-09-05T16:58:33Z | [
"python",
"list",
"boolean"
] |
plot a fuction in the same graph with different arguments next to each other | 39,334,057 | <p>I have a matrix H, that can take 3 directional arguments. I want to plot the eigenvalues (just think of it as function) with one set of arguments & next to it - still in the same graph - the function with another set of arguments.
This is used in physics very often i.e. when plotting band structures.
It looks li... | -1 | 2016-09-05T15:52:52Z | 39,334,208 | <p>Below is a script where a function <code>f</code> takes 3 parameters <code>a, b, c</code>. The x-values are split into three different regimes, <code>x1, x2, x3</code>, with corresponding function values <code>f1, f2, f3</code>. At some breakpoints (defined by <code>x_ticks</code>) there are lines drawn, and the x... | -1 | 2016-09-05T16:03:48Z | [
"python",
"matplotlib",
"plot",
"physics",
"axes"
] |
plot a fuction in the same graph with different arguments next to each other | 39,334,057 | <p>I have a matrix H, that can take 3 directional arguments. I want to plot the eigenvalues (just think of it as function) with one set of arguments & next to it - still in the same graph - the function with another set of arguments.
This is used in physics very often i.e. when plotting band structures.
It looks li... | -1 | 2016-09-05T15:52:52Z | 39,335,473 | <p>Let me see if I'm understanding what you're after correctly.</p>
<p>Try something like this:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
gs = gridspec.GridSpec(1,n, width_ratios = [width_1,...,width_n])
axes = [plt.subplot(subplot) fo... | 0 | 2016-09-05T17:44:18Z | [
"python",
"matplotlib",
"plot",
"physics",
"axes"
] |
Making queries ManyToMany relationships | 39,334,071 | <p>I have a model named <code>AffectedSegment</code> which is used for store a corporal segments selection.</p>
<pre><code>class AffectedSegment(models.Model):
SEGMENTO_ESCAPULA = 'Escápula'
SEGMENTO_HOMBRO = 'Hombro'
SEGMENTO_CODO = 'Codo'
SEGMENTO_ANTEBRAZO = 'Antebrazo'
SEGMENTO_CARPO_MUNECA =... | 0 | 2016-09-05T15:53:36Z | 39,336,045 | <p>As you've said, <code>affected_segment</code> is a many-to-many field. That means it refers to <em>many</em> segments (and the name seems wrong, it should be plural). So you can't just output it, you need to iterate through it:</p>
<pre><code>{% for a in rehabilitationsessions %}
{% for r in a.affected_segment.a... | 1 | 2016-09-05T18:35:56Z | [
"python",
"django",
"orm",
"models"
] |
Speech recognition streaming delay before start to recording on python | 39,334,172 | <p>I have a delay while trying to stream audio to speech recognition service.</p>
<p>I have two functions that handles this task,
the first one that using alsaaudio and "yield" to return the data to the calling function.
and the second function that using requests that I passing to it the url the headers and the reco... | 0 | 2016-09-05T16:01:23Z | 39,349,665 | <p>Well, there are many lower-level APIs, including async ones like <a href="https://pymotw.com/2/asyncore/" rel="nofollow">asyncore</a> which allows you to interact without using threads at all.</p>
<p>I would simply increase the buffer size in alsaaudio with <a href="https://larsimmisch.github.io/pyalsaaudio/libalsa... | 1 | 2016-09-06T13:00:55Z | [
"python",
"linux",
"multithreading",
"speech-recognition"
] |
De-Serializing msg_container objects returned from the telegram.org server | 39,334,196 | <p>I'm having trouble de-serializing a <code>msg_container</code> object. The issue seems to be my understanding of where the <code>flags</code> field is located in the <code>message</code> as it doesn't make sense to me. My assumptions below come from reading this page: <a href="https://core.telegram.org/mtproto/TL" r... | 1 | 2016-09-05T16:03:09Z | 39,335,056 | <p>Here is a simple approach to use in handling messages packed in a container:</p>
<pre><code>Container_type_header
Content_count
[messages]
</code></pre>
<p>Each message is packed like so:</p>
<pre><code>msgs_id
seq_no
mgs_len
msg_body
</code></pre>
<p>given your sample data:</p>
<pre><code>DCF8F173 --> conta... | 1 | 2016-09-05T17:06:40Z | [
"python",
"api",
"telegram"
] |
Use else in dict comprehension | 39,334,201 | <p>From two dictionaries:</p>
<pre><code>d1 = {a:a for a in 'abcdefg'}
d2 = {n:n for n in range(10)}
</code></pre>
<p>How can I create a third one like:</p>
<pre><code>new_dict = {k:d1[k] if k in d1.keys() else k:d2[k] for k in 'abc123' }
</code></pre>
<p>It's throwing a syntax Error, but with list comprehension s... | -1 | 2016-09-05T16:03:23Z | 39,334,330 | <p>You can't use the <em>key-value</em> pair in the <code>else</code> part of ternary conditional like so. </p>
<p>Do this instead:</p>
<pre><code>new_dict = {k: d1[k] if k in d1 else d2[int(k)] for k in 'abc123'}
# ^^<- make value d2[int(k)] on else
print(new_dict)
#{'2': 2, '1... | 1 | 2016-09-05T16:12:34Z | [
"python",
"dictionary",
"list-comprehension"
] |
Use else in dict comprehension | 39,334,201 | <p>From two dictionaries:</p>
<pre><code>d1 = {a:a for a in 'abcdefg'}
d2 = {n:n for n in range(10)}
</code></pre>
<p>How can I create a third one like:</p>
<pre><code>new_dict = {k:d1[k] if k in d1.keys() else k:d2[k] for k in 'abc123' }
</code></pre>
<p>It's throwing a syntax Error, but with list comprehension s... | -1 | 2016-09-05T16:03:23Z | 39,335,377 | <p>As described, it seems like both your <code>d1</code> and <code>d2</code> are artifacts of how you envision solving the problem and aren't essential. How about simply:</p>
<pre><code>>>> dictionary = {k: int(k) if k.isdigit() else k for k in 'abc123'}
>>> dictionary
{'b': 'b', '3': 3, '2': 2, '1'... | 1 | 2016-09-05T17:35:35Z | [
"python",
"dictionary",
"list-comprehension"
] |
Python_Flask_Webapp Select menu doesn't work | 39,334,235 | <p>I'm learning Flask Web Development this book, I have a function on my page that in the "account" there is a select menu , I can choose the function inside , i.e. change password , or log out.
But it's strange that the select menu doesn't work in the index page, no response when I click the "account" , in others page... | 0 | 2016-09-05T16:06:14Z | 39,375,088 | <p>Finally , I found the problem which caused this...</p>
<p>because ...in my index.html , I insert the {%block scripts%} inside the {%block page_content%}....</p>
<p>the "block" should be seprarte...if block A is inside block B, the A is useless</p>
<pre><code>{% extends "base.html" %}
{% import "bootstrap/wtf.html... | 0 | 2016-09-07T16:26:50Z | [
"javascript",
"jquery",
"python",
"html",
"flask"
] |
Capitalizing hyphenated name | 39,334,291 | <p>I have a script looking like this:</p>
<pre><code>firstn = input('Please enter your first name: ')
lastn = input('Please enter Your last name: ')
print('Good day, ' + str.capitalize(firstn) + ' ' + str.capitalize(lastn)+ '!')
</code></pre>
<p>It will work nicely with simple names like jack black or morgan meeman... | 2 | 2016-09-05T16:09:40Z | 39,334,331 | <p>You can use <a href="https://docs.python.org/2/library/stdtypes.html#str.title" rel="nofollow">title()</a>:</p>
<pre><code>print('Good day,', firstn.title(), lastn.title(), '!')
</code></pre>
<p>Example from the console:</p>
<pre><code>>>> 'jordan-bellfort image'.title()
'Jordan-Bellfort Image'
</code></... | 6 | 2016-09-05T16:12:45Z | [
"python",
"capitalize"
] |
Capitalizing hyphenated name | 39,334,291 | <p>I have a script looking like this:</p>
<pre><code>firstn = input('Please enter your first name: ')
lastn = input('Please enter Your last name: ')
print('Good day, ' + str.capitalize(firstn) + ' ' + str.capitalize(lastn)+ '!')
</code></pre>
<p>It will work nicely with simple names like jack black or morgan meeman... | 2 | 2016-09-05T16:09:40Z | 39,334,332 | <p>Use <a href="https://docs.python.org/2/library/string.html" rel="nofollow"><code>string.capwords()</code></a>instead</p>
<blockquote>
<p>Split the argument into words using str.split(), capitalize each word
using str.capitalize(), and join the capitalized words using
str.join()</p>
</blockquote>
<pre><code>i... | 1 | 2016-09-05T16:12:49Z | [
"python",
"capitalize"
] |
Capitalizing hyphenated name | 39,334,291 | <p>I have a script looking like this:</p>
<pre><code>firstn = input('Please enter your first name: ')
lastn = input('Please enter Your last name: ')
print('Good day, ' + str.capitalize(firstn) + ' ' + str.capitalize(lastn)+ '!')
</code></pre>
<p>It will work nicely with simple names like jack black or morgan meeman... | 2 | 2016-09-05T16:09:40Z | 39,334,405 | <p>I'd suggest just using <a href="https://docs.python.org/2/library/stdtypes.html#str.title" rel="nofollow">str.title</a>, here's a working example comparing your version and the one using str.title method:</p>
<pre><code>import string
tests = [
["jack", "black"],
["morgan", "meeman"],
["jordan-bellfort"... | 1 | 2016-09-05T16:17:41Z | [
"python",
"capitalize"
] |
Convert Pandas tseries object to a DataFrame | 39,334,343 | <p>I wish to convert the following <code><'pandas.tseries.resample.DatetimeIndexResampler'></code> type object into a pandas DataFrame object (<code><'pandas.core.frame.DataFrame'></code>). However I cannot find the relevant function in the pandas documentation to allow me to do this. </p>
<p>The data take... | 2 | 2016-09-05T16:13:22Z | 39,334,363 | <p>You need some aggregate function like <code>sum</code> or <code>mean</code>.</p>
<p>Sample with your data:</p>
<pre><code>print (df)
M30
Date
2016-02-29 -61.187699
2016-03-31 -60.869565
2016-04-30 -61.717922
2016-05-31 -61.823966
2016-06-30 -62.142100
#resample by 2 months
r = d... | 3 | 2016-09-05T16:14:43Z | [
"python",
"pandas",
"dataframe",
"time-series",
"resampling"
] |
Possible to pass a function into a object's method as an argument, which can refer to that object? | 39,334,408 | <pre><code>def my_func():
stuff
return something
my_object.my_method(my_func)
</code></pre>
<p>I want my_func to be able to refer to <code>my_object</code>. Essentially like deferred <code>self</code>, which means "whatever object I am in, refer to that"</p>
| 1 | 2016-09-05T16:17:56Z | 39,334,573 | <p>You could use the <strong><a href="https://docs.python.org/2/library/inspect.html" rel="nofollow"><code>inspect</code></a></strong> module</p>
<pre><code>import inspect
def my_func():
stuff
my_object = inspect.stack()[1][0].f_locals["self"]
return something
</code></pre>
<p>However, I guess a simpler ... | 1 | 2016-09-05T16:29:58Z | [
"python",
"python-2.7",
"functional-programming",
"self",
"function-object"
] |
Possible to pass a function into a object's method as an argument, which can refer to that object? | 39,334,408 | <pre><code>def my_func():
stuff
return something
my_object.my_method(my_func)
</code></pre>
<p>I want my_func to be able to refer to <code>my_object</code>. Essentially like deferred <code>self</code>, which means "whatever object I am in, refer to that"</p>
| 1 | 2016-09-05T16:17:56Z | 39,369,488 | <p>You want to make a <a href="http://code-maven.com/function-or-callback-in-python" rel="nofollow">callback</a>. </p>
<p>And <a href="http://stackoverflow.com/questions/4689984/implementing-a-callback-in-python-passing-a-callable-reference-to-the-current">here</a> is a usage of callback in a design pattern. </p>
| 0 | 2016-09-07T12:05:07Z | [
"python",
"python-2.7",
"functional-programming",
"self",
"function-object"
] |
WxPython zooming technique | 39,334,441 | <p>I am developing a wxpython project where I am drawing a diagram on to a panel that I need to be able to zoom in/out to this diagram(a directed acyclic graph in my case). I will achieve this by mouse scroll when the cursor is on the panel, however that is not a part of my question. I need an advice from an experience... | 0 | 2016-09-05T16:20:57Z | 39,335,812 | <p>Yes, from your description <code>FloatCanvas</code> would certainly meet your needs. </p>
<p>Another possibility to consider would be the <code>wx.GraphicsContext</code> and related classes. It is vector-based (instead of raster) and supports the use of a transformation matrix which would make zooming, rotating, ... | 0 | 2016-09-05T18:13:08Z | [
"python",
"wxpython",
"zooming"
] |
Output dictionary data dynamically from a python for loop | 39,334,464 | <p>here, I am trying to spell check a txt file. first half of my code outputs original (var word) and corrected, if any, (var spell(word)). my replacement code uses a data structure like <code>{'zero':'0', 'temp':'bob', 'garbage':'nothing', 'garnvsh': 'garnish'}</code>. Now I would like to produce the same data structu... | 0 | 2016-09-05T16:22:11Z | 39,334,526 | <p>I suppose you want to <a href="http://stackoverflow.com/a/14507637/1040597">create dictionary</a> which its keys are <code>word</code> and values are <code>spell(word)</code>.</p>
<pre><code>my_dict = { word: spell(word) for word in zen.words }
</code></pre>
| 1 | 2016-09-05T16:26:40Z | [
"python"
] |
Find all substrings of a really long string - Memory error | 39,334,480 | <p>I was solving a problem in hackerrank and it required me to create a list that can store millions of values.<br>
And when I created a list in the normal way, but it is giving me "Memory Error" </p>
<p><a href="http://stackoverflow.com/questions/4800858/filtering-iterating-thru-very-large-lists-in-python">I have... | 1 | 2016-09-05T16:23:02Z | 39,334,627 | <p>As far as I can tell, <code>list3</code> is completely unnecessary. You are likely running out of memory because if all elements in the first list are unique, you've doubled the required storage space to solve the problem. </p>
<p>Option 1) You can check if the substring is already in the list in the first loop</p>... | 1 | 2016-09-05T16:33:43Z | [
"python",
"python-3.x"
] |
string(array) vs string(list) in python | 39,334,498 | <p>I was constructing a database for a deep learning algorithm. The points I'm interested in are these:</p>
<pre><code>with open(fname, 'a+') as f:
f.write("intens: " + str(mean_intensity_this_object) + "," + "\n")
f.write("distances: " + str(dists_this_object) + "," + "\n")
</code></pre>
<p>Where <code>mean_... | -1 | 2016-09-05T16:24:04Z | 39,336,261 | <p>In an interactive Python session:</p>
<pre><code>>>> import numpy as np
>>> x = np.arange(10)/.33 # make an array of floats
>>> x
array([ 0. , 3.03030303, 6.06060606, 9.09090909,
12.12121212, 15.15151515, 18.18181818, 21.21212121,
24.24242424, 27.27272... | 0 | 2016-09-05T18:55:11Z | [
"python",
"arrays",
"string",
"list",
"numpy"
] |
string(array) vs string(list) in python | 39,334,498 | <p>I was constructing a database for a deep learning algorithm. The points I'm interested in are these:</p>
<pre><code>with open(fname, 'a+') as f:
f.write("intens: " + str(mean_intensity_this_object) + "," + "\n")
f.write("distances: " + str(dists_this_object) + "," + "\n")
</code></pre>
<p>Where <code>mean_... | -1 | 2016-09-05T16:24:04Z | 39,352,837 | <p>Actually python converts both in the same way: <code>str(object)</code> calls <code>object.__str__()</code> or <code>object.__repr__()</code> if the former does not exist. From that point it is the responsibility of <code>object</code> to provide its string representation.</p>
<p>Python lists and numpy arrays are d... | 0 | 2016-09-06T15:34:54Z | [
"python",
"arrays",
"string",
"list",
"numpy"
] |
Python && And Conditional Not Working | 39,334,518 | <p>I'm looking to extract lines of a CSV file that meet BOTH conditions.</p>
<p>For example, I want to extract a line which features a certain unique code AND a specific date.</p>
<p>Currently, my code is only extracting lines which meet ONE of the conditions:</p>
<p>for line in log:</p>
<pre><code>with open("log.c... | 1 | 2016-09-05T16:25:43Z | 39,334,547 | <p>try</p>
<pre><code>if "code123" in line and "29/07/2016" in line:
</code></pre>
<p>Since <code>and</code> returns <code>False</code> or the last operand, ie.</p>
<pre><code>x and y == y # iff bool(x) is True and bool(y) is True
</code></pre>
<p>this part</p>
<pre><code>("code123" and "29/07/2016")
</code></pr... | 0 | 2016-09-05T16:28:07Z | [
"python",
"conditional",
"extraction",
"conditional-operator",
"data-extraction"
] |
Python Pandas read_excel doesn't recognize null cell | 39,334,543 | <p>My excel sheet:</p>
<pre><code> A B
1 first second
2
3
4 x y
5 z j
</code></pre>
<p>Python code:</p>
<pre><code>df = pd.read_excel (filename, parse_cols=1)
</code></pre>
<p>return a correct output:</p>
<pre><code> first second
0 NaN NaN
1 NaN NaN
2 x y
3 z j
</code></pre>
<p>If i wa... | 3 | 2016-09-05T16:27:47Z | 39,334,616 | <p>For me works parameter <code>skip_blank_lines=False</code>:</p>
<pre><code>df = pd.read_excel ('test.xlsx',
parse_cols=1,
skip_blank_lines=False)
print (df)
A B
0 first second
1 NaN NaN
2 NaN NaN
3 x y
4 z j
</code></pre... | 4 | 2016-09-05T16:33:03Z | [
"python",
"excel",
"pandas",
null
] |
Pass Python object directly to C++ program without using subprocess | 39,334,586 | <p>I have a C++ program that, through the terminal, takes a text file as input and produces another text file. I'm executing this program from a Python script which first produces said text string, stores it to a file, runs the C++ program as a subprocess with the created file as input and parses the output text file b... | 0 | 2016-09-05T16:30:40Z | 39,334,642 | <p>You can use <a href="https://docs.python.org/3.5/library/ctypes.html" rel="nofollow">ctypes</a>.<br>
It requires the C++ function to be wrapped with <code>extern "c"</code> and compiled as C code.</p>
<p>Say your C++ function looks like that:</p>
<pre><code>char* changeString(char* someString)
{
// do somethin... | 2 | 2016-09-05T16:34:23Z | [
"python",
"c++"
] |
Why is this Django URL resolution not working | 39,334,609 | <p>I have the following Django url configuration in /urls.py file </p>
<pre><code>from django.conf.urls import url
from django.conf.urls import include, url
from django.contrib import admin
import core
import core.views as coreviews
urlpatterns = [
#url(r'^admin/', admin.site.urls),
#url(r'^create/$', corevie... | 0 | 2016-09-05T16:32:33Z | 39,334,634 | <p>Because you're terminating the including url pattern with a $, which means the end of the pattern. Nothing can match past that. Remove those characters:</p>
<pre><code>url(r'^create/', include('core.urls')),
url(r'', include('core.urls')),
</code></pre>
| 2 | 2016-09-05T16:34:08Z | [
"python",
"django",
"django-views"
] |
Print the structure of large nested dictionaries in a compact way without printing all elements | 39,334,638 | <p>I have a large nested dictionary and I want to print its structure and one sample element in each level. </p>
<p>For example:</p>
<pre><code>from collections import defaultdict
nested = defaultdict(dict)
for i in range(10):
for j in range(20):
nested['key'+str(i)]['subkey'+str(j)] = {'var1': 'value1', 'var2'... | 3 | 2016-09-05T16:34:16Z | 39,334,848 | <p>A basic solution is to just set up your own nested function that will loop through and detect values to print only the first item it finds from each. Since dictionaries aren't ordered, this does mean it will randomly pick one. So your goal is inherently complicated if you want it to intelligently separate different ... | 1 | 2016-09-05T16:51:45Z | [
"python",
"dictionary",
"printing"
] |
How to solve this equation with SciPy | 39,334,656 | <p>In MathCad it looks like this:</p>
<p><a href="http://i.stack.imgur.com/8rWer.png" rel="nofollow"><img src="http://i.stack.imgur.com/8rWer.png" alt="enter image description here"></a></p>
<p>How to solve it using python (scipy or sympy)?</p>
<p>Maybe something like this?</p>
<pre><code>def fun(n):
x, y, z = ... | -2 | 2016-09-05T16:36:14Z | 39,336,017 | <h3>Code</h3>
<p>The important thing (for this scipy.minimize based approach) is the quadratic penalization of the error (which is the difference of both sides). Of course there are other approaches, but be careful to bound the objective.</p>
<pre><code>from scipy.optimize import minimize
fun = lambda x: ((-0.7353 +... | 2 | 2016-09-05T18:33:33Z | [
"python",
"numpy",
"scipy",
"sympy"
] |
Output of a Python input into C program | 39,334,694 | <p>Is it possible to do this? Output of a Python as input into C program.</p>
<p>You believe me if I say that this code before works?
Now it doesn't work. How can I make it work?</p>
<pre><code>python -c 'print "a" ' | ./myProgram
</code></pre>
<p>Simple example for myProgram:</p>
<pre><code>#include <stdio.h>... | 0 | 2016-09-05T16:40:13Z | 39,336,745 | <p>The input to your <code>C</code> code should be taken by <code>scanf</code>.</p>
<p>C code: <code>[test.c]</code></p>
<pre><code>#include <stdio.h>
int main() {
int x;
scanf("%d",&x);
printf("Value is %d\n",x);
}
</code></pre>
<p>Compile:</p>
<p><code>gcc test.c -o foo</code></p>
<p>Python... | 1 | 2016-09-05T19:40:28Z | [
"python",
"terminal",
"pipe"
] |
wxPython listctrl: allowing sorting for only some columns | 39,334,696 | <p>I have a table displayed using <code>wx.ListCtrl</code>. I want all the columns to be sortable upon clicking the column headers except for the first column which stores the row index (e.g., 0,1,2,3,...). So that means, if a user clicks on the first column's header, the table should not be sorted. But <code>ColumnSor... | 0 | 2016-09-05T16:40:16Z | 39,343,280 | <p>I don't know if there is a prettier way of handling this. Anyway, following is my approach:</p>
<pre><code>class MyColumnSorterMixin(listmix.ColumnSorterMixin):
def GetColumnSorter(self):
if self._col <> 0:
return listmix.ColumnSorterMixin.GetColumnSorter(self)
</code></pre>
<p>Remem... | 1 | 2016-09-06T07:42:31Z | [
"python",
"wxpython",
"listctrl"
] |
How to make return do the same as print in python string | 39,334,704 | <pre><code>b = 'abbaab'
count = 0
width = 2
for k in range(0, len(b), width):
print b[k:k + width]
</code></pre>
<p>gives me</p>
<pre><code> ab
ba
ab
</code></pre>
<p>but I need to use return instead of print. I don't know how to store each line into something, the things I tried said index out of range.</p>
| -2 | 2016-09-05T16:40:52Z | 39,334,884 | <p><code>print</code> and <code>return</code> are very different.</p>
<p>Print is a function that will just print out something to the screen. return is a command that basically tells what value a function should return. For example:</p>
<pre><code>def func1():
print 1
def func2()
return 2
</code></pre>
<p>... | 0 | 2016-09-05T16:54:19Z | [
"python"
] |
How to make return do the same as print in python string | 39,334,704 | <pre><code>b = 'abbaab'
count = 0
width = 2
for k in range(0, len(b), width):
print b[k:k + width]
</code></pre>
<p>gives me</p>
<pre><code> ab
ba
ab
</code></pre>
<p>but I need to use return instead of print. I don't know how to store each line into something, the things I tried said index out of range.</p>
| -2 | 2016-09-05T16:40:52Z | 39,334,911 | <p>I think this will work , Solution in Python 2.7.6: </p>
<pre><code>def print_list(b):
count = 0
width = 2
for k in range(0, len(b), width):
yield b[k:k + width]
b = 'abbaab'
l = list(print_list(b))
for i in l:
print i
</code></pre>
<p><strong>Output</strong>:</p>
<pre><code>ab
ba
ab
</cod... | 1 | 2016-09-05T16:56:01Z | [
"python"
] |
How to make return do the same as print in python string | 39,334,704 | <pre><code>b = 'abbaab'
count = 0
width = 2
for k in range(0, len(b), width):
print b[k:k + width]
</code></pre>
<p>gives me</p>
<pre><code> ab
ba
ab
</code></pre>
<p>but I need to use return instead of print. I don't know how to store each line into something, the things I tried said index out of range.</p>
| -2 | 2016-09-05T16:40:52Z | 39,334,945 | <p>You want <code>return</code> to be same as <code>print</code>, <code>return</code> switches context from <code>callee</code> to <code>caller</code> function, with some value or none.
Whereas <code>print</code> is used to send some output to <code>console</code></p>
<p>They both cannot be same.</p>
<p>In your case,... | 0 | 2016-09-05T16:58:47Z | [
"python"
] |
pydbg 64 bit enumerate_processes() returning empty list | 39,334,795 | <p>I'm using pydbg binaries downloaded here: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pydbg" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#pydbg</a> as recommended in previous answers.</p>
<p>I can get the 32-bit version to work with a 32-bit Python interpreter, but I can't get the 64-bit versio... | 0 | 2016-09-05T16:47:08Z | 39,338,165 | <p>Pydbg defines the PROCESSENTRY32 structure wrong.</p>
<p>Better use a maintained package such as <a href="https://pythonhosted.org/psutil/#psutil.process_iter" rel="nofollow">psutil</a> or use ctypes directly, e.g.:</p>
<pre><code>from ctypes import windll, Structure, c_char, sizeof
from ctypes.wintypes import BOO... | 0 | 2016-09-05T22:00:53Z | [
"python",
"pydbg"
] |
Why is my python programme running correctly in my virtual environment despite not having the packages installed in that environment? | 39,334,854 | <p>Hi all I hope I can get some help with this. I am on Windows XP, using Python 2.7.12 and command prompt.</p>
<p>I have written a programme balances.py which uses <code>prettytable</code> package. This is installed in my main <code>C:\Python27\Lib\site-packages</code> folder.</p>
<p>I just created a virtual environ... | 2 | 2016-09-05T16:51:54Z | 39,334,909 | <p>You have installed prettytables globally. When you create a virtual environment it will include the globally installed packages hence the reason why your program is running. </p>
| 0 | 2016-09-05T16:55:47Z | [
"python",
"virtualenv"
] |
Why is my python programme running correctly in my virtual environment despite not having the packages installed in that environment? | 39,334,854 | <p>Hi all I hope I can get some help with this. I am on Windows XP, using Python 2.7.12 and command prompt.</p>
<p>I have written a programme balances.py which uses <code>prettytable</code> package. This is installed in my main <code>C:\Python27\Lib\site-packages</code> folder.</p>
<p>I just created a virtual environ... | 2 | 2016-09-05T16:51:54Z | 39,381,743 | <p>Someone has written an answer I found : </p>
<p>odie5533 answer on <a href="http://stackoverflow.com/questions/1382925/virtualenv-no-site-packages-and-pip-still-finding-global-packages">virtualenv --no-site-packages and pip still finding global packages?</a></p>
<p><strong>A similar problem can occur on Windows if... | 0 | 2016-09-08T02:34:33Z | [
"python",
"virtualenv"
] |
Parse only given values to command line via Python | 39,334,861 | <p>I'm sending I'm receiving a JSON message through MQTT in Python, and I would like to start a command line program with what the JSON gives as variables.</p>
<p>The problem with this is that I don't know what values are going to come through and thus this is where I have trouble.</p>
<p>The easiest would be if I kn... | 0 | 2016-09-05T16:52:41Z | 39,351,556 | <p>You can use a for loop to iterate over the json, and construct the command string.</p>
<pre><code> commandArgs = ["+f ","+g "]
commandCount=0
for element in data:
command= command + commandArgs[commandCount] + element
commandCount = commandCount +1
</code></pre>
| 1 | 2016-09-06T14:29:03Z | [
"python",
"json",
"mqtt"
] |
Parse only given values to command line via Python | 39,334,861 | <p>I'm sending I'm receiving a JSON message through MQTT in Python, and I would like to start a command line program with what the JSON gives as variables.</p>
<p>The problem with this is that I don't know what values are going to come through and thus this is where I have trouble.</p>
<p>The easiest would be if I kn... | 0 | 2016-09-05T16:52:41Z | 39,443,122 | <p>Although you <em>could</em> do this as described it's not something you <em>should</em> do. Running user-inputted commands is one of the most unsecure things a program can do. Scrubbing the commands thoroughly is possible but quite difficult to do comprehensively. The usual approach is to have a table of acceptab... | 1 | 2016-09-12T03:51:51Z | [
"python",
"json",
"mqtt"
] |
Regex ('foo'|'bar') notation | 39,334,868 | <p>I'm using regex to parse some time data, but my attempt is not matching as I would expect. Here's my code:</p>
<pre><code>import re
print re.findall("\d+:\d+ (am|pm)", "11:30 am - 2:20 pm")
</code></pre>
<p>This produces <code>['am', 'pm']</code>, not <code>['11:30 am', '2:20 pm']</code>, which is what I want.</p... | 2 | 2016-09-05T16:53:29Z | 39,334,914 | <p>Your problem relates to capturing groups. If you want to have non-capturing alternation use the regex <code>\d+:\d+ (?:am|pm)</code>.</p>
| 4 | 2016-09-05T16:56:07Z | [
"python",
"regex"
] |
Regex ('foo'|'bar') notation | 39,334,868 | <p>I'm using regex to parse some time data, but my attempt is not matching as I would expect. Here's my code:</p>
<pre><code>import re
print re.findall("\d+:\d+ (am|pm)", "11:30 am - 2:20 pm")
</code></pre>
<p>This produces <code>['am', 'pm']</code>, not <code>['11:30 am', '2:20 pm']</code>, which is what I want.</p... | 2 | 2016-09-05T16:53:29Z | 39,335,000 | <p><a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow">Quoting docs</a> (<strong>emphasis mine</strong>):</p>
<blockquote>
<p><code>re.findall(pattern, string, flags=0)</code></p>
<p>Return all non-overlapping matches of pattern in string, as a list of
strings. The string is scanned ... | 0 | 2016-09-05T17:02:34Z | [
"python",
"regex"
] |
Regex ('foo'|'bar') notation | 39,334,868 | <p>I'm using regex to parse some time data, but my attempt is not matching as I would expect. Here's my code:</p>
<pre><code>import re
print re.findall("\d+:\d+ (am|pm)", "11:30 am - 2:20 pm")
</code></pre>
<p>This produces <code>['am', 'pm']</code>, not <code>['11:30 am', '2:20 pm']</code>, which is what I want.</p... | 2 | 2016-09-05T16:53:29Z | 39,335,091 | <p>You probably don't even need regular expressions to split this particular string. If applicable, you can use the regular <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a>:</p>
<pre><code>>>> s = "11:30 am - 2:20 pm"
>>> s.split(" - ")
[... | 1 | 2016-09-05T17:10:20Z | [
"python",
"regex"
] |
In Matplotlib, upon mouse click event, fill the plot on the right of the mouse click | 39,334,874 | <p>I am new to programming and was wondering if I could get some expert assistance from the very helpful community on here.</p>
<p>I am trying to create a mouse click event upon which the entire area of the plot to the right of the mouse click gets shaded. So, I want the mouse click to register the x-value, create a v... | 2 | 2016-09-05T16:53:40Z | 39,335,287 | <h1>For your main question:</h1>
<p>Just add:</p>
<pre><code>plt.draw()
</code></pre>
<p>after all the updates you do (i.e before the <code>return</code> of <code>onClick</code>).</p>
<h1>For your seconed question:</h1>
<p>You can use (on <code>ax5</code> for example):</p>
<pre><code>ax5.get_xlim()[1]
</code></pr... | 1 | 2016-09-05T17:28:11Z | [
"python",
"matplotlib",
"mouseclick-event"
] |
paramiko - How can I refresh the modified date of a file on the SFTP server automatically? | 39,334,889 | <p>I have a file on the SFTP server that should be imported with <strong>paramiko</strong> package on certain conditions. Until these conditions aren't fulfilled, this file should stay on the server unimported, but its modified date shoud be updated, so that this date should be always bigger than the time, at which fil... | 0 | 2016-09-05T16:54:48Z | 39,334,890 | <p>This can be done with copying the file from the SFTP to the local host, removing the file from the SFTP and copying it again to the SFTP.</p>
<p>So,</p>
<ol>
<li><code>get(remotepath, localpath, callback=None)</code></li>
<li><code>remove(path)</code></li>
<li><code>put(localpath, remotepath, callback=None, confir... | 0 | 2016-09-05T16:54:48Z | [
"python",
"sftp",
"paramiko",
"last-modified"
] |
paramiko - How can I refresh the modified date of a file on the SFTP server automatically? | 39,334,889 | <p>I have a file on the SFTP server that should be imported with <strong>paramiko</strong> package on certain conditions. Until these conditions aren't fulfilled, this file should stay on the server unimported, but its modified date shoud be updated, so that this date should be always bigger than the time, at which fil... | 0 | 2016-09-05T16:54:48Z | 39,334,953 | <p>I would try opening the file in append mode ("a") and closing it immediately.</p>
| 0 | 2016-09-05T16:59:30Z | [
"python",
"sftp",
"paramiko",
"last-modified"
] |
paramiko - How can I refresh the modified date of a file on the SFTP server automatically? | 39,334,889 | <p>I have a file on the SFTP server that should be imported with <strong>paramiko</strong> package on certain conditions. Until these conditions aren't fulfilled, this file should stay on the server unimported, but its modified date shoud be updated, so that this date should be always bigger than the time, at which fil... | 0 | 2016-09-05T16:54:48Z | 39,342,187 | <p>There's the <a href="http://docs.paramiko.org/en/2.0/api/sftp.html#paramiko.sftp_client.SFTPClient.utime" rel="nofollow"><code>utime</code> method</a>:</p>
<pre><code> utime(path, times)
</code></pre>
<blockquote>
<p>Set the access and modified times of the file specified by <code>path</code>. If <code>times</co... | 1 | 2016-09-06T06:43:43Z | [
"python",
"sftp",
"paramiko",
"last-modified"
] |
How to make triangle x in python from source code below | 39,334,916 | <p>Hello I want to ask everybody...
Like this...
I want to make a triangle X or *, like below:</p>
<pre><code> *
***
*****
*******
*********
</code></pre>
<p>My Algorithm is like this:</p>
<pre><code>for y:=1 to i do
for x:=1 to j do
for j-x to 1 do write(' ');
for i to 2*(x-1)+1 do write(... | -3 | 2016-09-05T16:56:17Z | 39,334,947 | <p>I have some code to do that lying around here, maybe this can help you :)</p>
<pre><code>def pascals_triangle(order):
"""
:brief: Compute the line of pascal's triangle with order 'order'
| line | order |
|---------------------|-------|
... | 1 | 2016-09-05T16:59:05Z | [
"python",
"algorithm",
"pascal"
] |
How to make triangle x in python from source code below | 39,334,916 | <p>Hello I want to ask everybody...
Like this...
I want to make a triangle X or *, like below:</p>
<pre><code> *
***
*****
*******
*********
</code></pre>
<p>My Algorithm is like this:</p>
<pre><code>for y:=1 to i do
for x:=1 to j do
for j-x to 1 do write(' ');
for i to 2*(x-1)+1 do write(... | -3 | 2016-09-05T16:56:17Z | 39,335,077 | <p>You can simply do this like that:</p>
<pre><code>def triangle(lines):
for i in range(lines):
print(' '*(lines-i) + '*'*(i*2+1))
triangle(5)
</code></pre>
<p>Output as expected</p>
<pre><code> *
***
*****
*******
*********
</code></pre>
| 3 | 2016-09-05T17:09:10Z | [
"python",
"algorithm",
"pascal"
] |
How to make triangle x in python from source code below | 39,334,916 | <p>Hello I want to ask everybody...
Like this...
I want to make a triangle X or *, like below:</p>
<pre><code> *
***
*****
*******
*********
</code></pre>
<p>My Algorithm is like this:</p>
<pre><code>for y:=1 to i do
for x:=1 to j do
for j-x to 1 do write(' ');
for i to 2*(x-1)+1 do write(... | -3 | 2016-09-05T16:56:17Z | 39,335,164 | <p>Here's a possible solution:</p>
<pre><code>def print_pascals_triangle(levels, debug_char=None):
triangle = []
for order in range(levels):
line = [debug_char] if debug_char is not None else [1]
for k in range(order):
if debug_char is None:
value = line[k] * (order... | 1 | 2016-09-05T17:17:45Z | [
"python",
"algorithm",
"pascal"
] |
How do I organise a nested list representing coordinate-values to a coordinate-list | 39,334,935 | <p>I would like to change my data-structure that get from my data-files in such a way that I get a list of all coordinate-values for every coordinates (so a list for all coordinates filled with values)</p>
<p>e.g.
for i in range (files):</p>
<h3>open file</h3>
<pre><code>file_output = [[0,4,6],[9,4,1],[2,5,3]]
</cod... | 0 | 2016-09-05T16:57:48Z | 39,334,970 | <pre><code>>>> a = [[0,4,6],[9,4,1],[2,5,3]]
>>> b = [[6,1,8],[4,7,3],[3,7,0]]
>>> from itertools import chain
>>> zip(chain(*a),chain(*b))
[(0, 6), (4, 1), (6, 8), (9, 4), (4, 7), (1, 3), (2, 3), (5, 7), (3, 0)]
>>>
</code></pre>
| 0 | 2016-09-05T17:00:45Z | [
"python",
"list",
"structure",
"coordinates"
] |
How do I organise a nested list representing coordinate-values to a coordinate-list | 39,334,935 | <p>I would like to change my data-structure that get from my data-files in such a way that I get a list of all coordinate-values for every coordinates (so a list for all coordinates filled with values)</p>
<p>e.g.
for i in range (files):</p>
<h3>open file</h3>
<pre><code>file_output = [[0,4,6],[9,4,1],[2,5,3]]
</cod... | 0 | 2016-09-05T16:57:48Z | 39,334,976 | <p>This should be useful.</p>
<pre><code>[zip(i,j) for i in a for j in b]
</code></pre>
<p>However it provides list of tuples, which should satisfy your needs.</p>
<p>If there will only be two lists, you can use this as well.</p>
<pre><code>[[i, j] for i in a for j in b]
</code></pre>
| 0 | 2016-09-05T17:00:58Z | [
"python",
"list",
"structure",
"coordinates"
] |
How do I organise a nested list representing coordinate-values to a coordinate-list | 39,334,935 | <p>I would like to change my data-structure that get from my data-files in such a way that I get a list of all coordinate-values for every coordinates (so a list for all coordinates filled with values)</p>
<p>e.g.
for i in range (files):</p>
<h3>open file</h3>
<pre><code>file_output = [[0,4,6],[9,4,1],[2,5,3]]
</cod... | 0 | 2016-09-05T16:57:48Z | 39,334,994 | <p>You could also explore the built-in <strong><a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip()</code></a></strong> function</p>
<pre><code>>>> l = []
>>> for k,v in zip(a,b):
l.append(zip(k,v))
>>> print l
[[0,6],[4,1],[6,8],[9,4],[4,7],[1,3]... | 1 | 2016-09-05T17:01:52Z | [
"python",
"list",
"structure",
"coordinates"
] |
Tkinter: How to add kwargs to a class you inherit from? | 39,335,013 | <p>How do I add keyword arguments (<a href="http://effbot.org/tkinterbook/frame.htm" rel="nofollow">**options</a>) to a Tkinter class that inherits from <code>tk.Frame</code>? For example, all I want to do is set the frame's <code>width</code> and <code>height</code> (or any other options).</p>
<p>The broader question... | 0 | 2016-09-05T17:03:22Z | 39,335,053 | <p>Just add what you want to add directly, without adding it to <code>kwargs</code>:</p>
<pre><code>class profiles(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, width=900, height=800, *args, **kwargs)
</code></pre>
| 0 | 2016-09-05T17:06:07Z | [
"python",
"class",
"tkinter"
] |
Tkinter: How to add kwargs to a class you inherit from? | 39,335,013 | <p>How do I add keyword arguments (<a href="http://effbot.org/tkinterbook/frame.htm" rel="nofollow">**options</a>) to a Tkinter class that inherits from <code>tk.Frame</code>? For example, all I want to do is set the frame's <code>width</code> and <code>height</code> (or any other options).</p>
<p>The broader question... | 0 | 2016-09-05T17:03:22Z | 39,335,119 | <p>You would do it like this:</p>
<pre><code>class Profiles(tk.Frame):
def __init__(self, parent, *args, **kwargs):
self.parent = parent
kwargs.update(width=900, height=600)
super(profiles, self).__init__(parent, *args, **kwargs)
</code></pre>
<p>This will override the keywords if they wer... | 0 | 2016-09-05T17:13:16Z | [
"python",
"class",
"tkinter"
] |
How do I make all elements of a webpage appear in the source? | 39,335,106 | <p>When I press "view-source" (in chrome) of certain webpages, I get some thinned-version of an html, opposed to the more rich version I get when I press "inspect". </p>
<p>I think some content (maybe the scripts) are hidden when you view the source code, and all you get is the script code and not what it translates i... | -2 | 2016-09-05T17:11:33Z | 39,343,908 | <p>What "Show Source" does is give you the actual raw original source file that the browser received from the server. What you see in your browser and what the <em>Element Inspector</em> shows you is the current state of the DOM, these days often heavily modified at runtime by Javascript. </p>
<p>source = what the pag... | 3 | 2016-09-06T08:15:05Z | [
"javascript",
"python",
"html",
"element",
"inspect"
] |
if negative then with weighted average | 39,335,149 | <p>I have a DataFrame:</p>
<pre><code>a = {'Price': [10, 15, 20, 25, 30], 'Total': [10000, 12000, 15000, 14000, 10000],
'Previous Quarter': [0, 10000, 12000, 15000, 14000]}
a = pd.DataFrame(a)
print (a)
</code></pre>
<p>With this raw data, i have added a number of additional columns including a weighted average pric... | 2 | 2016-09-05T17:16:04Z | 39,335,417 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cummax.html" rel="nofollow"><code>cummax</code></a>: </p>
<pre><code>a['WAP'] = (a['Cum Sum Amount'] / a['Total']).cummax()
print (a['WAP'])
0 10.000000
1 10.833333
2 12.666667
3 12.666667
4 12.666667
Name: W... | 3 | 2016-09-05T17:39:12Z | [
"python",
"pandas"
] |
if negative then with weighted average | 39,335,149 | <p>I have a DataFrame:</p>
<pre><code>a = {'Price': [10, 15, 20, 25, 30], 'Total': [10000, 12000, 15000, 14000, 10000],
'Previous Quarter': [0, 10000, 12000, 15000, 14000]}
a = pd.DataFrame(a)
print (a)
</code></pre>
<p>With this raw data, i have added a number of additional columns including a weighted average pric... | 2 | 2016-09-05T17:16:04Z | 39,335,542 | <p>As a total Python beginner, here are two options I could think of</p>
<p>Either</p>
<pre><code>a['WAP'] = np.maximum.accumulate(a['Cum Sum Amount'] / a['Total'])
</code></pre>
<p>Or after you've already created <code>WAP</code> you could modify only the subset using the <code>diff</code> method (thanks to @ayhan ... | 1 | 2016-09-05T17:51:47Z | [
"python",
"pandas"
] |
Counting repeated (duplicated) in a list using dictionary | 39,335,188 | <p>I'm writing a program to identify repeated values and their count in a particular column (named 'StrId') in an Excel spreadsheet. Besides finding repetitions, I need to know how many times each value is repeated.</p>
<p>The Excel data was processed as a list of dictionaries (one dictionary per row) with headers as ... | -1 | 2016-09-05T17:19:21Z | 39,335,273 | <p>Here's a possible solution:</p>
<pre><code>from collections import defaultdict
excel_data = [
{'StrId': 2, 'ProjId': 984},
{'StrId': 2, 'ProjId': 984},
{'StrId': 2, 'ProjId': 984},
{'StrId': 2, 'ProjId': 984},
{'StrId': 1, 'ProjId': 358},
{'StrId': 1, 'ProjId': 358},
{'StrId': 1, 'ProjI... | 0 | 2016-09-05T17:26:28Z | [
"python",
"excel",
"dictionary",
"duplicates"
] |
Counting repeated (duplicated) in a list using dictionary | 39,335,188 | <p>I'm writing a program to identify repeated values and their count in a particular column (named 'StrId') in an Excel spreadsheet. Besides finding repetitions, I need to know how many times each value is repeated.</p>
<p>The Excel data was processed as a list of dictionaries (one dictionary per row) with headers as ... | -1 | 2016-09-05T17:19:21Z | 39,335,320 | <p>You can use Python's <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> for this. I'm assuming your <code>excel_data</code> is structured as a list of lists with one dictionary per list, but let me know if it's not the case.</p>
<pre><code>from c... | 1 | 2016-09-05T17:31:00Z | [
"python",
"excel",
"dictionary",
"duplicates"
] |
Counting repeated (duplicated) in a list using dictionary | 39,335,188 | <p>I'm writing a program to identify repeated values and their count in a particular column (named 'StrId') in an Excel spreadsheet. Besides finding repetitions, I need to know how many times each value is repeated.</p>
<p>The Excel data was processed as a list of dictionaries (one dictionary per row) with headers as ... | -1 | 2016-09-05T17:19:21Z | 39,339,385 | <p>If the sublists can contain more than one dict you can flatten the sublists with <em>itertools.chain</em> :</p>
<pre><code>from collections import Counter
excel_data = [
[{'StrId': 1, 'ProjId': 358},{'StrId': 5, 'ProjId': 358}],
[{'StrId': 2, 'ProjId': 984},{'StrId': 3, 'ProjId': 358}],
[{'StrId': 2, 'P... | 1 | 2016-09-06T01:20:51Z | [
"python",
"excel",
"dictionary",
"duplicates"
] |
Append new lines to the existing file in Pandas dataframe | 39,335,303 | <p>I have a python script that runs a query and stores it in a dataframe as below:</p>
<pre><code> df = pd.read_gbq(queryString, project_id=PROJECT)
out = df.to_json(orient='records')[1:-1].replace('},{', '}\n{')
</code></pre>
<p>After some processing, I current store it in a json file:</p>
<pre><code>with open('/... | 0 | 2016-09-05T17:29:36Z | 39,335,368 | <p>Try this: </p>
<pre><code>with open('/home/user/Downloads/Count1/Count.json', 'ab') as f:
f.write(out)
</code></pre>
| 3 | 2016-09-05T17:34:33Z | [
"python",
"file",
"dataframe"
] |
Remove several rows with zero values in a dataframe using python | 39,335,350 | <p>HI everybody i need some help with python. </p>
<p>I'm working with an excel with several rows, some of this rows has zero value in all the columns, so i need to delete that rows. </p>
<pre><code>In
id a b c d
a 0 1 5 0
b 0 0 0 0
c 0 0 0 0
d 0 0 0 1
e 1 0 0 1
Out
id a b c d
a 0 1 5 0
d 0 0 0 1 ... | 0 | 2016-09-05T17:33:13Z | 39,335,433 | <p>For this dataframe:</p>
<pre><code>df
Out:
id a b c d e
0 a 2 0 2 0 1
1 b 1 0 1 1 1
2 c 1 0 0 0 1
3 d 2 0 2 0 2
4 e 0 0 0 0 2
5 f 0 0 0 0 0
6 g 0 2 1 0 2
7 h 0 0 0 0 0
8 i 1 2 2 0 2
9 j 2 2 1 2 1
</code></pre>
<p>Temporarily set the index:</p>
<p... | 2 | 2016-09-05T17:40:53Z | [
"python",
"excel",
"dataframe"
] |
Remove several rows with zero values in a dataframe using python | 39,335,350 | <p>HI everybody i need some help with python. </p>
<p>I'm working with an excel with several rows, some of this rows has zero value in all the columns, so i need to delete that rows. </p>
<pre><code>In
id a b c d
a 0 1 5 0
b 0 0 0 0
c 0 0 0 0
d 0 0 0 1
e 1 0 0 1
Out
id a b c d
a 0 1 5 0
d 0 0 0 1 ... | 0 | 2016-09-05T17:33:13Z | 39,335,439 | <p>Given your input you can group by whether all the columns are zero or not, then access them, eg:</p>
<pre><code>groups = df.groupby((df.drop('id', axis= 1) == 0).all(axis=1))
all_zero = groups.get_group(True)
non_all_zero = groups.get_group(False)
</code></pre>
| 2 | 2016-09-05T17:41:18Z | [
"python",
"excel",
"dataframe"
] |
Conversion of Strings to list | 39,335,491 | <p>Can someone please help me with a simple code that returns a list as an output to list converted to string? The list is NOT like this:</p>
<pre><code>a = u"['a','b','c']"
</code></pre>
<p>but the variable is like this: </p>
<pre><code>a = '[a,b,c]'
</code></pre>
<p>So,</p>
<pre><code>list(a)
</code></pre>
<p>w... | 1 | 2016-09-05T17:46:09Z | 39,335,514 | <p>There is no standard library that'll load such a list. But you can trivially do this with string processing:</p>
<pre><code>a.strip('[]').split(',')
</code></pre>
<p>would give you your list.</p>
<p><code>str.strip()</code> will remove <em>any</em> of the given characters from the start and end; so it'll remove a... | 2 | 2016-09-05T17:48:42Z | [
"python",
"python-2.7"
] |
Conversion of Strings to list | 39,335,491 | <p>Can someone please help me with a simple code that returns a list as an output to list converted to string? The list is NOT like this:</p>
<pre><code>a = u"['a','b','c']"
</code></pre>
<p>but the variable is like this: </p>
<pre><code>a = '[a,b,c]'
</code></pre>
<p>So,</p>
<pre><code>list(a)
</code></pre>
<p>w... | 1 | 2016-09-05T17:46:09Z | 39,335,772 | <p>Let us use hack.</p>
<pre><code>import string
x = "[a,b,c]"
for char in x:
if char in string.ascii_lowercase:
x = x.replace(char, "'%s'" % char)
# Now x is "['a', 'b', 'c']"
lst = eval(x)
</code></pre>
<p>This checks if a character is in the alphabet(lowercase) if it is, it replaces it with a charac... | 0 | 2016-09-05T18:09:27Z | [
"python",
"python-2.7"
] |
ElasticSearch bulk update: organizing JSON using python script | 39,335,493 | <p>So I am trying to index some public Amazon data set (products) into my ElasticSearch.</p>
<p>I have a very large JSON file for data (9.9 Gigabytes). I have splitted the file into various smaller files (for memory's sake), and now each file has the following structure:</p>
<pre><code>{"asin": "0001048791", "salesRa... | 0 | 2016-09-05T17:46:17Z | 39,337,759 | <p>I don't get the same results when I run the following which tries to reproduce the problem:</p>
<pre><code>import json
import sys
json_in =(
"""{"asin": "0001048791", "salesRank": {"Books": 6334800}, "imUrl": "http://ecx.images-amazon.com/images/I/51MKP0T4DBL.jpg", "categories": [["Books"]], "title": "The Cruc... | 0 | 2016-09-05T21:13:39Z | [
"python",
"json",
"elasticsearch"
] |
Set up multiple session handlers on python webapp2 | 39,335,513 | <p>I'm writing a simple web application in google appengine and python. In this application I need to handle two types of sessions:
the "long term session" that stores information about users, current page ecc, with long max_age parameter and the "short term session" with max_age about 20 minutes that keep an access to... | 0 | 2016-09-05T17:48:20Z | 39,336,309 | <p>Try setting your config params: </p>
<pre><code>config = {}
config['webapp2_extras.sessions'] = {
'session_max_age': 100000, # try None here also, though that is the default
}
app = webapp2.WSGIApplication([
('/', HomeHandler),
], debug=True, config=config)
</code></pre>
| 0 | 2016-09-05T18:59:36Z | [
"python",
"google-app-engine",
"session",
"webapp2"
] |
Label smoothing (soft targets) in Pandas | 39,335,535 | <p>In Pandas there is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>get_dummies</code></a> method that one-hot encodes categorical variable. Now I want to do label smoothing as described in section 7.5.1 of <a href="http://www.deeplearningbook.org/" rel="no... | 0 | 2016-09-05T17:50:31Z | 39,335,797 | <p>First, lets use much simpler equation (<code>ϵ</code> denotes how much probability mass you move from "true label" and distribute to all remaining ones).</p>
<pre><code>1 -> 1 - ϵ
0 -> ϵ / (k-1)
</code></pre>
<p>You can simply use nice mathematical property of the above, since all you have to do is</p>
... | 2 | 2016-09-05T18:11:33Z | [
"python",
"pandas",
"machine-learning"
] |
I don't understand why i get difference answer by change put line if on in code | 39,335,612 | <p>I would write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example <code>s = 'azcbobobegghakl'</code>
will print out <code>'beggh'</code>.</p>
<pre><code>s = 'azcbobobegghakl'
result = ''
word ='a'
sen = ''
for alpha in s:
if alpha < word:
word ... | -1 | 2016-09-05T17:57:01Z | 39,335,745 | <p>You are discarding the first character of the new sequence</p>
<pre><code>s = 'azcbobobegghakl'
result = ''
word ='a'
sen = ''
for alpha in s:
print alpha,word,sen
if alpha >= word:
word = alpha
sen += alpha
if len(result) <len(sen):
result = sen
if alpha < word:
... | 0 | 2016-09-05T18:07:07Z | [
"python"
] |
I don't understand why i get difference answer by change put line if on in code | 39,335,612 | <p>I would write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example <code>s = 'azcbobobegghakl'</code>
will print out <code>'beggh'</code>.</p>
<pre><code>s = 'azcbobobegghakl'
result = ''
word ='a'
sen = ''
for alpha in s:
if alpha < word:
word ... | -1 | 2016-09-05T17:57:01Z | 39,335,751 | <p>Ok, let's say you got a couple of functions f1 and f2 and you're tracking every iteration of your for loop like this:</p>
<pre><code>def f1(s):
result = ''
word = 'a'
sen = ''
for index, alpha in enumerate(s):
if alpha < word:
word = 'a'
sen = ''
if alpha &... | 0 | 2016-09-05T18:07:45Z | [
"python"
] |
SQLAlchemy: Trigger not firing on INSERT | 39,335,704 | <p>I have a problem with a trigger that doesn't fire through a <code>.merge()</code> call in SQLAlchemy. <br>
I have the following trigger:</p>
<pre><code>CREATE TRIGGER trigger_update_comment_count
BEFORE INSERT ON mediacomment
FOR EACH ROW
EXECUTE PROCEDURE update_comment_count();
</code></pre>
<p>The trigger execu... | 1 | 2016-09-05T18:03:56Z | 39,353,868 | <p>I figured it out by enabling logging and examining the log files in <code>pg_log</code>. The reason was that the transaction with the <code>INSERT</code>, that should have fired the trigger, was being rolled back.</p>
| 0 | 2016-09-06T16:34:13Z | [
"python",
"postgresql",
"sqlalchemy"
] |
how to use counter on dictonary values are list items | 39,335,766 | <p>My defaultdict is as follows:</p>
<pre><code>defaultdict(<class 'list'>, {'DrJillStein': [18021496, 30576467, 35175054, 122130797, 227720229, 289019104, 441389311, 456794981, 774180818,763849988988211200], 'realDonaldTrump': [14669951, 22203756, 41634520, 50769180, 75541946, 245963716, 475802156, 2325495378, ... | 1 | 2016-09-05T18:08:57Z | 39,335,907 | <p>Initialize a <code>Counter</code> from <code>collections</code> and ask for the 5 <code>most_common</code>.</p>
<p>In order to initialize the <code>Counter</code> just provide it with a comprehension:</p>
<pre><code>c = Counter(v for sub in d.values() for v in sub)
</code></pre>
<p>I added an extra <code>id</code... | 2 | 2016-09-05T18:23:26Z | [
"python",
"list",
"python-3.x",
"dictionary",
"counter"
] |
NameError -- imported modules when script is broken down in multiple python files | 39,335,948 | <p>It is hard to find a title for this question and hopefully this thread is not a duplicate. </p>
<p>I was writing that long script in Python 2.7 (using PyCharm 2016.2.2) for a project and decided to split it in different .py files which I could then import into a main file. </p>
<p>Unfortunately, it seems that when... | 0 | 2016-09-05T18:27:38Z | 39,336,027 | <p>The <code>numpy</code> module imported in <code>basic.py</code> has a reference defined only withing <code>basic.py</code> scope. You have to explictly import <code>numpy</code> everywhere you use it.</p>
<pre><code>import basic.py
import numpy
numpy.random.seed(7)
import load_data.py
</code></pre>
| 0 | 2016-09-05T18:34:19Z | [
"python",
"python-2.7"
] |
QLabel font differs when inserting a short HTML text | 39,335,955 | <p>I have noticed that the font size of a <code>QLabel()</code> in a PyQt GUI is not very consistent. Let's take a look at the following example. I've written a complete python file for a quick test. It will pop up a Qt window with two labels:</p>
<pre><code>from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
fro... | 1 | 2016-09-05T18:28:07Z | 39,336,023 | <p>I think I found the answer.</p>
<p>Replace the html snippet by:</p>
<pre><code> self.infoTxt = \
'<html> \
<head> \
</head> \
<body> \
<p style="margin-left:8px; font-size:10pt">My html text, font = 10pt</p> \
</body> \
</html> '
</code... | 0 | 2016-09-05T18:33:53Z | [
"python",
"html",
"qt",
"pyqt",
"pyqt5"
] |
QLabel font differs when inserting a short HTML text | 39,335,955 | <p>I have noticed that the font size of a <code>QLabel()</code> in a PyQt GUI is not very consistent. Let's take a look at the following example. I've written a complete python file for a quick test. It will pop up a Qt window with two labels:</p>
<pre><code>from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
fro... | 1 | 2016-09-05T18:28:07Z | 39,336,089 | <p>As you've already discovered it seems you need to use style instead. More info about it here:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font</a></li>
<li><a href="http://www.w3schools.com/tags/tag_fo... | 1 | 2016-09-05T18:40:15Z | [
"python",
"html",
"qt",
"pyqt",
"pyqt5"
] |
QLabel font differs when inserting a short HTML text | 39,335,955 | <p>I have noticed that the font size of a <code>QLabel()</code> in a PyQt GUI is not very consistent. Let's take a look at the following example. I've written a complete python file for a quick test. It will pop up a Qt window with two labels:</p>
<pre><code>from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
fro... | 1 | 2016-09-05T18:28:07Z | 39,336,933 | <p>The <code>font</code> tag is still fully supported in both Qt4 and Qt5. The fact that it has been made obsolete by the current HTML standard is irrelevant, because Qt has only ever supported <a href="http://doc.qt.io/qt-5/richtext-html-subset.html" rel="nofollow">a limited subset of HTML4</a>.</p>
<p>The real probl... | 2 | 2016-09-05T19:55:42Z | [
"python",
"html",
"qt",
"pyqt",
"pyqt5"
] |
how to fix ImportError python | 39,336,128 | <p>I have a file beginning with <code>from moviepy.editor import *</code>.
when I run this file I get the error: </p>
<blockquote>
<p>Traceback (most recent call last):<br> File "moviepy.py", line 2, in
<br> from moviepy.editor import *
<br>File "/home/debian/Videos/moviepy.py", line 2, in <br>
... | 0 | 2016-09-05T18:43:27Z | 39,336,156 | <p>Your filename <code>moviepy.py</code> shadows installed package. Rename your main file and everything should work fine (if moviepy is installed in used interpreter).</p>
| 2 | 2016-09-05T18:45:53Z | [
"python",
"python-2.7",
"python-import",
"importerror"
] |
Where does tkinter load his fonts from? | 39,336,204 | <p>I would like to know where does tkinter load his fonts from.</p>
<p>Is it from <code>/usr/share/fonts</code> or does it have a specific folder ?</p>
<p>thanks</p>
| 2 | 2016-09-05T18:50:24Z | 39,337,845 | <p>So as Bryan said, tkinter gets the fonts from the standard font locations of the OS. Putting fonts there will permit to tkinter to be able to load them.</p>
<p>Thanks Bryan</p>
| 0 | 2016-09-05T21:23:08Z | [
"python",
"python-3.x",
"tkinter"
] |
Best approach to create time difference variable by id | 39,336,234 | <p>I am working with a pandas df that looks like this:</p>
<pre><code>ID time
34 43
2 99
2 20
34 8
2 90
</code></pre>
<p>What would be the best approach to a create variable that represents the difference from the most recent time per ID?</p>
<pre><code>ID time diff
34 43 35
2 99 9
2 20 NA
34 8 ... | 3 | 2016-09-05T18:53:16Z | 39,336,395 | <p>Here's one possibility</p>
<pre><code>df["diff"] = df.sort_values("time").groupby("ID")["time"].diff()
df
ID time diff
0 34 43 35.0
1 2 99 9.0
2 2 20 NaN
3 34 8 NaN
4 2 90 70.0
</code></pre>
| 3 | 2016-09-05T19:07:23Z | [
"python",
"pandas"
] |
How to write data results into an output file in python | 39,336,254 | <p>I have wrote this code to analyze and search geological coordinates for proximity of data points. Since I had so many data points, the output in PyCharm was becoming overloaded and gave me a bunch of nonsense. Since then I have worked to try and solve this issue by writing the True/False results into separate docume... | -1 | 2016-09-05T18:54:39Z | 39,347,955 | <p>My suggestion: take your code that writes to the file and wrap it in a context manager. E.g. <a href="https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/" rel="nofollow">https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/</a></p>
| 0 | 2016-09-06T11:28:11Z | [
"python",
"geolocation",
"coordinates",
"pycharm",
"data-analysis"
] |
Finding the Area of a Triangle using if else statements | 39,336,283 | <p>I am supposed to write a program that prompts the user for the lengths of three sides of a triangle, determines that the three lengths can form a triangle and if so uses Heron's formula to compute the area to 4 digits of precision.This is what I have so far I don't know where or how to put in the math</p>
<pre><cod... | 1 | 2016-09-05T18:57:06Z | 39,336,500 | <p>Here's a slightly modified version of your program that checks if the inputs are compatible in one compound conditional expression and replaces the use of <code>eval</code>:</p>
<pre><code>import math
def main():
print("\nTriangle Area Program\n")
a, b, c = map(float, input("Enter three lengths separated b... | 1 | 2016-09-05T19:18:03Z | [
"python",
"python-3.x"
] |
Finding the Area of a Triangle using if else statements | 39,336,283 | <p>I am supposed to write a program that prompts the user for the lengths of three sides of a triangle, determines that the three lengths can form a triangle and if so uses Heron's formula to compute the area to 4 digits of precision.This is what I have so far I don't know where or how to put in the math</p>
<pre><cod... | 1 | 2016-09-05T18:57:06Z | 39,336,544 | <p>Here's another possible version of your mathy problem:</p>
<pre><code>import math
def heron(a, b, c):
return 0.25 * math.sqrt((a + (b + c)) * (c - (a - b)) * (c + (a - b)) * (a + (b - c)))
if __name__ == "__main__":
print()
print("Triangle Area Program")
print()
print()
try:
desc... | 1 | 2016-09-05T19:22:49Z | [
"python",
"python-3.x"
] |
How to fix "unsupported operand type(s)" in Python? | 39,336,330 | <pre><code>total=0
output=("enter next sales value")
sales=input
total_sales=total+sales
</code></pre>
<p>I keep getting this error:</p>
<blockquote>
<p>Traceback (most recent call last): File "python", line 4, in TypeError: unsupported operand type(s) for +: 'int' and 'builtin_function_or_method'</p>
</blockquo... | -2 | 2016-09-05T19:01:26Z | 39,336,434 | <p>You must use input() instead of input.
Moreover in python 3, the input() function returns a string, not an integer. So to use the return value in an addition, you must indicate it as an integer: </p>
<pre><code> sales = input("Enter next sales value")
total_sales = total + int(sales)
</code></pre>
| -1 | 2016-09-05T19:11:20Z | [
"python",
"runtime-error"
] |
Python 2.7 store duplicate string or not | 39,336,347 | <p>Wondering if my two cases, whether Python 2.7 stores duplicate string literal <code>Hello</code>, or store one string literal <code>Hello</code>, and store only address to the string literal for duplicate to save space? Thanks.</p>
<p>My two cases shows using string literal, and using a string (<code>str</code>) va... | 3 | 2016-09-05T19:03:14Z | 39,336,534 | <p>In case 2 you are safe to assume that the same object is being referenced twice, because that's what you explicitly do. Just keep in mind that you always toss around references in Python. At the same time, the first case is a bit more complicated. CPython does optimise memory usage by caching short strings (and smal... | 4 | 2016-09-05T19:21:59Z | [
"python",
"python-2.7"
] |
Import a whole folder of python files | 39,336,356 | <p>I am making a bot in python 3 and wish it to be easily expanded so I have a central file and then one for each command. I wish to know if there is a way to import a sub-directory full of modules without importing each separately. For example:</p>
<pre><code>example
âââ commands
â  âââ bar.py
â Â... | 0 | 2016-09-05T19:03:43Z | 39,336,535 | <p>If you're using python3, the <code>importlib</code> module can be used to dynamically import modules. On python2.x, there is the <code>__import__</code> function but I'm not very familiar with the semantics. As a quick example, </p>
<p>I have 2 files in the current directory</p>
<pre><code># a.py
name = "a"
</code... | 0 | 2016-09-05T19:22:05Z | [
"python",
"python-3.x"
] |
Import a whole folder of python files | 39,336,356 | <p>I am making a bot in python 3 and wish it to be easily expanded so I have a central file and then one for each command. I wish to know if there is a way to import a sub-directory full of modules without importing each separately. For example:</p>
<pre><code>example
âââ commands
â  âââ bar.py
â Â... | 0 | 2016-09-05T19:03:43Z | 39,336,669 | <p>Import each separately with:
<code>from commands import bar</code> and
<code>from commands import foo</code></p>
<p><code>from commands import *</code> Does not work.</p>
| -2 | 2016-09-05T19:33:56Z | [
"python",
"python-3.x"
] |
Python check if value in csv file | 39,336,449 | <p>i got list of URLs, for example: </p>
<pre><code>urls_list = [
"http://yandex.ru",
"http://google.ru",
"http://rambler.ru",
"http://google.ru",
"http://gmail.ru",
"http://mail.ru"
]
</code></pre>
<p>I need to open the csv file, check if each value from list in file - skip to next value, els... | -1 | 2016-09-05T19:13:21Z | 39,336,687 | <p>Read the file <em>into</em> a variable-</p>
<pre><code>with open('urls_list.csv', 'r') as fp:
s = fp.read()
</code></pre>
<p>Check to see if each list item is in the file, if not save it</p>
<pre><code>missing = []
for url in urls_list:
if url not in s:
missing.append(url + '\n')
</code></pre>
<p... | 1 | 2016-09-05T19:35:31Z | [
"python",
"loops",
"csv",
"if-statement"
] |
Python check if value in csv file | 39,336,449 | <p>i got list of URLs, for example: </p>
<pre><code>urls_list = [
"http://yandex.ru",
"http://google.ru",
"http://rambler.ru",
"http://google.ru",
"http://gmail.ru",
"http://mail.ru"
]
</code></pre>
<p>I need to open the csv file, check if each value from list in file - skip to next value, els... | -1 | 2016-09-05T19:13:21Z | 39,336,719 | <p>Considering your file has only one column, the <code>csv</code> module might be an overkill. </p>
<p>Here's a version that first reads all the lines from the file and reopens the file to write urls that are not already in the file:</p>
<pre><code>lines = open('urls_list.csv', 'r').read()
with open('urls_list.csv'... | 1 | 2016-09-05T19:38:18Z | [
"python",
"loops",
"csv",
"if-statement"
] |
(Basic?) File compiles fine, doesn't execute as intended | 39,336,459 | <blockquote>
<p>I'm running this on cygwin using atom as my editor. Python3.</p>
</blockquote>
<p>Hi,</p>
<p>Basic Python question that really baffles me. I've looked around on SO and found a lot of questions regarding similiar issues, but can't find one that covers the issue I'm facing.</p>
<p>Before I go into de... | -1 | 2016-09-05T19:14:20Z | 39,336,532 | <pre><code>if __name__ == "__main__":
main()
</code></pre>
<p>should not be indented.</p>
<p>In your current code, the <code>main()</code> method is run in the <code>else</code> block, but you never get there because the program won't start because you just <strong>define</strong> the <code>main()</code> method b... | 0 | 2016-09-05T19:21:46Z | [
"python",
"import",
"atom"
] |
(Basic?) File compiles fine, doesn't execute as intended | 39,336,459 | <blockquote>
<p>I'm running this on cygwin using atom as my editor. Python3.</p>
</blockquote>
<p>Hi,</p>
<p>Basic Python question that really baffles me. I've looked around on SO and found a lot of questions regarding similiar issues, but can't find one that covers the issue I'm facing.</p>
<p>Before I go into de... | -1 | 2016-09-05T19:14:20Z | 39,336,768 | <p>The functions defined in marvin.py are not globals in main.py; they are members of the marvin module object. So, this:</p>
<pre><code>elif choice == "1": myNameIs()
</code></pre>
<p>should be changed to this:</p>
<pre><code>elif choice == "1": marvin.myNameIs()
</code></pre>
<p>The same goes for the rest of the ... | 0 | 2016-09-05T19:42:25Z | [
"python",
"import",
"atom"
] |
Is it possible to upload multiple versions of the same package to pypiserver? | 39,336,613 | <p>Say you have two different versions of the same package and want to upload them to <code>pypiserver</code> and have clients install the version they want via <code>pip</code>. Is this possible?</p>
| 0 | 2016-09-05T19:29:10Z | 39,336,706 | <p>Yes it is possible.</p>
<p>You just upload package twice setting different version (e.g. first <code>0.1</code> and second <code>0.2</code>) in <code>setup.py</code> of your package.</p>
<p>Here is instruction how to upload:
<a href="http://peterdowns.com/posts/first-time-with-pypi.html" rel="nofollow">http://pete... | 0 | 2016-09-05T19:36:52Z | [
"python"
] |
Reusing compiled regular expressions in python | 39,336,664 |
<p>I have a program in Perl that uses a regular expression to store supported file extensions. It reuses this regex through the code. Each file extension has a description since the regular expression has the 'x' flag. I cannot figure out how to port this to python (2.7).</p>
<h3>The original Perl</h3>
<pre class="... | 1 | 2016-09-05T19:33:01Z | 39,336,738 | <p>You are doing this completely wrong. First of all the <code>.pattern</code> attribute is just <strong>a string</strong>. So it's 100% useless calling <code>re.compile</code> and then extracting the initial string used to obtain the regex object to pass to <code>re.search</code>:</p>
<pre><code>>>> regex = ... | 4 | 2016-09-05T19:39:38Z | [
"python",
"regex",
"python-2.7",
"perl"
] |
Reusing compiled regular expressions in python | 39,336,664 |
<p>I have a program in Perl that uses a regular expression to store supported file extensions. It reuses this regex through the code. Each file extension has a description since the regular expression has the 'x' flag. I cannot figure out how to port this to python (2.7).</p>
<h3>The original Perl</h3>
<pre class="... | 1 | 2016-09-05T19:33:01Z | 39,338,497 | <p>It is a myth that Perl will interpolate one compiled regular expression into another. If you write this</p>
<pre><code>my $exts = qr/ abc | mi | avi | ma | iff | tga /x;
if ( $f =~ /^([^.]+\.$exts)/ ) {
...
}
</code></pre>
<p>then within <code>$f =~ /^([^.]+\.$exts)/</code>, the contents of the regex pattern ... | 1 | 2016-09-05T22:46:31Z | [
"python",
"regex",
"python-2.7",
"perl"
] |
Reusing compiled regular expressions in python | 39,336,664 |
<p>I have a program in Perl that uses a regular expression to store supported file extensions. It reuses this regex through the code. Each file extension has a description since the regular expression has the 'x' flag. I cannot figure out how to port this to python (2.7).</p>
<h3>The original Perl</h3>
<pre class="... | 1 | 2016-09-05T19:33:01Z | 39,352,721 | <p>Yes, it can! In the Python documentation on re I found that you can specify any re flag in the expression itself - similar to how Perl prints the re flag inline. By adding the flag to the string hack you can achieve the result:</p>
<pre><code>exts = '''(?ix)(?:
abc # alembic
|... | 0 | 2016-09-06T15:26:58Z | [
"python",
"regex",
"python-2.7",
"perl"
] |
Get lag with cross-correlation? | 39,336,727 | <p>Let's say have have two signals:</p>
<pre><code>import numpy
dt = 0.001
t_steps = np.arange(0, 1, dt)
a_sig = np.sin(2*np.pi*t_steps*4+5)
b_sig = np.sin(2*np.pi*t_steps*4)
</code></pre>
<p>I want to shift the first signal to match the second signal. I know this can be completed using cross-correlation, as evidenc... | 0 | 2016-09-05T19:38:57Z | 39,336,728 | <p>As defined in <a href="https://en.wikipedia.org/wiki/Cross-correlation#Time_delay_analysis" rel="nofollow">this Wikipedia article</a>, the lag between signals is given by the argmax of the cross-correlation. Consequently, the following code will shift the <code>b_sig</code> to be in phased with <code>a_sig</code> to... | 0 | 2016-09-05T19:38:57Z | [
"python",
"numpy",
"scipy",
"signal-processing"
] |
child_process spawnSync iterate python stdout results using for loop | 39,336,754 | <p>First I will post my code,</p>
<p>I will give an example of what I am facing problem: </p>
<pre><code> for(var i=0;i<arrayleng.length;i++){
var oneScript = spawnSync('python',["/home/demo/mypython.py",arrayleng[i].path]);
//console.log(String(oneScript.stdout));
fs.readFile('/hom... | 3 | 2016-09-05T19:41:05Z | 39,336,906 | <p>Here is a nodejs example:</p>
<pre><code>var fs = require('fs')
var checkThese = ['/Users/jmunsch/Desktop/code_scraps/1.json', '/Users/jmunsch/Desktop/code_scraps/2.json']
checkThese.forEach(function(checkThisPath){
// Both of these will log first
console.log(`run first: ${checkThisPath}`)
var data = f... | 1 | 2016-09-05T19:53:18Z | [
"javascript",
"python",
"node.js"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.