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 |
|---|---|---|---|---|---|---|---|---|---|
Reading a .json file using python - Flask | 40,019,961 | <p>I'm trying to read a <code>.json</code> file from within my Flask application using:</p>
<pre><code>def renderblog():
with open(url_for("static", filename="blogs.json")) as blog_file:
data = json.load(blog_file)
</code></pre>
<p>However I get the error:</p>
<pre><code>FileNotFoundError: [Errno 2] No s... | 0 | 2016-10-13T11:40:36Z | 40,020,056 | <p>You generated a <em>URL path</em>, not a path to the local static folder. Use the <a href="http://flask.pocoo.org/docs/0.11/api/#flask.Flask.static_folder" rel="nofollow"><code>app.static_folder</code> attribute</a> instead:</p>
<pre><code>def renderblog():
filename = os.path.join(app.static_folder, 'blogs.json... | 4 | 2016-10-13T11:45:02Z | [
"python",
"json",
"flask"
] |
Replace IP addresses with filename in Python for all files in a directory | 40,020,173 | <p>If I knew the first thing about Python, I'd have figured this out myself just by referring to other similar questions that were already answered. </p>
<p>With that out of the way, I'm hoping you can help me achieve the following: </p>
<p>I'm looking to replace all occurrences of IP addresses with the file name it... | 0 | 2016-10-13T11:49:40Z | 40,021,305 | <p>Please check the below code with comments inline:</p>
<pre><code>import os
import re
import fileinput
#Get the file list from the directory
file_list = [f for f in os.listdir("C:\\Users\\dinesh_pundkar\\Desktop\\demo")]
#Change the directory where file to checked and modify
os.chdir("C:\\Users\\dinesh_pundkar\\Des... | 0 | 2016-10-13T12:40:56Z | [
"python",
"regex",
"file",
"replace",
"substitution"
] |
What python linter can I use to spot Python 2-3 compatibility issues? | 40,020,178 | <p>I want to migrate a Python codebase to work in both Python 2 and Python 3 and I was surprised to see that by default tools like flake8 or pep8 missed a very simple use of print without parentheses (<code>print 1</code> instead of <code>print(1)</code>).</p>
<p>How can I ease this migration?</p>
| 0 | 2016-10-13T11:49:46Z | 40,020,575 | <p>You should use 2to3 to spot issues/incompatibilities in the code</p>
<p><a href="https://docs.python.org/3/howto/pyporting.html" rel="nofollow">https://docs.python.org/3/howto/pyporting.html</a></p>
| 1 | 2016-10-13T12:07:00Z | [
"python",
"python-3.x",
"pep8",
"flake8"
] |
SyntaxError: invalid syntax -- One line if statement in python | 40,020,244 | <p>My initial <code>if else</code> code is :</p>
<pre><code>if response.get('fulfillments') is None:
return (False, response)
else:
return (True, response)
</code></pre>
<p>But I want to convert it to <code>one-line-if-else-statement</code>. </p>
<p>Here is what I am doing : </p>
<pre><code>return (False, r... | 1 | 2016-10-13T11:52:51Z | 40,020,329 | <p>Omit the second <code>return</code>. To simplify:</p>
<pre><code>>>> def foo(x):
... return True if x == 2 else False
</code></pre>
<p>read it as "return the results of this ternary expression" not "return this thing in one case but return some other thing in another case"</p>
| 2 | 2016-10-13T11:56:25Z | [
"python",
"if-statement"
] |
SyntaxError: invalid syntax -- One line if statement in python | 40,020,244 | <p>My initial <code>if else</code> code is :</p>
<pre><code>if response.get('fulfillments') is None:
return (False, response)
else:
return (True, response)
</code></pre>
<p>But I want to convert it to <code>one-line-if-else-statement</code>. </p>
<p>Here is what I am doing : </p>
<pre><code>return (False, r... | 1 | 2016-10-13T11:52:51Z | 40,020,365 | <p>A one-line <code>if-else</code> is not the same as the block. It is an expression, not a statement or multiple statements. You can't do something like:</p>
<pre><code>(x = 4) if x > 5 else (x = 6)
</code></pre>
<p>Because those are statements. Instead, it is like this:</p>
<pre><code>x = (4 if x > 5 else... | 6 | 2016-10-13T11:57:30Z | [
"python",
"if-statement"
] |
SyntaxError: invalid syntax -- One line if statement in python | 40,020,244 | <p>My initial <code>if else</code> code is :</p>
<pre><code>if response.get('fulfillments') is None:
return (False, response)
else:
return (True, response)
</code></pre>
<p>But I want to convert it to <code>one-line-if-else-statement</code>. </p>
<p>Here is what I am doing : </p>
<pre><code>return (False, r... | 1 | 2016-10-13T11:52:51Z | 40,020,377 | <pre><code>return (False, response) if response.get('fulfillments') is None else (True, response)
</code></pre>
<p><code>val_positive if expression else val_negative</code>. val_positive or val_negative can't contain return statement</p>
| 2 | 2016-10-13T11:58:09Z | [
"python",
"if-statement"
] |
Pandas groupby countif with dynamic columns | 40,020,270 | <p>I have a dataframe with this structure:</p>
<pre><code>time,10.0.0.103,10.0.0.24
2016-10-12 13:40:00,157,172
2016-10-12 14:00:00,0,203
2016-10-12 14:20:00,0,0
2016-10-12 14:40:00,0,200
2016-10-12 15:00:00,185,208
</code></pre>
<p>It details the number of events per IP address for a given 20 minute period. I need a... | 2 | 2016-10-13T11:53:55Z | 40,020,437 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html" rel="nofollow"><code>mean</code></a> of boolean mask by condition <code>df == 0</cod... | 3 | 2016-10-13T12:01:20Z | [
"python",
"pandas",
"sum",
"multiple-columns",
"mean"
] |
Pandas groupby countif with dynamic columns | 40,020,270 | <p>I have a dataframe with this structure:</p>
<pre><code>time,10.0.0.103,10.0.0.24
2016-10-12 13:40:00,157,172
2016-10-12 14:00:00,0,203
2016-10-12 14:20:00,0,0
2016-10-12 14:40:00,0,200
2016-10-12 15:00:00,185,208
</code></pre>
<p>It details the number of events per IP address for a given 20 minute period. I need a... | 2 | 2016-10-13T11:53:55Z | 40,024,011 | <p>Transpose the <code>DF</code>:</p>
<pre><code>df = df.T
</code></pre>
<p>Since you tried along the lines of using <code>groupby</code>, you could further proceed using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> to get... | 2 | 2016-10-13T14:36:20Z | [
"python",
"pandas",
"sum",
"multiple-columns",
"mean"
] |
Pyplot errorbar keeps connecting my points with lines? | 40,020,274 | <p>I am having trouble getting these lines between my data points to go away! It seems to be whenever I try to add error bars it does this. If you look at the graphs, the first is without the errorbar line, and the second is with it. Is this a usual side effect of pyplot errorbar? Does anyone know why it does this, or ... | 0 | 2016-10-13T11:54:00Z | 40,020,492 | <p>You can set the line style (<code>ls</code>) to <code>none</code>:</p>
<pre><code>import numpy as np
import matplotlib.pylab as plt
x = np.arange(10)
y = np.arange(10)
yerr = np.random.random(10)
xerr = np.random.random(10)
plt.figure()
plt.subplot(121)
plt.scatter(x, y, label = 'blah')
plt.errorbar(x, y, yerr = ... | 2 | 2016-10-13T12:03:48Z | [
"python",
"matplotlib",
"errorbar"
] |
How to remove words containing only numbers in python? | 40,020,326 | <p>I have some text in Python which is composed of numbers and alphabets. Something like this:</p>
<pre><code>s = "12 word word2"
</code></pre>
<p>From the string s, I want to remove all the words containing <strong>only numbers</strong></p>
<p>So I want the result to be </p>
<pre><code>s = "word word2"
</code></pr... | 2 | 2016-10-13T11:56:14Z | 40,020,376 | <p>You can use this regex:</p>
<pre><code>>>> s = "12 word word2"
>>> print re.sub(r'\b[0-9]+\b\s*', '', s)
word word2
</code></pre>
<p><code>\b</code> is used for word boundary and <code>\s*</code> will remove 0 or more spaces after your number word.</p>
| 3 | 2016-10-13T11:58:06Z | [
"python",
"regex",
"string"
] |
How to remove words containing only numbers in python? | 40,020,326 | <p>I have some text in Python which is composed of numbers and alphabets. Something like this:</p>
<pre><code>s = "12 word word2"
</code></pre>
<p>From the string s, I want to remove all the words containing <strong>only numbers</strong></p>
<p>So I want the result to be </p>
<pre><code>s = "word word2"
</code></pr... | 2 | 2016-10-13T11:56:14Z | 40,020,421 | <p>Using a regex is probably a bit overkill here depending whether you need to preserve whitespace:</p>
<pre><code>s = "12 word word2"
s2 = ' '.join(word for word in s.split() if not word.isdigit())
# 'word word2'
</code></pre>
| 6 | 2016-10-13T12:00:33Z | [
"python",
"regex",
"string"
] |
How to remove words containing only numbers in python? | 40,020,326 | <p>I have some text in Python which is composed of numbers and alphabets. Something like this:</p>
<pre><code>s = "12 word word2"
</code></pre>
<p>From the string s, I want to remove all the words containing <strong>only numbers</strong></p>
<p>So I want the result to be </p>
<pre><code>s = "word word2"
</code></pr... | 2 | 2016-10-13T11:56:14Z | 40,020,470 | <p>Without using any external library you could do:</p>
<pre><code>stringToFormat = "12 word word2"
words = ""
for word in stringToFormat.split(" "):
try:
int(word)
except ValueError:
words += "{} ".format(word)
print(words)
</code></pre>
| 1 | 2016-10-13T12:02:48Z | [
"python",
"regex",
"string"
] |
Flask-SQLAlchemy db.session.query(Model) vs Model.query | 40,020,388 | <p>This is a weird bug I've stumbled upon, and I am not sure why is it happening, whether it's a bug in SQLAlchemy, in Flask-SQLAlchemy, or any feature of Python I'm not yet aware of.</p>
<p>We are using Flask 0.11.1, with Flask-SQLAlchemy 2.1 using a PostgreSQL as DBMS.</p>
<p>Examples use the following code to upda... | 1 | 2016-10-13T11:58:47Z | 40,022,276 | <p>So, the correct way to made changes in model instance and also committed them to DB is looks like this:-</p>
<pre><code># get the instance of `Entry`
entry = Entry.query.get(1)
# change the attribute of an instance which you want, here `name` attribute is changed
entry.name = 'New name'
# now, commit your change... | 2 | 2016-10-13T13:23:10Z | [
"python",
"postgresql",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
Flask-SQLAlchemy db.session.query(Model) vs Model.query | 40,020,388 | <p>This is a weird bug I've stumbled upon, and I am not sure why is it happening, whether it's a bug in SQLAlchemy, in Flask-SQLAlchemy, or any feature of Python I'm not yet aware of.</p>
<p>We are using Flask 0.11.1, with Flask-SQLAlchemy 2.1 using a PostgreSQL as DBMS.</p>
<p>Examples use the following code to upda... | 1 | 2016-10-13T11:58:47Z | 40,047,125 | <p>Our project is separated in several files to ease mantenaince. One is <code>routes.py</code> with the controllers, and another one is <code>models.py</code>, which contains the SQLAlchemy instance and models.</p>
<p>So, while I was removing boilerplate to get a minimal working Flask project to upload it to a git re... | 0 | 2016-10-14T15:41:42Z | [
"python",
"postgresql",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
creating a pandas dataframe from a list first I create a dictionary then convert that to a dataframe | 40,020,566 | <p>I have a list that I have converted to a dictionary and want to convert the dictionary to a pandas dataframe.</p>
<p>My attempt is below however I am getting the following error:</p>
<blockquote>
<p>'numpy.int64' object has no attribute 'DataFrame'</p>
</blockquote>
<pre><code>**df = pd.DataFrame.from_dict(a, o... | 0 | 2016-10-13T12:06:40Z | 40,022,569 | <p>If you already have the dict as in your sample you could do two list comprehensions:</p>
<pre><code>d = {
'AAM': 2,
'ABC': 5,
'ABP': 3,
'ABU': 1,
'ACL': 3,
'ACX': 6,
'ADA': 7,
'ADE': 2
}
pd.DataFrame([[item for item in d.keys()],[item for item in d.values()]])
</code></pre>
<p>Resul... | 0 | 2016-10-13T13:36:19Z | [
"python",
"pandas",
"dataframe"
] |
creating a pandas dataframe from a list first I create a dictionary then convert that to a dataframe | 40,020,566 | <p>I have a list that I have converted to a dictionary and want to convert the dictionary to a pandas dataframe.</p>
<p>My attempt is below however I am getting the following error:</p>
<blockquote>
<p>'numpy.int64' object has no attribute 'DataFrame'</p>
</blockquote>
<pre><code>**df = pd.DataFrame.from_dict(a, o... | 0 | 2016-10-13T12:06:40Z | 40,023,781 | <p>Do you just want the key and value as two columns or are you trying to do something else? If the former, this is all you need:</p>
<pre><code>pd.DataFrame(a.items())
</code></pre>
| 1 | 2016-10-13T14:26:14Z | [
"python",
"pandas",
"dataframe"
] |
Scrapy: NameError: global name 'MyItem' is not defined | 40,020,654 | <p>I'm trying to fill my Items with parsed data and I'm getting error: <strong>NameError: global name 'QuotesItem' is not defined</strong>
when trying to run <strong>$ scrapy crawl quotes</strong></p>
<p>Here's my spider's code: </p>
<p>quotes.py:</p>
<pre><code>import scrapy
class QuotesSpider(scrapy.Spider):
name... | 0 | 2016-10-13T12:10:47Z | 40,020,699 | <p>You've defined <code>QuotesItem</code> in another file called <code>items.py</code>. Now you have to <a href="https://docs.python.org/3.5/tutorial/modules.html" rel="nofollow">import</a> either the entire module <code>items</code> or just the <code>QuotesItem</code>. Add the following to the top of your <code>quotes... | 1 | 2016-10-13T12:13:32Z | [
"python",
"scrapy"
] |
List of lists: replacing and adding up items of sublists | 40,020,663 | <p>I have a list of lists, let's say something like this:</p>
<pre><code>tripInfo_csv = [['1','2',6,2], ['a','h',4,2], ['1','4',6,1], ['1','8',18,3], ['a','8',2,1]]
</code></pre>
<p>Think of sublists as trips: [start point, end point, number of adults, number of children]</p>
<p>My aim is to get a list where trips w... | 1 | 2016-10-13T12:11:14Z | 40,020,977 | <p>See if this helps </p>
<pre><code>trips = [['1','2',6,2], ['a','h',4,2], ['1','2',6,1], ['1','8',18,3], ['a','h',2,1]]
# To get the equivalent value
def x(n):
if '1' <= n <= '8':
return int(n)
return ord(n) - ord('a')
# To group lists with similar start and end points
from collections impo... | 0 | 2016-10-13T12:27:17Z | [
"python",
"nested-lists"
] |
List of lists: replacing and adding up items of sublists | 40,020,663 | <p>I have a list of lists, let's say something like this:</p>
<pre><code>tripInfo_csv = [['1','2',6,2], ['a','h',4,2], ['1','4',6,1], ['1','8',18,3], ['a','8',2,1]]
</code></pre>
<p>Think of sublists as trips: [start point, end point, number of adults, number of children]</p>
<p>My aim is to get a list where trips w... | 1 | 2016-10-13T12:11:14Z | 40,021,413 | <p>Let say start and end points are between 0 and n values. </p>
<p>Then, the result 'OkTrip' has maximum n^2 elements. Then, your second loop in function has a complexity O(n^2). It is possible to reduce the complexity to O(n) if you have not problem with space complexity.</p>
<p>Firslty, create dict which contains ... | 0 | 2016-10-13T12:45:06Z | [
"python",
"nested-lists"
] |
List of lists: replacing and adding up items of sublists | 40,020,663 | <p>I have a list of lists, let's say something like this:</p>
<pre><code>tripInfo_csv = [['1','2',6,2], ['a','h',4,2], ['1','4',6,1], ['1','8',18,3], ['a','8',2,1]]
</code></pre>
<p>Think of sublists as trips: [start point, end point, number of adults, number of children]</p>
<p>My aim is to get a list where trips w... | 1 | 2016-10-13T12:11:14Z | 40,021,745 | <p>To handle this more efficiently it's best to sort the input list by the start and end points, so that rows which have matching start and end points are grouped together. Then we can easily use the <code>groupby</code> function to process those groups efficiently.</p>
<pre><code>from operator import itemgetter
from ... | 1 | 2016-10-13T12:59:36Z | [
"python",
"nested-lists"
] |
List of lists: replacing and adding up items of sublists | 40,020,663 | <p>I have a list of lists, let's say something like this:</p>
<pre><code>tripInfo_csv = [['1','2',6,2], ['a','h',4,2], ['1','4',6,1], ['1','8',18,3], ['a','8',2,1]]
</code></pre>
<p>Think of sublists as trips: [start point, end point, number of adults, number of children]</p>
<p>My aim is to get a list where trips w... | 1 | 2016-10-13T12:11:14Z | 40,021,753 | <p>The following gives much better times than yours for large lists with much merging: 2 seconds vs. 1 minute for <code>tripInfo_csv*500000</code>. We get the almost linear complexity using a dict to get the keys, that have constant lookup time. IMHO it is also more elegant. Notice that <code>tg</code> is a generator, ... | 1 | 2016-10-13T12:59:51Z | [
"python",
"nested-lists"
] |
Web2py Field value depends on another field - (validate while defining the model) | 40,020,739 | <p>Please consider the following table:</p>
<pre><code>db.define_table('bio_data',
Field('name', 'string'),
Field('total_mark', 'integer', requires=IS_EMPTY_OR(IS_INT_IN_RANGE(0, 1e100))),
Field('marks_obtained', 'integer')
)
</code></pre>
<p>Now the field 'marks_obtain... | 0 | 2016-10-13T12:15:52Z | 40,037,101 | <p>You can easily do this using <code>onvalidation</code> callback function. Read this
<a href="http://www.web2py.com/books/default/chapter/29/07/forms-and-validators#onvalidation" rel="nofollow">Form and validators - onvalidation</a></p>
<p>Second solution is you need to combine '<em>Validators with dependencies</em>... | 1 | 2016-10-14T07:12:53Z | [
"python",
"web2py",
"data-access-layer"
] |
Add a library in Spark in Bluemix & connect MongoDB , Spark together | 40,020,767 | <p><b>1) </b>I have Spark on Bluemix platform, how do I add a library there ?</p>
<p>I can see the preloaded libraries but cant add a library that I want.</p>
<p>Any command line argument that will install a library?</p>
<blockquote>
<p>pip install --package is not working there</p>
</blockquote>
<p><b>2) </b> I ... | 0 | 2016-10-13T12:17:34Z | 40,021,035 | <p>In a Python notebook:</p>
<p><code>!pip install <package></code></p>
<p>and then</p>
<p><code>import <package></code></p>
| 0 | 2016-10-13T12:30:11Z | [
"python",
"apache-spark",
"ibm-bluemix",
"bluemix-plugin"
] |
How to make a call to the surveygizmo API to a specific page using python surveygizmo package? | 40,020,846 | <p>I downloaded the surveygizmo package (1.2.1) and easily did a call to surveygizmo API like this:</p>
<pre><code>import surveygizmo as sg
client = sg.SurveyGizmo(
api_version='v4',
# example
api_token = "E4F796932C2743FEBF150B421BE15EB9",
api_token_secret = "A9fGMkJ5pJF1k"
)
surveys = client.api.survey.list()
prin... | 0 | 2016-10-13T12:20:33Z | 40,025,039 | <p>Via trial and error I found this solution:</p>
<pre><code>surveys = client.api.survey.list(resultsperpage=500, page=5)
</code></pre>
| 1 | 2016-10-13T15:22:52Z | [
"python",
"survey"
] |
How to make a call to the surveygizmo API to a specific page using python surveygizmo package? | 40,020,846 | <p>I downloaded the surveygizmo package (1.2.1) and easily did a call to surveygizmo API like this:</p>
<pre><code>import surveygizmo as sg
client = sg.SurveyGizmo(
api_version='v4',
# example
api_token = "E4F796932C2743FEBF150B421BE15EB9",
api_token_secret = "A9fGMkJ5pJF1k"
)
surveys = client.api.survey.list()
prin... | 0 | 2016-10-13T12:20:33Z | 40,025,303 | <p>I didn't take the time to set up access to SurveyGizmo. However, by importing the Python façade and poking around it and the documentation I found this possibility.</p>
<pre><code>client.config.requests_kwargs={'page':2}
</code></pre>
<p>I'm curious to know whether it works.</p>
| 0 | 2016-10-13T15:35:27Z | [
"python",
"survey"
] |
IndexError in this code | 40,020,897 | <p>When I use this as the contents of the input file:</p>
<pre><code>1,3,5,7,9,11
</code></pre>
<p>I receive this error: </p>
<pre><code>IndexError: li
</code></pre>
<hr>
<pre><code>with open('fig.fig') as o:
n = 6
for i in range(1, 2*n, 2):
print(o.readlines()[i].replace(' ', ''))
</code></pre>
| -1 | 2016-10-13T12:23:15Z | 40,021,496 | <p>there is nothing wrong with the following code:</p>
<pre><code>n = 6
for i in range(1, 2*n, 2):
print <something>[i].replace(' ', '')
</code></pre>
<p>so the problem is in the open or reading of your file (really open? line length?). Hope that helps.</p>
| 0 | 2016-10-13T12:49:19Z | [
"python",
"indexing",
"file-access"
] |
IndexError in this code | 40,020,897 | <p>When I use this as the contents of the input file:</p>
<pre><code>1,3,5,7,9,11
</code></pre>
<p>I receive this error: </p>
<pre><code>IndexError: li
</code></pre>
<hr>
<pre><code>with open('fig.fig') as o:
n = 6
for i in range(1, 2*n, 2):
print(o.readlines()[i].replace(' ', ''))
</code></pre>
| -1 | 2016-10-13T12:23:15Z | 40,029,962 | <p>When opening and processing a file, you should always make sure that you don't attempt to read more lines than are actually in the file. Also, you are making repeated calls to <code>readlines</code> which is quite inefficient. Try something like:</p>
<pre><code>with open('fig.fig') as o:
lines = o.readlines... | 0 | 2016-10-13T20:03:49Z | [
"python",
"indexing",
"file-access"
] |
Not able to open Firefox using Selenium Python | 40,020,913 | <p>I am getting an error when trying to open <code>Firefox</code> with <code>Selenium</code>. I tried this:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.firefox.webdriver import FirefoxProfile
profile = FirefoxProfile('/home/usr/.mozilla/firefox')
driver = webdriver.Firefox(profile)
</code></... | -2 | 2016-10-13T12:24:05Z | 40,021,369 | <p>Try:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://google.com')
</code></pre>
| 0 | 2016-10-13T12:43:32Z | [
"python",
"selenium",
"selenium-webdriver"
] |
Not able to open Firefox using Selenium Python | 40,020,913 | <p>I am getting an error when trying to open <code>Firefox</code> with <code>Selenium</code>. I tried this:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.firefox.webdriver import FirefoxProfile
profile = FirefoxProfile('/home/usr/.mozilla/firefox')
driver = webdriver.Firefox(profile)
</code></... | -2 | 2016-10-13T12:24:05Z | 40,022,595 | <p>I think you are using selenium 2.53.6</p>
<p>The issue is compatibility of firefox with selenium, since firefox>= 48 need Gecko Driver(<a href="https://github.com/mozilla/geckodriver" rel="nofollow">https://github.com/mozilla/geckodriver</a>) to run testcases on firefox. or you can downgrade the firefox to 46..from... | 0 | 2016-10-13T13:37:18Z | [
"python",
"selenium",
"selenium-webdriver"
] |
counting occurrence of elements in each sequence of the list in python | 40,020,920 | <p>I have a (very big) list like the small example. I want to count the number of D in each sequence in the list and divide by the length of that sequence. (occurrence of D in each sequence).</p>
<p>small example:</p>
<pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQ... | 0 | 2016-10-13T12:24:38Z | 40,020,983 | <p>You can simply use a <em>list comprehension</em>, get the count of <code>D</code> in each sequence and divide by the length of the sequence:</p>
<pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE']
result = [x.count('D')/len(x) for x in l]
print(result)
# ... | 1 | 2016-10-13T12:27:39Z | [
"python"
] |
counting occurrence of elements in each sequence of the list in python | 40,020,920 | <p>I have a (very big) list like the small example. I want to count the number of D in each sequence in the list and divide by the length of that sequence. (occurrence of D in each sequence).</p>
<p>small example:</p>
<pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQ... | 0 | 2016-10-13T12:24:38Z | 40,020,995 | <p>You're looking for something like:</p>
<pre><code>def fn(x):
return x.count('D') / len(x)
results = ap(fn, l)
</code></pre>
| 0 | 2016-10-13T12:28:03Z | [
"python"
] |
counting occurrence of elements in each sequence of the list in python | 40,020,920 | <p>I have a (very big) list like the small example. I want to count the number of D in each sequence in the list and divide by the length of that sequence. (occurrence of D in each sequence).</p>
<p>small example:</p>
<pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQ... | 0 | 2016-10-13T12:24:38Z | 40,021,111 | <p>You can use list comprehension in order to get the expected result.</p>
<p>I have iterated over each item in the list, for each one of the items in the list I've counted the number of the occurrences of the specified sub string (in this case 'D').</p>
<p>Last, I've divided the number of the occurrences with the le... | 1 | 2016-10-13T12:32:56Z | [
"python"
] |
Python Selenium - iterate through search results | 40,020,982 | <p>In the search results, I need to verify that all of them must contain the search key. This is the HTML source code:</p>
<pre><code><div id="content">
<h1>Search Results</h1>
<a id="main-content" tabindex="-1"></a>
<ul class="results">
<li&... | 0 | 2016-10-13T12:27:37Z | 40,021,079 | <p>You should check if <code>innerHTML</code> value of particular element contains key string, but not element itself, so try</p>
<pre><code>for result in results:
assert "Sunshine" in result.text
</code></pre>
| 1 | 2016-10-13T12:31:39Z | [
"python",
"selenium",
"selenium-webdriver"
] |
Python Selenium - iterate through search results | 40,020,982 | <p>In the search results, I need to verify that all of them must contain the search key. This is the HTML source code:</p>
<pre><code><div id="content">
<h1>Search Results</h1>
<a id="main-content" tabindex="-1"></a>
<ul class="results">
<li&... | 0 | 2016-10-13T12:27:37Z | 40,021,083 | <p>I got a mistake in <code>assert</code> statement.</p>
<p>Because <code>result</code> is a WebElement so there is no text to look up in it.</p>
<p>I just change it like: <code>assert "Sunshine" in result.text</code></p>
| 0 | 2016-10-13T12:31:54Z | [
"python",
"selenium",
"selenium-webdriver"
] |
Django ORM, accessing the attributes of relationships | 40,020,993 | <p>I have on my projects two apps: account_app and image_app which have the models below.</p>
<p>I am wondering if it is possible to directly access the number of likes of one profile, which has a OneToOne relation with User(django bultin) that in turn has a ManyToMany relation with Images user_like.</p>
<p><strong><... | 0 | 2016-10-13T12:28:01Z | 40,021,567 | <p>Given a <em>Profile</em> instance <code>profile</code>, you may get the number of <code>users_like</code> with:</p>
<pre><code>number_of_likes = profile.user.images_liked.count()
</code></pre>
| 0 | 2016-10-13T12:52:22Z | [
"python",
"django",
"django-models"
] |
Django ORM, accessing the attributes of relationships | 40,020,993 | <p>I have on my projects two apps: account_app and image_app which have the models below.</p>
<p>I am wondering if it is possible to directly access the number of likes of one profile, which has a OneToOne relation with User(django bultin) that in turn has a ManyToMany relation with Images user_like.</p>
<p><strong><... | 0 | 2016-10-13T12:28:01Z | 40,021,754 | <p>You can also introduce a property <code>likes</code> in Profile Model. </p>
<pre><code>class Profile(models.Model):
# quando usar a relacao nao colocar o nome User de vez, tem que usar dessa forma
# essa relacao nos permite linkar o perfil com o usuario
user = models.OneToOneField(settings.AUTH_USER_MOD... | 0 | 2016-10-13T12:59:51Z | [
"python",
"django",
"django-models"
] |
How can I queue a task to Celery from C#? | 40,021,066 | <p>As I understand message brokers like RabbitMQ facilitates different applications written in different language/platform to communicate with each other. So since celery can use RabbitMQ as message broker, I believe we can queue task from any application to Celery, even though the producer isn't written in Python.</p>... | 1 | 2016-10-13T12:31:15Z | 40,132,075 | <p>According to this <a href="http://www.rabbitmq.com/dotnet-api-guide.html" rel="nofollow">article</a>, celery .Net client uses default TaskScheduler that comes with .Net Framework. This knows how to generate ID for your task. This article also points to some example <a href="https://msdn.microsoft.com/library/system.... | 0 | 2016-10-19T12:58:15Z | [
"c#",
"python",
"rabbitmq",
"celery",
"task-queue"
] |
geopandas: how do I merge information only if point is inside a polygon? | 40,021,140 | <p>I have a <code>geopandas</code> dataframe <code>A</code> with the geometry field set to a single <code>Point</code> (x,y). Then I have a second dataframe <code>B</code> with the geometry field set to some polygon and some other information. For example:</p>
<pre><code>A
geometry
(1,2)
(3,4)
...
</code></pre>
<p... | 0 | 2016-10-13T12:34:21Z | 40,026,513 | <p>Just in case someone else needs it, and assuming your geometry is well-formed, then you can do:</p>
<p><code>new_df = gpd.sjoin(A,B,how="inner", op='intersects')</code></p>
<p>this was enough.</p>
| 1 | 2016-10-13T16:35:09Z | [
"python",
"pandas",
"shapefile",
"geopandas"
] |
How to modify the XML file using Python? | 40,021,380 | <p>Actually I have got the XML string and parse the string to get the attributes from it. Now I want my XML file to change, viewing the attributes. Like I want to change the color of the stroke. Is there any way? How I will change and then again save the file.</p>
<pre><code>import requests
from xml.dom import minidom... | 0 | 2016-10-13T12:43:50Z | 40,044,391 | <p>You should probably read through the <a href="http://docs.geoserver.org/latest/en/user/styling/sld/cookbook/index.html" rel="nofollow">SLD Cook book</a> to get hints on how to change things like the colour of the lines in your SLD. Once you've changed it you need to make a <a href="http://docs.geoserver.org/latest/e... | 0 | 2016-10-14T13:28:24Z | [
"python",
"xml",
"django",
"geoserver"
] |
Python List Segregation | 40,021,608 | <p>I have a list of roughly 30,000 items that I am currently printing into a table with their associated relationships. I want to break apart this list into alphabetically segregated pages. </p>
<p>The data comes from a database, and the list is formed with the following code:</p>
<p><code>ListView.as_view(queryset=T... | -4 | 2016-10-13T12:54:11Z | 40,022,881 | <p>If the list is a text file, you can use pandas</p>
<pre><code>df = pd.read_csv(filepath,sep='|')
</code></pre>
<p>I'm going to use a dummy df to show querying</p>
<pre><code>df = pd.DataFrame(np.array(['alaska',1,2,'alabama',1,2,'brooklyn',1,2]).reshape(3,3))
ar2 = [df.values[n] if df.values[n][0].startswith('a')... | 0 | 2016-10-13T13:48:35Z | [
"python",
"django"
] |
Is it more reliable to rely on index of occurrence or keywords when parsing websites? | 40,021,636 | <p>Just started using XPath, I'm parsing a website with lxml.</p>
<p>Is it preferable to do: </p>
<pre><code>number_I_want = parsed_body.xpath('.//b')[6].text
#or
number_I_want = parsed_body.xpath('.//span[@class="class_name"]')[0].text
</code></pre>
<p>I'd rather find this out now, rather than much further down th... | 0 | 2016-10-13T12:55:22Z | 40,021,899 | <p>I'd say that it is generally better to rely on <code>id</code> attributes, or <code>class</code> by default, than on the number and order of appearance of specific tags.
That is more resilient to change in the page content.</p>
| 1 | 2016-10-13T13:06:46Z | [
"python",
"xpath",
"lxml"
] |
Pyplot Label Scatter Plot with Coincident Points / Overlapping Annotations | 40,021,676 | <p>This question is a follow on to <a href="http://stackoverflow.com/questions/5147112/matplotlib-how-to-put-individual-tags-for-a-scatter-plot">this</a>. How can I layout the annotations so they are still readable when the labeled points are exactly or nearly coincident? I need a programmatic solution, hand tuning t... | 0 | 2016-10-13T12:56:53Z | 40,022,068 | <p>Take the distance between the last point, set a threshold hold, and then flip the x,y text accordingly. See below.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
N = 10
data = np.random.random((N, 4))
data[1, :2] = data[0, :2]
data[-1, :2] = data[-2, :2] + .01
labels = ['poin... | 1 | 2016-10-13T13:15:02Z | [
"python",
"matplotlib"
] |
Pyplot Label Scatter Plot with Coincident Points / Overlapping Annotations | 40,021,676 | <p>This question is a follow on to <a href="http://stackoverflow.com/questions/5147112/matplotlib-how-to-put-individual-tags-for-a-scatter-plot">this</a>. How can I layout the annotations so they are still readable when the labeled points are exactly or nearly coincident? I need a programmatic solution, hand tuning t... | 0 | 2016-10-13T12:56:53Z | 40,025,264 | <p>Here's what I ended up with. Not perfect for all situations, and it doesn't even work smoothly for this example problem, but I think it is good enough for my needs. Thanks Dan for your answer pointing me in the right direction.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial i... | 0 | 2016-10-13T15:33:15Z | [
"python",
"matplotlib"
] |
How to debug silent crash | 40,021,842 | <p>I have a Python3.4 and PyQt5 application. This application communicate with an embedded device (Send and receive some frames).</p>
<p>I have a method (run from a QThread) to retrieve the device events ( It can be 10 events or more than 600 ). This methode work well in "release" mode.
But when I start the program in... | 0 | 2016-10-13T13:04:13Z | 40,033,229 | <p>Actually the best thing that you can do is try to make your code independent from pyqt and debug it look for issues fix them and make connection with pyqt, because otherwise even if your code works fine you will get just the interface on a screen and you can not see what happen </p>
| 0 | 2016-10-14T00:44:51Z | [
"python",
"multithreading",
"exception-handling",
"pyqt",
"pycharm"
] |
tkinter get selection radiobutton | 40,021,843 | <p>How can I append the priority of this application to the file as seen in the code below?</p>
<pre><code> #Option boxes for assigning a priority level to the request
priority = StringVar()
Radiobutton(self.f4, text = "High", variable=priority, value="1").grid(row = 4, column = 1, sticky = W)
Radiobut... | 0 | 2016-10-13T13:04:15Z | 40,022,538 | <p>Have you tried changing </p>
<blockquote>
<p>variable=priority</p>
</blockquote>
<p>to </p>
<blockquote>
<p>variable=self.priority</p>
</blockquote>
<p>This way, the Radiobutton knows where to search for the variable (in your program / class) instead of looking for it in the Radiobutton-Class itself.</p>
<p... | 0 | 2016-10-13T13:35:09Z | [
"python",
"tkinter"
] |
Find indices of a list of values in a not sorted numpy array | 40,021,914 | <p>I'm referring to a similar question: <a href="http://stackoverflow.com/questions/12122639">Find indices of a list of values in a numpy array</a></p>
<p>In that case we have a master array that is sorted and another array of which we want to find the index in the master array.</p>
<pre><code>master = np.array([1,2,... | 1 | 2016-10-13T13:07:37Z | 40,022,097 | <p>If all else fails, you need to sort your master array temporarily, then invert the sort order needed for this after matching the elements:</p>
<pre><code>import numpy as np
master = np.array([2,3,5,4,1])
search = np.array([3,2,1,4,5])
# sorting permutation and its reverse
sorti = np.argsort(master)
sorti_inv = np... | 0 | 2016-10-13T13:16:41Z | [
"python",
"arrays",
"numpy"
] |
Find element by tag name within element by tag name (Selenium) | 40,022,010 | <p>I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.</p>
<pre><code... | 1 | 2016-10-13T13:11:44Z | 40,022,084 | <p>You have the right idea, but part of your problem is that <code>a_childrens = link.find_element_by_tag_name('a')</code> will get you what you're looking for, but you're basically throwing out all of them because you get them in the loop, but don't do anything with them as you're in the loop. So you're only left with... | 1 | 2016-10-13T13:16:09Z | [
"python",
"selenium"
] |
Find element by tag name within element by tag name (Selenium) | 40,022,010 | <p>I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.</p>
<pre><code... | 1 | 2016-10-13T13:11:44Z | 40,022,128 | <p>I recommend css_selector instead of tag_name</p>
<pre><code>aTagsInLi = driver.find_elements_by_css_selector('li a')
for a in aTagsInLi:
(print a.get_attribute('href'))
</code></pre>
| 3 | 2016-10-13T13:17:55Z | [
"python",
"selenium"
] |
Find element by tag name within element by tag name (Selenium) | 40,022,010 | <p>I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.</p>
<pre><code... | 1 | 2016-10-13T13:11:44Z | 40,022,176 | <p>Try to select the links directly:</p>
<pre><code> links = driver.find_elements_by_tag_name('a')
</code></pre>
| 0 | 2016-10-13T13:19:47Z | [
"python",
"selenium"
] |
Find element by tag name within element by tag name (Selenium) | 40,022,010 | <p>I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.</p>
<pre><code... | 1 | 2016-10-13T13:11:44Z | 40,022,302 | <p><strong>find_element_by_xpath</strong> would do the trick...</p>
<pre><code>links = driver.find_elements_by_xpath('//li/a/@href')
</code></pre>
| 0 | 2016-10-13T13:24:24Z | [
"python",
"selenium"
] |
Remove spaces before newlines | 40,022,102 | <p>I need to remove all spaces before the newline character throughout a string.</p>
<pre><code>string = """
this is a line \n
this is another \n
"""
</code></pre>
<p>output:</p>
<pre><code>string = """
this is a line\n
this is another\n
"""
</code></pre>
| 2 | 2016-10-13T13:16:54Z | 40,022,269 | <pre><code>import re
re.sub('\s+\n','\n',string)
</code></pre>
<p>Edit: better version from comments:</p>
<pre><code>re.sub(r'\s+$', '', string, flags=re.M)
</code></pre>
| 2 | 2016-10-13T13:22:56Z | [
"python"
] |
Remove spaces before newlines | 40,022,102 | <p>I need to remove all spaces before the newline character throughout a string.</p>
<pre><code>string = """
this is a line \n
this is another \n
"""
</code></pre>
<p>output:</p>
<pre><code>string = """
this is a line\n
this is another\n
"""
</code></pre>
| 2 | 2016-10-13T13:16:54Z | 40,022,271 | <p>You can <em>split</em> the string into lines, <em>strip</em> off all whitespaces on the right using <code>rstrip</code>, then add a new line at the end of each line:</p>
<pre><code>''.join([line.rstrip()+'\n' for line in string.splitlines()])
</code></pre>
| 6 | 2016-10-13T13:23:00Z | [
"python"
] |
Remove spaces before newlines | 40,022,102 | <p>I need to remove all spaces before the newline character throughout a string.</p>
<pre><code>string = """
this is a line \n
this is another \n
"""
</code></pre>
<p>output:</p>
<pre><code>string = """
this is a line\n
this is another\n
"""
</code></pre>
| 2 | 2016-10-13T13:16:54Z | 40,022,448 | <p>As you can find <a href="http://stackoverflow.com/questions/8270092/python-remove-all-whitespace-in-a-string">here</a>, </p>
<p>To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:</p>
<pre><code>sentence = ''.join(sentence.split())
</code></pre>
<p>or a regular expres... | -1 | 2016-10-13T13:31:27Z | [
"python"
] |
How to integrate Django-CMS into an existing project | 40,022,161 | <p>I need to integrate Django-CMS 3.x into an existing project (<code>mypjc</code> hereafter). I already checked <a href="http://stackoverflow.com/questions/31167313/how-to-start-integrating-django-cms-into-existing-project">this</a> question (and other similar) but they point to a <a href="http://django-cms.readthedoc... | 0 | 2016-10-13T13:19:19Z | 40,022,513 | <p>With Django CMS, it is indeed possible to integrate it into an existing project. </p>
<p>If you already have an existing project with URL/menu management, then you can simply integrate just the per-page CMS, which can be added as additional field to your model:</p>
<pre><code>from django.db import models
from cms.... | 1 | 2016-10-13T13:33:59Z | [
"python",
"django",
"content-management-system",
"django-cms"
] |
How can I replace all the " " values with Zero's in a column of a pandas dataframe | 40,022,178 | <pre><code>titanic_df['Embarked'] = titanic_df['Embarked'].fillna("S")
</code></pre>
<p>titanic_df is data frame,Embarked is a column name. I have to missing cells in my column i.e blank spaces and I want to add "S" at the missing place but the code I mentioned above is not working.Please help me.</p>
| 1 | 2016-10-13T13:19:48Z | 40,022,218 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>replace</code></a>:</p>
<pre><code>titanic_df['Embarked'] = titanic_df['Embarked'].replace(" ", "S")
</code></pre>
<p>Sample:</p>
<pre><code>import pandas as pd
titanic_df = pd.DataFra... | 3 | 2016-10-13T13:21:03Z | [
"python",
"pandas"
] |
How can I replace all the " " values with Zero's in a column of a pandas dataframe | 40,022,178 | <pre><code>titanic_df['Embarked'] = titanic_df['Embarked'].fillna("S")
</code></pre>
<p>titanic_df is data frame,Embarked is a column name. I have to missing cells in my column i.e blank spaces and I want to add "S" at the missing place but the code I mentioned above is not working.Please help me.</p>
| 1 | 2016-10-13T13:19:48Z | 40,022,351 | <p>Or you could use <code>apply</code></p>
<pre><code>titanic_df['Embarked'] = titanic_df['Embarked'].apply(lambda x: "S" if x == " " else x)
</code></pre>
| 1 | 2016-10-13T13:27:20Z | [
"python",
"pandas"
] |
Attempted relative import beyond toplevel package | 40,022,220 | <p>Here is my folder structure:</p>
<pre><code>Mopy/ # no init.py !
bash/
__init__.py
bash.py # <--- Edit: yep there is such a module too
bass.py
bosh/
__init__.py # contains from .. import bass
bsa_files.py
...
test_bash\
__init__.py # code below
test_bosh\
... | 0 | 2016-10-13T13:21:04Z | 40,022,629 | <p>TLDR: Do</p>
<pre><code>import bash.bosh
</code></pre>
<p>or</p>
<pre><code>from bash import bosh
</code></pre>
<p>If you also just happen to have a construct like <code>bash.bash</code>, you have to make sure your package takes precedence over its contents. Instead of appending, add it to the front of the searc... | 1 | 2016-10-13T13:38:51Z | [
"python",
"python-2.7",
"python-import",
"python-unittest",
"relative-import"
] |
How to solve TypeError: 'str' does not support the buffer interface? | 40,022,354 | <p>My code:</p>
<pre><code>big_int = 536870912
f = open('sample.txt', 'wb')
for item in range(0, 10):
y = bytearray.fromhex('{:0192x}'.format(big_int))
f.write("%s" %y)
f.close()
</code></pre>
<p>I want to convert a long int to bytes. But I am getting <code>TypeError: 'str' does not support the buffer interfac... | 1 | 2016-10-13T13:27:34Z | 40,022,501 | <p>In Python 3, strings are implicitly Unicode and are therefore detached from a specific binary representation (which depends on the encoding that is used). Therefore, the string <code>"%s" % y</code> cannot be written to a file that is opened in binary mode.</p>
<p>Instead, you can just write <code>y</code> directl... | 1 | 2016-10-13T13:33:38Z | [
"python"
] |
How to solve TypeError: 'str' does not support the buffer interface? | 40,022,354 | <p>My code:</p>
<pre><code>big_int = 536870912
f = open('sample.txt', 'wb')
for item in range(0, 10):
y = bytearray.fromhex('{:0192x}'.format(big_int))
f.write("%s" %y)
f.close()
</code></pre>
<p>I want to convert a long int to bytes. But I am getting <code>TypeError: 'str' does not support the buffer interfac... | 1 | 2016-10-13T13:27:34Z | 40,023,130 | <p>In addition to @Will answer, it is better to use <a href="http://effbot.org/zone/python-with-statement.htm" rel="nofollow"><code>with</code></a> statement in to open your files. Also, if you using python 3.2 and later, you can use <a href="https://docs.python.org/3/library/stdtypes.html#int.to_bytes" rel="nofollow">... | 3 | 2016-10-13T13:59:04Z | [
"python"
] |
.readlines() shouldn't return an array? | 40,022,420 | <p>I have a problem with <code>.readlines()</code>.
it used to only return the line specified, i.e. if I ran</p>
<pre><code>f1 = open('C:\file.txt','r')
filedata = f1.readlines(2)
f1.close()
print filedata
</code></pre>
<p>it should print the second line of <strong>file.txt.</strong>
However now when I run that same ... | 0 | 2016-10-13T13:29:58Z | 40,022,449 | <p>Change this:</p>
<pre><code>f1.readlines(2)
</code></pre>
<p>To this:</p>
<pre><code>f1.readlines()[2]
</code></pre>
| 2 | 2016-10-13T13:31:33Z | [
"python",
"readlines"
] |
.readlines() shouldn't return an array? | 40,022,420 | <p>I have a problem with <code>.readlines()</code>.
it used to only return the line specified, i.e. if I ran</p>
<pre><code>f1 = open('C:\file.txt','r')
filedata = f1.readlines(2)
f1.close()
print filedata
</code></pre>
<p>it should print the second line of <strong>file.txt.</strong>
However now when I run that same ... | 0 | 2016-10-13T13:29:58Z | 40,022,680 | <p>Don't use <code>readlines</code>; it reads the entire file into memory, <em>then</em> selects the desired line. Instead, just read the first <code>n</code> lines, then break.</p>
<pre><code>n = 2
with open('C:\file.txt','r') as f1:
for i, filedata in enumerate(f1, 1):
if i == n:
break
print ... | 3 | 2016-10-13T13:40:42Z | [
"python",
"readlines"
] |
My version of the quicksort algorithm from Wikipedia does not work | 40,022,487 | <pre><code>def partition(A,lo,hi):
pivot = A[hi]
i=lo
#Swap
for j in range(lo,hi-1):
if (A[j] <= pivot):
val=A[i]
A[i]=A[j]
A[j]=val
i=i+1
val=A[i]
A[i]=A[hi]
A[hi]=val
return(i)
def quicksort(A,lo,hi):
if (lo<h... | -5 | 2016-10-13T13:33:15Z | 40,022,761 | <pre><code>def partition(A,lo,hi):
pivot = A[hi]
i=lo
#Swap
for j in range(lo,hi-1):
if (A[j] <= pivot):
val=A[i]
A[i]=A[j]
A[j]=val
i=i+1
val=A[i] #was in for loop was suppose to be outside of for loop
A[i]=A[hi] #was in for loop ... | 2 | 2016-10-13T13:44:25Z | [
"python",
"quicksort"
] |
AWS alarm for real time values | 40,022,495 | <p>(AWS Beginner) </p>
<p>I am connected to temperature sensors and want to trigger an email notification when temperature crosses the threshold value. </p>
<p>In SNS alarms,metrics are predefined and I am not able to customize my real time alarm.</p>
| 0 | 2016-10-13T13:33:28Z | 40,022,848 | <p>Amazon CloudWatch supports custom CloudWatch metrics.</p>
<p><a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html" rel="nofollow">http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html</a></p>
<p>Once you have your metrics being pushed to Cloud... | 2 | 2016-10-13T13:47:17Z | [
"python",
"amazon-web-services"
] |
Check the entry after the user has entered a value | 40,022,499 | <p>I wrote a graphical interface using Tkinter with Python 3.4. In my script, I am using ttk.Entry to generate a input space where the user can enter a value.</p>
<p>Is it possible to do an action when the user has finished tipping e.g. call a function? I though about using a button if it was not possible.</p>
<p>Her... | 0 | 2016-10-13T13:33:31Z | 40,022,668 | <p>You can add a <code>FocusOut</code> event manager function. This event-manager would execute as soon as the user has finished typing in the field and moved to something else: </p>
<pre><code>input_path_frame.bind( '<FocusOut>',
lambda e, strvar=path_frame: check_field(e, strvar)
)
# check_field functio... | 1 | 2016-10-13T13:40:27Z | [
"python",
"python-3.x",
"tkinter"
] |
Creating an empty Pandas DataFrame column with a fixed first value then filling it with a formula | 40,022,553 | <p>I'd like to create an emtpy column in an existing DataFrame with the first value in only one column to = 100. After that I'd like to iterate and fill the rest of the column with a formula, like row[C][t-1] * (1 + row[B][t])</p>
<p>very similar to:
<a href="http://stackoverflow.com/questions/13784192/creating-an-emp... | 0 | 2016-10-13T13:35:41Z | 40,023,331 | <p>Try this. Unfortunately, something similar to a for loop is likely needed because you will need to calculate the next row based on the prior rows value which needs to be saved to a variable as it moves down the rows (c_column in my example):</p>
<pre><code>c_column = []
c_column.append(100)
for x,i in enumerate(df... | 0 | 2016-10-13T14:07:38Z | [
"python",
"pandas",
"dataframe"
] |
ajax returns python array response as string | 40,022,582 | <p>I am trying to list, in a select dropdown, some ontology elements using the following ajax:</p>
<pre><code>$.ajax({
type: 'get',
url:"../py/ConfigOntology.py",
success: function(data){
$("#instance_image_1").append($("<option></option>... | 0 | 2016-10-13T13:36:49Z | 40,022,925 | <p>I think what you should do is to return a JSON Object in the endpoint of your ajax call. </p>
<p>If I understand it correctly right now you try to read the output of a python script in an ajax request which is not the normal workflow for this. </p>
<p>the normal workflow would be <strong>request</strong> (client, ... | 0 | 2016-10-13T13:50:16Z | [
"javascript",
"php",
"python",
"ajax"
] |
Scrapy ImportError: No module named Item | 40,022,721 | <p>I know that this question was already widely discussed, but I didn't find an answer. I'm getting error <strong>ImportError: No module named items</strong>. I've created a new project with <strong>$ scrapy startproject pluto</strong> and I have no equal names (in names of project, classes etc), to avoid <a href="http... | 0 | 2016-10-13T13:42:29Z | 40,022,922 | <p>First of all, make sure to <em>execute the Scrapy command from inside the top level directory of your project</em>.</p>
<p>Or you may also try changing your import to:</p>
<pre><code>from pluto.items import PlutoItem
</code></pre>
| 1 | 2016-10-13T13:50:10Z | [
"python",
"scrapy"
] |
Scrapy ImportError: No module named Item | 40,022,721 | <p>I know that this question was already widely discussed, but I didn't find an answer. I'm getting error <strong>ImportError: No module named items</strong>. I've created a new project with <strong>$ scrapy startproject pluto</strong> and I have no equal names (in names of project, classes etc), to avoid <a href="http... | 0 | 2016-10-13T13:42:29Z | 40,022,964 | <p>It looks like your <code>items.py</code> and <code>pluto_spider.py</code> are at different levels. You should make your import either <code>from pluto import items</code> or a relative import <code>import ..items</code> per <a href="https://www.python.org/dev/peps/pep-0328/" rel="nofollow">PEP 328</a> to import the ... | 1 | 2016-10-13T13:52:07Z | [
"python",
"scrapy"
] |
Finding out where analytics should be defined | 40,022,757 | <p>I am working with Google Analytics api in python and keep getting the error</p>
<pre><code>NameError: name 'analytics' is not defined.
</code></pre>
<p>I have been searching for several days on the <code>analytics</code> api site and on StackOverflow for the answer. If someone could please point me in the directi... | 2 | 2016-10-13T13:44:08Z | 40,023,032 | <p>The error is saying what is happening: you did not define the name <code>analytics</code> used in line 9 previously</p>
<pre><code>daily_upload = analytics.management().uploads().uploadData(
</code></pre>
<p>You need to go over the first steps in order to use that and import it. You will also need an account since... | 0 | 2016-10-13T13:55:18Z | [
"python",
"python-2.7",
"google-analytics",
"google-analytics-api"
] |
Any ideas why this code won't work | 40,022,809 | <p>I have multiple files with names and stats and a file that checks for a certain stat.</p>
<pre><code>Example File 1
Eddy,23,2,4,9,AB
Frank,46,2,4,5,DA
Example File 2
AB
B
BA
DA
DH
</code></pre>
<p>I am not getting any errors but it is not writing to the new file.</p>
<p>The code I am using to do this is:</p>
<p... | -1 | 2016-10-13T13:45:40Z | 40,023,845 | <pre><code>import csv
stats = set()
with open('File2.csv') as file2:
for line in file2:
stats.add(line)
with open('File1.csv', newline='') as file1:
file1_reader = csv.reader(file1)
with open('output.csv', 'w+', newline='') as output:
output_writer = csv.writer(output)
for line in fi... | 0 | 2016-10-13T14:29:22Z | [
"python",
"python-3.5.2"
] |
Python: count time of watching video | 40,022,937 | <p>I have a task, connected with detection time of watching video.
If I watch the video, for example <code>https://www.youtube.com/watch?v=jkaMiaRLgvY</code>, is it real to get quantity of seconds, which passed from the moment you press the button to start and until stop?</p>
| 0 | 2016-10-13T13:50:46Z | 40,024,596 | <p>If what you are measuring is the total time the <strong>user</strong> spent watching the video (including stalls/interruptions) then your strategy would work. </p>
<p>However, if you are looking to measure the video duration, then simply counting the number of seconds since "start" was pressed isn't very accurate. ... | 0 | 2016-10-13T15:02:36Z | [
"python",
"video",
"youtube",
"video-streaming"
] |
pairing data between two files | 40,022,967 | <p>I'm trying to match data between two files.</p>
<p>File 1:</p>
<pre class="lang-none prettyprint-override"><code># number of records, name
1234, keyword
</code></pre>
<p>File 2:</p>
<pre class="lang-none prettyprint-override"><code># date/time, name
2016-10-13| here is keyword in the name
</code></pre>
<p>as a ... | 1 | 2016-10-13T13:52:20Z | 40,023,307 | <p>this</p>
<pre><code>if name in item:
</code></pre>
<p>checks if there is an item <em>cell</em> with the exact content <code>name</code> in the <code>item</code> row (list of cells) (<code>item</code> is actually the row you stored earlier, bad naming :))</p>
<p>What you need is to scan each item to see if the str... | 3 | 2016-10-13T14:06:23Z | [
"python"
] |
Django - Dynamic form fields based on foreign key | 40,022,982 | <p>I'm working on creating a database which has programs and these programs have risks. Some background information: Programs (grandparents) have multiple Characteristics (parents) which have multiple Categories (children). I've already constructed a database containing these, however, I want to add risks to a particul... | 2 | 2016-10-13T13:53:18Z | 40,033,424 | <p>To rephrase your question, are you asking how to pre-populate the form fields? If so consider using <a href="https://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset" rel="nofollow">initial values in your formsets</a></p>
| 0 | 2016-10-14T01:12:14Z | [
"python",
"django",
"forms",
"dynamic",
"formset"
] |
Elasticsearch profile api in python library | 40,023,005 | <p>Elasticsearch has a very useful feature called profile API. That is you can get very useful information on the queries performed. I am using the python elasticsearch library to perform the queries and want to be able to get those information back but I don't see anywhere in the docs that this is possible. Have you m... | 0 | 2016-10-13T13:54:10Z | 40,023,342 | <p>adding <code>profile="true"</code> to the body did the trick. In my opinion this should be an argument like size etc in the search method of the Elasticsearch class</p>
| 0 | 2016-10-13T14:08:03Z | [
"python",
"elasticsearch",
"profiler"
] |
Pandas Split 9GB CSV into 2 5GB CSVs | 40,023,026 | <p>I have a 9GB CSV and need to split it into 2 5GB CSVs.
I started out doing this:</p>
<pre><code>for i, chunk in enumerate(pd.read_csv('csv_big_file2.csv',chunksize=100000)):
chunk.drop('Unnamed: 0',axis=1,inplace=True)
chunk.to_csv('chunk{}.csv'.format(i),index=False)
</code></pre>
<p>What I need to do is ... | 1 | 2016-10-13T13:54:59Z | 40,023,552 | <p>Give this a try. </p>
<pre><code>for i, chunk in enumerate(pd.read_csv('csv_big_file2.csv',chunksize=312500)):
if i<11:
chunk.to_csv(file_name, chunksize = 312500)
else
chunk.to_csv(file_name_2, chunksize = 312500)
</code></pre>
| 0 | 2016-10-13T14:16:40Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
Pandas Split 9GB CSV into 2 5GB CSVs | 40,023,026 | <p>I have a 9GB CSV and need to split it into 2 5GB CSVs.
I started out doing this:</p>
<pre><code>for i, chunk in enumerate(pd.read_csv('csv_big_file2.csv',chunksize=100000)):
chunk.drop('Unnamed: 0',axis=1,inplace=True)
chunk.to_csv('chunk{}.csv'.format(i),index=False)
</code></pre>
<p>What I need to do is ... | 1 | 2016-10-13T13:54:59Z | 40,023,556 | <p>Library dask could be helpful. You can find documentation here: <a href="http://dask.pydata.org/en/latest/dataframe-create.html" rel="nofollow">http://dask.pydata.org/en/latest/dataframe-create.html</a></p>
| 1 | 2016-10-13T14:16:57Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
Pandas Split 9GB CSV into 2 5GB CSVs | 40,023,026 | <p>I have a 9GB CSV and need to split it into 2 5GB CSVs.
I started out doing this:</p>
<pre><code>for i, chunk in enumerate(pd.read_csv('csv_big_file2.csv',chunksize=100000)):
chunk.drop('Unnamed: 0',axis=1,inplace=True)
chunk.to_csv('chunk{}.csv'.format(i),index=False)
</code></pre>
<p>What I need to do is ... | 1 | 2016-10-13T13:54:59Z | 40,023,798 | <p>Solution is a little messy. But this should split the data based on the ~6 billion row threshold you mentioned. </p>
<pre><code>import pandas as pd
from __future__ import division
numrows = 6250000000 #number of rows threshold to be 5 GB
count = 0 #keep track of chunks
chunkrows = 100000 #read 100k rows at a tim... | 1 | 2016-10-13T14:27:01Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
Making text shrink and expand enlessly in tkinter canvas | 40,023,074 | <p>Basically, I wanted to make a program that would create a text in the cavas with the size 1, rotate it by 180 degrees (continuosly) and while that expand it to its full size (let's say 50) than keep rotating it and by the time it has made a full it spin it would have shrunk down to 1 again and then repeat the proces... | 1 | 2016-10-13T13:56:57Z | 40,030,003 | <p>I believe it is because you aren't leaving the second loop. your i variable moves on into infinity. To see an example run this and look at the output:</p>
<pre><code>from tkinter import *
import time
j = 0 # Time spent in the first while loop
k = 0 # Time spent in the second while loop
size = 1
angl = 0
i = 0
... | 0 | 2016-10-13T20:06:13Z | [
"python",
"canvas",
"tkinter",
"tkinter-canvas"
] |
How to define multidimensional dictionary with default value in python? | 40,023,106 | <p>I would like to modify next dict definition:</p>
<pre><code>class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
</code></pre>
<p>To be able to use it in next way:</p>
<pre><code>totals[year][month] += amount
</code></pre>
| 0 | 2016-10-13T13:57:57Z | 40,023,158 | <p>Use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a> with <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>. </p>
<pre><code>from collections... | 1 | 2016-10-13T14:00:26Z | [
"python",
"dictionary",
"autovivification"
] |
How to define multidimensional dictionary with default value in python? | 40,023,106 | <p>I would like to modify next dict definition:</p>
<pre><code>class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
</code></pre>
<p>To be able to use it in next way:</p>
<pre><code>totals[year][month] += amount
</code></pre>
| 0 | 2016-10-13T13:57:57Z | 40,103,773 | <p>At the end I have used Counter with tuple as a key.</p>
| 0 | 2016-10-18T08:55:37Z | [
"python",
"dictionary",
"autovivification"
] |
read data from a huge CSV file efficiently | 40,023,133 | <p>I was trying to process my huge CSV file (more than 20G), but the process was killed when reading the whole CSV file into memory. To avoid this issue, I am trying to read the second column line by line. </p>
<p>For example, the 2nd column contains data like</p>
<ol>
<li>xxx, computer is good</li>
<li><p>xxx, build... | 0 | 2016-10-13T13:59:25Z | 40,049,578 | <p>As far as I know, calling <code>csv.reader(infile)</code> opens and reads the whole file...which is where your problem lies.</p>
<p>You can just read line-by-line and parse manually: </p>
<pre><code>X=[]
with open('desc.csv', 'r') as infile:
for line in infile:
# Split on comma first
cols = [... | 0 | 2016-10-14T18:11:48Z | [
"python",
"csv"
] |
How to pass arguments to python script similar to MATLAB function script? | 40,023,143 | <p>I have a python script that implements several functions, but I want to be flexible in terms of which functions I use every time. When I would run the Python Script I would want to pass some arguments that would stand as "flags" for executing my functions.</p>
<p>In MATLAB would look something like this:</p>
<pre>... | 0 | 2016-10-13T13:59:47Z | 40,023,965 | <p>You can use the results directly just like you do in MATLAB. The argument parsing stuff is for calling python scripts from the system command prompt or shell, not from the Python shell. So have a script file like <code>myscript.py</code>:</p>
<pre><code>def metrics(minval, maxval):
"""UNTITLED Summary of this... | 3 | 2016-10-13T14:33:56Z | [
"python",
"matlab",
"function"
] |
Prints output twice when reading a file | 40,023,319 | <p>I have written the following code to write a file, convert it into integer values, save that file and then read and convert it back to the original string. However, it prints the output twice.</p>
<p>My code is</p>
<pre><code>def write():
sentence=input('What is your Statement?:')
name=input('Name your fil... | -1 | 2016-10-13T14:06:56Z | 40,024,335 | <p>In <code>write()</code>, you declare <code>position</code> as global. In <code>read1()</code>, you don't declare it as global, but since you never create a local <code>position</code> variable it's the global one that gets used. So you end up populating it twice: once in <code>write()</code> then once again in <code... | 0 | 2016-10-13T14:49:49Z | [
"python"
] |
How to create new string column extracting integers from a timestamp in Spark? | 40,023,381 | <p>I have a spark dataframe with a timestamp column, I want a new column which has strings in the format "YYYYMM".</p>
<p>I tried with: </p>
<pre><code>df.withColumn('year_month',year(col("timestamp")).cast("string")+month(col("timestamp")).cast("string"))
</code></pre>
<p>But if my timestamp is 2016-10-12, it retur... | 0 | 2016-10-13T14:09:49Z | 40,023,591 | <p>You can use <code>date_format</code>:</p>
<pre><code>from pyspark.sql.functions import date_format
df.withColumn('year_month', date_format('timestamp', 'yyyyMM'))
</code></pre>
| 0 | 2016-10-13T14:18:28Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe",
"pyspark-sql"
] |
Cannot open filename that has umlaute in python 2.7 & django 1.9 | 40,023,476 | <p>I am trying doing a thing that goes through every file in a directory, but it crashes every time it meets a file that has an umlaute in the name. Like ä.txt</p>
<p>the shortened code:</p>
<pre><code>import codecs
import os
for filename in os.listdir(WATCH_DIRECTORY):
with codecs.open(filename, 'rb', 'utf-8')... | 1 | 2016-10-13T14:13:50Z | 40,023,571 | <p>You are opening a <em>relative directory</em>, you need to make them absolute.</p>
<p>This has nothing really to do with encodings; both Unicode strings and byte strings will work, especially when soured from <code>os.listdir()</code>.</p>
<p>However, <code>os.listdir()</code> produces just the base filename, not ... | 4 | 2016-10-13T14:17:37Z | [
"python",
"django",
"python-2.7",
"encoding",
"utf-8"
] |
Pulling specific string with lxml? | 40,023,568 | <p>I have the html: </p>
<pre><code><div title="" data-toggle="tooltip" data-template="
<div class=&quot;tooltip infowin-tooltip&quot; role=&quot;tooltip&quot;>
<div class=&quot;tooltip-arrow&quot;>
<div class=&quot;tooltip-arrow-inner&quot;>
</div>
</div&g... | 0 | 2016-10-13T14:17:33Z | 40,023,860 | <p>You can use the XPath:</p>
<pre><code>//div[@class="font-160 line-110 text-default text-light"]/@data-original-title
</code></pre>
<p>in XPath, square brackets represent predicates. Predicates filter <em>which</em> nodes are returned without affecting <em>what</em> is returned. i.e. so your example would return th... | 1 | 2016-10-13T14:29:53Z | [
"python",
"python-3.x",
"lxml"
] |
Pulling specific string with lxml? | 40,023,568 | <p>I have the html: </p>
<pre><code><div title="" data-toggle="tooltip" data-template="
<div class=&quot;tooltip infowin-tooltip&quot; role=&quot;tooltip&quot;>
<div class=&quot;tooltip-arrow&quot;>
<div class=&quot;tooltip-arrow-inner&quot;>
</div>
</div&g... | 0 | 2016-10-13T14:17:33Z | 40,140,074 | <p>I ended up using <code>//div/@title[0]</code> which pulls the desired text.</p>
| 0 | 2016-10-19T19:34:37Z | [
"python",
"python-3.x",
"lxml"
] |
Tkinter - columnspan doesn't seem to affect Message | 40,023,572 | <p>I've trying to create a simple interface in Python (2.7) with Tkinter featuring a user-input box, browse button and description on the first row and a multi-line explanation spanning their width on the line below. </p>
<p>My issue is that the <code>columnspan</code> option doesn't seem to allow my <code>Message</co... | 0 | 2016-10-13T14:17:38Z | 40,024,033 | <p>The <code>Message</code> uses an aspect ratio or a character width to determine its size.</p>
<p>You can give it a width and then it will work:</p>
<pre><code> self.desc = Message(
self, text='This tool will create a .csv file in the specified folder containing the Time and '
'Latitud... | 1 | 2016-10-13T14:37:09Z | [
"python",
"tkinter"
] |
Tkinter - columnspan doesn't seem to affect Message | 40,023,572 | <p>I've trying to create a simple interface in Python (2.7) with Tkinter featuring a user-input box, browse button and description on the first row and a multi-line explanation spanning their width on the line below. </p>
<p>My issue is that the <code>columnspan</code> option doesn't seem to allow my <code>Message</co... | 0 | 2016-10-13T14:17:38Z | 40,024,049 | <p>If you change the background color of the widget you will see that it does indeed span multiple columns. </p>
<p>The main feature of the <code>Message</code> widget is that it will insert linebreaks in the text so that the text maintains a specific aspect ratio if a width is not specified. The text of a <code>Messa... | 1 | 2016-10-13T14:37:49Z | [
"python",
"tkinter"
] |
How to catch Cntrl + C in a shell script which runs a Python script | 40,023,581 | <p>I'm trying to write a simple program which runs a Python program and inspects the resulting output file:</p>
<pre><code>#!/bin/bash
rm archived_sensor_data.json
python rethinkdb_monitor_batch.py
trap "gedit archived_sensor_data.json" 2
</code></pre>
<p>The Python script <code>rethinkdb_monitor_batch.py</code> run... | 0 | 2016-10-13T14:17:53Z | 40,023,883 | <pre>
import signal
import os
os.system("rm archived_sensor_data.json")
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
os.system("gedit archived_sensor_data.json")
signal.signal(signal.SIGINT, signal_handler)
#your remaining code
#must be placed here... | 0 | 2016-10-13T14:30:52Z | [
"python",
"shell"
] |
How to catch Cntrl + C in a shell script which runs a Python script | 40,023,581 | <p>I'm trying to write a simple program which runs a Python program and inspects the resulting output file:</p>
<pre><code>#!/bin/bash
rm archived_sensor_data.json
python rethinkdb_monitor_batch.py
trap "gedit archived_sensor_data.json" 2
</code></pre>
<p>The Python script <code>rethinkdb_monitor_batch.py</code> run... | 0 | 2016-10-13T14:17:53Z | 40,024,168 | <p>You could do this by capturing the signal inside <code>rethinkdb_monitor_batch.py</code> as follows:</p>
<pre><code>#!/usr/env/bin python
try:
# your existing code here---let's assume it does the following:
import time
outfile = open( "archived_sensor_data.json", "wt" ) # NB: this already does the jo... | 2 | 2016-10-13T14:43:33Z | [
"python",
"shell"
] |
How to catch Cntrl + C in a shell script which runs a Python script | 40,023,581 | <p>I'm trying to write a simple program which runs a Python program and inspects the resulting output file:</p>
<pre><code>#!/bin/bash
rm archived_sensor_data.json
python rethinkdb_monitor_batch.py
trap "gedit archived_sensor_data.json" 2
</code></pre>
<p>The Python script <code>rethinkdb_monitor_batch.py</code> run... | 0 | 2016-10-13T14:17:53Z | 40,128,072 | <p>The other answers involve modifying the Python code itself, which is less than ideal since I don't want it to contain code related only to the testing. Instead, I found that the following bash script useful:</p>
<pre><code>#!/bin/bash
rm archived_sensor_data.json
python rethinkdb_monitor_batch.py ; gedit archived_... | 0 | 2016-10-19T09:59:44Z | [
"python",
"shell"
] |
Detect the changes in a file and write them in a file | 40,023,651 | <p>I produced a script that detects the changes on files that are located in a specific directory. I'm trying to write all these changes to a <code>changes.txt</code> file. For this purpose I'm using the <code>sys.stdout = open('changes.txt','w')</code> instruction.</p>
<p>The problem is that whenever I run the script... | 0 | 2016-10-13T14:20:46Z | 40,023,827 | <p>I'd recommend something like</p>
<pre><code>#!/usr/bin/python
import time
import sys
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def __init__(self, f):
self.f = f
def on_modified(self, event):
self.f.wr... | 0 | 2016-10-13T14:28:15Z | [
"python",
"file"
] |
Python: good way to pass variable to multiple function calls | 40,023,663 | <p>Need a help with the next situation. I want to implement debug mode in my script through printing small completion report in functions with command executed name and ellapsed time like:</p>
<pre><code>def cmd_exec(cmd):
if isDebug:
commandStart = datetime.datetime.now()
print commandStart
... | 3 | 2016-10-13T14:21:31Z | 40,023,778 | <p><code>isDebug</code> is state that applies to the application of a function <code>cmd_exec</code>. Sounds like a use-case for a class to me.</p>
<pre><code>class CommandExecutor(object):
def __init__(self, debug):
self.debug = debug
def execute(self, cmd):
if self.debug:
comman... | 2 | 2016-10-13T14:26:08Z | [
"python",
"function",
"arguments",
"global-variables"
] |
Python: good way to pass variable to multiple function calls | 40,023,663 | <p>Need a help with the next situation. I want to implement debug mode in my script through printing small completion report in functions with command executed name and ellapsed time like:</p>
<pre><code>def cmd_exec(cmd):
if isDebug:
commandStart = datetime.datetime.now()
print commandStart
... | 3 | 2016-10-13T14:21:31Z | 40,023,830 | <p>Python has a built-in <code>__debug__</code> variable that could be useful.</p>
<pre><code>if __debug__:
print 'information...'
</code></pre>
<p>When you run your program as <code>python test.py</code>, <code>__debug__</code> is <code>True</code>. If you run it as <code>python -O test.py</code>, it will be <co... | 2 | 2016-10-13T14:28:17Z | [
"python",
"function",
"arguments",
"global-variables"
] |
Python: good way to pass variable to multiple function calls | 40,023,663 | <p>Need a help with the next situation. I want to implement debug mode in my script through printing small completion report in functions with command executed name and ellapsed time like:</p>
<pre><code>def cmd_exec(cmd):
if isDebug:
commandStart = datetime.datetime.now()
print commandStart
... | 3 | 2016-10-13T14:21:31Z | 40,024,533 | <p>You can use a module to create variables that are shared. This is better than a global because it only affects code that is specifically looking for the variable, it doesn't pollute the global namespace. It also lets you define something without your main module needing to know about it.</p>
<p>This works because m... | 1 | 2016-10-13T14:59:36Z | [
"python",
"function",
"arguments",
"global-variables"
] |
Python: good way to pass variable to multiple function calls | 40,023,663 | <p>Need a help with the next situation. I want to implement debug mode in my script through printing small completion report in functions with command executed name and ellapsed time like:</p>
<pre><code>def cmd_exec(cmd):
if isDebug:
commandStart = datetime.datetime.now()
print commandStart
... | 3 | 2016-10-13T14:21:31Z | 40,032,915 | <p>Specifically for this, I would use partials/currying, basically pre-filling a variable.</p>
<pre><code>import sys
from functools import partial
import datetime
def _cmd_exec(cmd, isDebug=False):
if isDebug:
command_start = datetime.datetime.now()
print command_start
print cmd
else:... | 0 | 2016-10-14T00:02:17Z | [
"python",
"function",
"arguments",
"global-variables"
] |
Trying to map the 'Private IP' of my computer with python | 40,023,678 | <p>I want to filter the IPv4 ips and take the one which belong to my LAN (and not to my VMware network).
I coded this thing:</p>
<pre><code>print re.findall(r'[0-255]\.[0-255]\.[0-255]\.[0-255]', str([y for y in filter(lambda x: 'IPv4 Address' in x, os.popen("ipconfig").readlines())]))
</code></pre>
<p>This part:</p>... | 0 | 2016-10-13T14:22:07Z | 40,023,819 | <p>Watch out! <code>[0-255]</code> isn't a number range in regex ! (in fact it means <em>one</em> character in the list 0,1,2,5)</p>
<p>You should use <code>\d{1,3}</code> if you want a three digit number, then extract groups if you want to check if the number is in the range.</p>
| 0 | 2016-10-13T14:27:58Z | [
"python"
] |
Django url config with multiple urls matching | 40,023,708 | <p>in one of our Django applications we have defined multiple urls for views.</p>
<p>The first URL matches a general feature with pk and a second match group.
The second URL matches a subfeature with pk.</p>
<p>Between this two urls more urls are defined, so it is not easy to see them all at once. Or, for example, t... | 0 | 2016-10-13T14:23:05Z | 40,023,810 | <p>There's no general answer to that. Any change that makes an url more generic may break other urls that follow it.</p>
<p>In this case, you can swap the urls so <code>subfeature/</code> will match the subfeature url, and any other url will fall through and match <code>views.b</code>:</p>
<pre><code>url(r'^subfeatur... | 1 | 2016-10-13T14:27:36Z | [
"python",
"django"
] |
Django url config with multiple urls matching | 40,023,708 | <p>in one of our Django applications we have defined multiple urls for views.</p>
<p>The first URL matches a general feature with pk and a second match group.
The second URL matches a subfeature with pk.</p>
<p>Between this two urls more urls are defined, so it is not easy to see them all at once. Or, for example, t... | 0 | 2016-10-13T14:23:05Z | 40,031,853 | <p>As a general rule, you need to take the order into consideration when defining urlpatterns.</p>
<p>The thing is django will try to find the match by trying to fit a url into every pattern and will try to get to the views whenever it finds the first url matching.</p>
<pre><code>url(r'^(?P<pk>[^/]+)/', views.b... | 0 | 2016-10-13T22:09:07Z | [
"python",
"django"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.