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 |
|---|---|---|---|---|---|---|---|---|---|
Catching only one group out of two on both sides of | | 37,646,097 | <p>I need to catch something inside double or single quotes, logically, I do this:</p>
<pre><code>>>> re.match( '"(\d+)"|\'(\d+)\'', "'123'" ).groups()
(None, '123')
</code></pre>
<p>But for some reason two groups are returned, why?..</p>
| -1 | 2016-06-05T19:48:51Z | 37,646,109 | <p>Because your regex contains two groups and <code>groups()</code> returns "<em>a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern</em>" (<a href="https://docs.python.org/3/library/re.html#re.match.groups" rel="nofollow">https://docs.python.org/3/library/re.html#re.m... | 0 | 2016-06-05T19:49:54Z | [
"python",
"regex",
"python-3.x"
] |
Catching only one group out of two on both sides of | | 37,646,097 | <p>I need to catch something inside double or single quotes, logically, I do this:</p>
<pre><code>>>> re.match( '"(\d+)"|\'(\d+)\'', "'123'" ).groups()
(None, '123')
</code></pre>
<p>But for some reason two groups are returned, why?..</p>
| -1 | 2016-06-05T19:48:51Z | 37,646,152 | <pre><code>s1 = '..."123"...'
s2 = "...'123'..."
s3 = """...'123"..."""
>>> re.findall(r'(\'\d+\'|"\d+")', s1)
['"123"']
>>> re.findall(r'(\'\d+\'|"\d+")', s2)
["'123'"]
>>> re.findall(r'(\'\d+\'|"\d+")', s3)
[]
</code></pre>
| 1 | 2016-06-05T19:55:05Z | [
"python",
"regex",
"python-3.x"
] |
Read analog signal in raspberry without an interface | 37,646,174 | <p>I need to read an analog signal in raspberry and for this purpose I bought an MCP3002 circuit. i plug it in with the correct connections and i have found sample codes over the internet but it doesn't work. </p>
<p>Do I need to have an interface or I can do the job without it? Do you have any ideas what can go wrong... | 1 | 2016-06-05T19:56:49Z | 37,861,019 | <p>The code below may help you. Please try it and tell me result.</p>
<pre><code>import spidev
import time
import RPi.GPIO as GPIO
spi_ce0 = spidev.Spidev()
spi_ce0.open(0,0)
# channel1: adc1, channel2: adc2
adc1 = spi_ce0.xfer2([1,(8+0)<<4,0])
adc2 = spi_ce0.xfer2([1,(8+1)<<4,0])
</code></pre>
| 0 | 2016-06-16T13:40:49Z | [
"python",
"raspberry-pi"
] |
Read analog signal in raspberry without an interface | 37,646,174 | <p>I need to read an analog signal in raspberry and for this purpose I bought an MCP3002 circuit. i plug it in with the correct connections and i have found sample codes over the internet but it doesn't work. </p>
<p>Do I need to have an interface or I can do the job without it? Do you have any ideas what can go wrong... | 1 | 2016-06-05T19:56:49Z | 37,862,598 | <p>This is a very wide question because the problem can be a result of many things, hardware or software.</p>
<p>To narrow it down I would suggest to measure if there actually is any data transfer on the I/Os. If you don't have an oscilloscope it will probably be OK to use a LED (and a suitable resistor of course) to ... | 0 | 2016-06-16T14:50:24Z | [
"python",
"raspberry-pi"
] |
Plot only works when hard coded or Copy/Pasted | 37,646,178 | <p><strong>Update 2 Full Error Code:</strong> </p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Desktop\Radar2.py", line 156, in <module>
radar = ComplexRadar(fig1, variables, ranges)
File "C:\Users\Desktop\Radar2.py", line 127, in __init__
num=n_ordinate_levels)
File "C:\Python... | -1 | 2016-06-05T19:56:59Z | 37,647,177 | <p>The error is in this line:</p>
<pre><code>for i, ax in enumerate(axes):
grid = np.linspace(*ranges[i],
num=n_ordinate_levels)
</code></pre>
<p>And it is because when you read those from a file, the elements in <code>ranges</code> are not floats/ints:</p>
<pre><code>ranges
Out[24]:
[('... | 0 | 2016-06-05T21:56:52Z | [
"python",
"python-2.7",
"numpy",
"matplotlib"
] |
Keyword/phrase extraction from free text using NLTK and Python for structured queries | 37,646,254 | <p>I want to interpret specific keywords from a free text such as "I want to order boiled eggs and spinach soup from nearest restaurants' and use them to search content from my database.
For e.g i want to extract following specific keyword(s) and want an output similar to following like a tuple of (Keyword type , Keyw... | 1 | 2016-06-05T20:05:29Z | 37,646,309 | <p>It's not that difficult, but not that super precise either.</p>
<p>Use NLTK's <a href="http://www.nltk.org/book/ch05.html" rel="nofollow">PoS Tagging</a>, then extract <code>nouns</code> and <code>compound nouns</code>, and use them in your DB queries.</p>
<p>A natural sentence is practically has two parts, an act... | 2 | 2016-06-05T20:12:17Z | [
"python",
"nlp",
"nltk",
"information-retrieval"
] |
How can I make sure users are turning in correct input, for Guess game in python 3.5.1? | 37,646,360 | <p>This is my code:</p>
<pre><code>from random import randint
print("What is your name?")
name=input()
tries=0
number= randint(1,100)
print("Hello, %s guess a number from 0 to 100" % name)
while tries < 8:
print("Take a Guess")
guess=input()
guess=int(guess)
if guess < number:
print("Too ... | 0 | 2016-06-05T20:18:26Z | 37,646,491 | <p>Change the line <code>guess=int(guess)</code> into this:</p>
<pre><code>guess=int(re.search(r'\d+', guess).group())
</code></pre>
| 0 | 2016-06-05T20:34:30Z | [
"python",
"validation",
"python-3.x",
"input"
] |
How can I make sure users are turning in correct input, for Guess game in python 3.5.1? | 37,646,360 | <p>This is my code:</p>
<pre><code>from random import randint
print("What is your name?")
name=input()
tries=0
number= randint(1,100)
print("Hello, %s guess a number from 0 to 100" % name)
while tries < 8:
print("Take a Guess")
guess=input()
guess=int(guess)
if guess < number:
print("Too ... | 0 | 2016-06-05T20:18:26Z | 37,646,723 | <p>Attempt to parse entered value with <code>guess=int(guess)</code> can lead to different exceptions. Quick and dirty way to fix it - is to wrap it in <code>try ... except</code> block. Like:</p>
<pre><code>try:
guess=int(guess)
except ValueError:
print("Cannot understand your input. Pls, try again")
cont... | 0 | 2016-06-05T21:01:17Z | [
"python",
"validation",
"python-3.x",
"input"
] |
Trouble with writing files inside loop (Python) | 37,646,405 | <p>I've been having trouble with the following piece of Python code. It's running without errors, but it isn't exactly giving me the expected output; no files at all are being written.</p>
<pre><code>for l in h:
r=l.rfind(",")+1
s=l[r:-2]
j=0
while j&l... | 0 | 2016-06-05T20:23:30Z | 37,646,439 | <p>You need to indent the code that is in our for-loop. Indentation is very important in python since there isn't the use of curly brackets or semi-colons. Hopefully this will solve the problem you are having!</p>
<p>:) Derek</p>
<pre><code>for l in h:
r=l.rfind("... | 0 | 2016-06-05T20:27:22Z | [
"python"
] |
Trouble with writing files inside loop (Python) | 37,646,405 | <p>I've been having trouble with the following piece of Python code. It's running without errors, but it isn't exactly giving me the expected output; no files at all are being written.</p>
<pre><code>for l in h:
r=l.rfind(",")+1
s=l[r:-2]
j=0
while j&l... | 0 | 2016-06-05T20:23:30Z | 37,646,604 | <p>The problem is that you set s to a string with <code>s=l[r:-2]</code> and then later check for an int with <code>if s[j]==1:</code></p>
<p>Since the condition is never met there won't be any files written. Check for the string "1" instead and it will work:</p>
<pre><code>for l in h: ... | 0 | 2016-06-05T20:49:02Z | [
"python"
] |
How could I do one hot encoding with multiple values in one cell? | 37,646,473 | <p>I have this table in Excel:</p>
<pre><code>id class
0 2 3
1 1 3
2 3 5
</code></pre>
<p>Now, I want to do a 'special' one-hot encoding in Python.
For each id in the first table, there are two numbers. Each number corresponds to a class (class1, class2, etc.). The second table is created based off of the fi... | 1 | 2016-06-05T20:32:21Z | 37,690,257 | <p>Does this satisfy your problem as stated?</p>
<pre><code>#!/usr/bin/python
input = [
(0, (2,3)),
(1, (1,3)),
(2, (3,5)),
]
maximum = max(reduce(lambda x, y: x+list(y[1]), input, []))
# Or ...
# maximum = 0
# for i, classes in input:
# maximum = max(maximum, *classes)
# print header.
print "\t".joi... | 3 | 2016-06-07T22:11:01Z | [
"python",
"one-hot"
] |
How could I do one hot encoding with multiple values in one cell? | 37,646,473 | <p>I have this table in Excel:</p>
<pre><code>id class
0 2 3
1 1 3
2 3 5
</code></pre>
<p>Now, I want to do a 'special' one-hot encoding in Python.
For each id in the first table, there are two numbers. Each number corresponds to a class (class1, class2, etc.). The second table is created based off of the fi... | 1 | 2016-06-05T20:32:21Z | 37,776,403 | <p>It may be simpler to split the original dataframe into 3 columns:</p>
<pre><code>id class_a class_b
0 2 3
1 1 3
2 3 5
</code></pre>
<p>And then perform a normal one-hot encoding on that. Afterwards you may end up with duplicates of columns like:</p>
<pre><code>id ... class_a_3... | 3 | 2016-06-12T16:10:02Z | [
"python",
"one-hot"
] |
How could I do one hot encoding with multiple values in one cell? | 37,646,473 | <p>I have this table in Excel:</p>
<pre><code>id class
0 2 3
1 1 3
2 3 5
</code></pre>
<p>Now, I want to do a 'special' one-hot encoding in Python.
For each id in the first table, there are two numbers. Each number corresponds to a class (class1, class2, etc.). The second table is created based off of the fi... | 1 | 2016-06-05T20:32:21Z | 37,777,624 | <p>You need to make your variables to be <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="nofollow"><code>categorical</code></a> and then you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>one hot encoding</code></a> as sho... | 3 | 2016-06-12T18:22:06Z | [
"python",
"one-hot"
] |
How can I slice a dataframe by timestamp, when timestamp isn't classified as index? | 37,646,501 | <p>How can I split my pandas dataframe by using the timestamp on it?</p>
<p>I got the following prices when I call <code>df30m</code>:</p>
<pre><code> Timestamp Open High Low Close Volume
0 2016-05-01 19:30:00 449.80 450.13 449.80 449.90 74.1760
1 2016-05-01 20:00:00 449.90... | 1 | 2016-06-05T20:35:34Z | 37,646,517 | <p>You can use <code>loc</code> to index your data. Do you know if your timestamps at datetime.datetime formats or Pandas Timestamps?</p>
<pre><code>df30m.loc[(df30m.Timestamp <= d0) & (df30m.Timestamp >= d1)]
</code></pre>
<p>You can set the index to the Timestamp column and then index as follows:</p>
<p... | 1 | 2016-06-05T20:38:16Z | [
"python",
"pandas",
"dataframe",
"split",
"timestamp"
] |
Django querying top weekly hits in a Database | 37,646,574 | <p>I am currently using django's ORM functions to build a viable backend to my web application. I have an Model object in my models.py that relates to and is displayed in a specific url which keeps track of hits using <a href="https://github.com/thornomad/django-hitcount" rel="nofollow">https://github.com/thornomad/dja... | 0 | 2016-06-05T20:45:54Z | 37,647,461 | <p>Never used this package, but after checking the <a href="https://github.com/thornomad/django-hitcount/blob/master/hitcount/models.py" rel="nofollow">models definition</a>, they use <code>GFK</code> to store hitcounts for any or your models, so in order to filter/annotate on their models you can define your own <a hr... | 1 | 2016-06-05T22:34:56Z | [
"python",
"django",
"web-applications"
] |
Modify an element in a nested dict given a "path" to it | 37,646,631 | <p>Given a "path" of a list of indices (of an arbitrary length) and a nested Python <code>list</code>/<code>dict</code> object, how can I write to the part of the object at a list?</p>
<p>For example, this might be my object (it's loaded from a JSON file):</p>
<pre><code>data = {"dogs":[{"tail": True, "properties":{"... | 2 | 2016-06-05T20:51:39Z | 37,646,687 | <p>This would be probably a good alternative option, but I find <a href="https://pypi.python.org/pypi/jsonpath-rw" rel="nofollow"><code>jsonpath-rw</code></a> library a good way to navigate and search inside a JSON structure:</p>
<pre><code>>>> from jsonpath_rw import jsonpath, parse
>>>
>>>... | 3 | 2016-06-05T20:57:17Z | [
"python",
"dictionary",
"nested",
"pass-by-reference",
"pass-by-value"
] |
How to handle google api oauth in this app? | 37,646,652 | <p>My client asked me to build a tool that would let him and his partners to upload video to youtube to his channel automatically .</p>
<p>For example let's say that my client is A and he has some buisness partners . A want to be able to upload videos to his channel, that is easy to do, but the problem here is to let ... | 0 | 2016-06-05T20:53:23Z | 37,647,153 | <p>You can create a server-side script in which you use Google OAuth to upload videos to A's account.</p>
<p>Then you can create a client-side app which allows your clients B and C to upload their videos to the server; on completion, the server can then upload them to A's account.</p>
<p>Alternatively, to avoid uploa... | 2 | 2016-06-05T21:54:08Z | [
"python",
"google-oauth"
] |
When would an informative __repr__ be dangerous? | 37,646,702 | <p>I am having trouble understanding why the default <code>__repr__</code>'s implementation isn't more informative.</p>
<p>This answer on <a href="http://stackoverflow.com/a/2626364/3646408">http://stackoverflow.com/a/2626364/3646408</a>
states </p>
<blockquote>
<p>having a default for <strong>repr</strong> which ... | 0 | 2016-06-05T20:58:56Z | 37,646,756 | <p>That is a valid use case for some hierarchical structure, when node can have children that reference their parent</p>
<p>As an example,</p>
<pre><code>root = Node()
child = Node()
child.parent=root
root.children = [child]
</code></pre>
| 2 | 2016-06-05T21:04:42Z | [
"python",
"repr"
] |
When would an informative __repr__ be dangerous? | 37,646,702 | <p>I am having trouble understanding why the default <code>__repr__</code>'s implementation isn't more informative.</p>
<p>This answer on <a href="http://stackoverflow.com/a/2626364/3646408">http://stackoverflow.com/a/2626364/3646408</a>
states </p>
<blockquote>
<p>having a default for <strong>repr</strong> which ... | 0 | 2016-06-05T20:58:56Z | 37,646,759 | <p>Consider a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model" rel="nofollow">DOM</a> tree where a node contains references to its children, and every child contains a reference to its parent.</p>
<p>(It also happens between siblings via <code>nextSibling</code>/<code>previousSibling</c... | 2 | 2016-06-05T21:04:46Z | [
"python",
"repr"
] |
When would an informative __repr__ be dangerous? | 37,646,702 | <p>I am having trouble understanding why the default <code>__repr__</code>'s implementation isn't more informative.</p>
<p>This answer on <a href="http://stackoverflow.com/a/2626364/3646408">http://stackoverflow.com/a/2626364/3646408</a>
states </p>
<blockquote>
<p>having a default for <strong>repr</strong> which ... | 0 | 2016-06-05T20:58:56Z | 37,646,784 | <p>This could happen with any type of object with bidirectional references. For instance, a class that represents family relationships, where each person has a reference to their spouse, or where parents have references to their children and children have references to their parents.</p>
<p>PHP's <code>print_r()</code... | 2 | 2016-06-05T21:07:07Z | [
"python",
"repr"
] |
Converting Tuple Index to a Datetime index | 37,646,829 | <p>I am averaging my data frame by month/day/year etc and have run into trouble with my index being converted from Datetime to Tuple. I want to have my index in Datetime so that I can export it to excel for other non-python users and have it still make sense with timestamps.</p>
<p>This what my Df look like:</p>
<pre... | 2 | 2016-06-05T21:13:21Z | 37,647,764 | <p>First you should use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">pd.to_datetime</a> to convert <code>Date Time</code> values to <code>datetime</code> then you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.h... | 0 | 2016-06-05T23:25:19Z | [
"python",
"datetime",
"pandas",
"tuples"
] |
Converting Tuple Index to a Datetime index | 37,646,829 | <p>I am averaging my data frame by month/day/year etc and have run into trouble with my index being converted from Datetime to Tuple. I want to have my index in Datetime so that I can export it to excel for other non-python users and have it still make sense with timestamps.</p>
<p>This what my Df look like:</p>
<pre... | 2 | 2016-06-05T21:13:21Z | 37,647,919 | <p>I think you can convert <code>index</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_period.html" rel="nofollow"><code>to_period</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> b... | 2 | 2016-06-05T23:52:56Z | [
"python",
"datetime",
"pandas",
"tuples"
] |
dict.fromkeys doesn't work as expected for floating point keys | 37,646,843 | <p>I have a Python list like so:</p>
<pre><code>import numpy
thresholds = numpy.linspace(0.7, 0.9, 21)
print(thresholds)
[0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9]
</code></pre>
<p>When I try to create a <code>dict</code> from this li... | 0 | 2016-06-05T21:14:46Z | 37,646,885 | <p>If you're getting upset about the floating point representations you should try converting the values to <code>decimal</code> types. Otherwise, just let it go.</p>
<pre><code>print('%1.17f' % 0.7)
print('%1.2f' % 0.7)
0.69999999999999996
0.70
</code></pre>
| 2 | 2016-06-05T21:20:09Z | [
"python",
"list",
"dictionary"
] |
dict.fromkeys doesn't work as expected for floating point keys | 37,646,843 | <p>I have a Python list like so:</p>
<pre><code>import numpy
thresholds = numpy.linspace(0.7, 0.9, 21)
print(thresholds)
[0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9]
</code></pre>
<p>When I try to create a <code>dict</code> from this li... | 0 | 2016-06-05T21:14:46Z | 37,646,958 | <p>You're better of converting the floats from <code>numpy.linspace</code> into strings. Using <code>floats</code> directly as dictionary keys in python is a terrible idea, for reasons relating to precision (you can't bet on 100% precision) and the way floating point numbers are evaluated.</p>
<pre><code>thresholds = ... | 2 | 2016-06-05T21:29:00Z | [
"python",
"list",
"dictionary"
] |
Get synonymes with awn | 37,646,844 | <p>I use arabic wordnet to get synonyms, i want to integrate it to my code to get the matrix of similarity. The idea is if someone use the synonym of word it will give 1 what is mean similar. so there is the code :</p>
<pre><code># -*- coding: utf-8 -*-
from numpy import zeros
from scipy.linalg import svd
from math i... | 1 | 2016-06-05T21:14:48Z | 37,647,001 | <p>You have one problem, you text is not vocalized and also the stemmer normalize the words before stemming them while the Arabic Wordnet require words to be vocalized exactly as it is stored. </p>
<p>You should patch the wordnet to list words by unvocalized version of words. </p>
| 1 | 2016-06-05T21:33:39Z | [
"python",
"arabic"
] |
pystan .plot() plots trace summary twice | 37,646,860 | <p>This is probably a stupid question, but whenever I'm using the .plot() function it plots the summary twice. Anyone knows, why it does that and how I can stop it?
<a href="http://i.stack.imgur.com/jRdlI.png" rel="nofollow"><img src="http://i.stack.imgur.com/jRdlI.png" alt="pystan.plot()"></a></p>
<p>As you can see I... | 1 | 2016-06-05T21:17:11Z | 38,447,154 | <p>This is caused by the <code>%matplotlib inline</code> statement drawing more than you want it to. The <code>StanFit4Model.plot</code> method calls <code>matplotlib.pyplot.subplot</code>, and that call itself will draw a plot when your notebook has <code>%matplotlib inline</code>. Then the method returns the <code>Fi... | 1 | 2016-07-18T22:54:01Z | [
"python",
"jupyter",
"stan"
] |
Computing integral with the Trapezoidal Rule (the approximate value of the integral, and the number of iterations) | 37,646,910 | <p>The program needs to compute define integral with a predetermined
accuracy (eps) with the Trapezoidal Rule and my function needs to return: </p>
<p>1.the approximate value of the integral.</p>
<p>2.the number of iterations.</p>
<p>My code:</p>
<pre><code> from math import *
def f1(x):
return (x ** ... | -2 | 2016-06-05T21:22:58Z | 37,660,472 | <p>You implemented the math wrong. The error is in the lines</p>
<pre><code>for i in range(n):
sum = sum + f(a + i * h)
</code></pre>
<p><code>range(n)</code> always starts at 0, so in your first iteration you just add the <code>f(a)</code> term again.
If you replace it with</p>
<pre><code>for i in range(1, n):
... | 0 | 2016-06-06T14:49:54Z | [
"python",
"function",
"python-3.x",
"rule",
"integral"
] |
Computing integral with the Trapezoidal Rule (the approximate value of the integral, and the number of iterations) | 37,646,910 | <p>The program needs to compute define integral with a predetermined
accuracy (eps) with the Trapezoidal Rule and my function needs to return: </p>
<p>1.the approximate value of the integral.</p>
<p>2.the number of iterations.</p>
<p>My code:</p>
<pre><code> from math import *
def f1(x):
return (x ** ... | -2 | 2016-06-05T21:22:58Z | 37,666,851 | <p>The trapezoidal rule of integration simply says that an approximation to the integral $\int_a^b f(x) dx$ is <code>(b-a) (f(a)+f(b))/2</code>. The error is proportional to <code>(b-a)^2</code>, so that it is possible to have a better estimate using the <em>composite</em> rule, i.e., subdividing the initial interval i... | 0 | 2016-06-06T21:02:21Z | [
"python",
"function",
"python-3.x",
"rule",
"integral"
] |
Querying LDAP by date | 37,646,962 | <p><strong>The Problem:</strong></p>
<p>Certain LDAP date fields, like <code>createTimestamp</code> or <code>pwdChangedTime</code>, are kept in a <a href="https://en.wikipedia.org/wiki/GeneralizedTime" rel="nofollow"><em>"generalized datetime format"</em></a>:</p>
<pre><code>{"createTimestamp": "20100226142156Z"}
</c... | 0 | 2016-06-05T21:29:37Z | 37,646,963 | <p>First of all, we need a reusable function to <em>convert from datetime to a generalized time format</em>:</p>
<pre><code>def convert_datetime_to_generalized_time(dt):
"""Convert datetime object to generalized time format."""
dt = dt.timetuple()
gtime = str(dt.tm_year) + ''.join('0' * (2 - len(str(item))... | 1 | 2016-06-05T21:29:37Z | [
"python",
"datetime",
"ldap",
"python-ldap"
] |
Spoof IP address in Python | 37,647,033 | <p>There is a certain data API which I need to call to fetch some data. Imagine there are few million such records. For each such record, I construct the data URL (that returns a JSON response) from the record id and API key, fetch the response and put it to my local database. Now if I do it on my Mac, even with a 16 G... | 0 | 2016-06-05T21:38:13Z | 37,647,222 | <p>Use the <a href="https://docs.python.org/2/library/socket.html" rel="nofollow"><code>socket.bind</code></a> method to specify the source address of the network connection.</p>
<pre><code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind socket to a particular IP. port 0 allows it to select ... | 0 | 2016-06-05T22:01:51Z | [
"python",
"ip",
"urllib"
] |
making function lazy in Python | 37,647,085 | <p>I want to write a wrapper function for <code>eternity</code> that will make it behave as if it's being lazily evaluated. In other words, its functionality should be made identical to that of the function <code>lazyeternity</code> below. I have this function <code>packageN</code> that takes a function and packages it... | -1 | 2016-06-05T21:44:40Z | 37,647,154 | <p>To make both <code>eternity</code> work, simply remove the <code>()</code>. You want to return a function, not the evaluation of a function (infinite loop).</p>
| 1 | 2016-06-05T21:54:16Z | [
"python",
"lambda",
"lazy-evaluation"
] |
making function lazy in Python | 37,647,085 | <p>I want to write a wrapper function for <code>eternity</code> that will make it behave as if it's being lazily evaluated. In other words, its functionality should be made identical to that of the function <code>lazyeternity</code> below. I have this function <code>packageN</code> that takes a function and packages it... | -1 | 2016-06-05T21:44:40Z | 37,648,989 | <p>The difference between <code>lazyeternity</code> and <code>eternity</code> as returned by <code>packageN</code> is that calling <code>lazyeternity</code> returns a lambda, whereas <code>eternity</code> <em>is</em> a lambda which, when called, runs forever.</p>
<p>To make <code>packageN</code> return something that ... | 2 | 2016-06-06T03:02:02Z | [
"python",
"lambda",
"lazy-evaluation"
] |
Echo bot using FB Messenger and Django | 37,647,099 | <p>I have the following view given below:</p>
<pre><code>import json, requests
from pprint import pprint
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
def echo(fb_id, received_message):
post_mes... | 1 | 2016-06-05T21:46:40Z | 37,730,642 | <p>If I read the tutorial clearly, it said outside but not inside...</p>
<pre class="lang-py prettyprint-override"><code># yomamabot/fb_yomamabot/views.py
# This function should be outside the BotsView class
def post_facebook_message(fbid, recevied_message):
post_message_url = 'https://graph.facebook.co... | 1 | 2016-06-09T15:44:28Z | [
"python",
"django",
"bots",
"messenger"
] |
Flask uWSGI - ImportError: No module named request | 37,647,211 | <p>I'm using <strong>Python 2.7.11 :: Anaconda 2.4.0 (x86_64)</strong></p>
<p>I am trying to learn <code>uWSGI</code>. I am able to get a "Hello World" <code>Python</code> <code>uWSGI</code> app started from this tutorial: <a href="http://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#the-first-wsgi-applicati... | 1 | 2016-06-05T22:00:32Z | 37,647,512 | <p>There seems to be something messed up with your python version. This is the source code from <a href="https://github.com/pallets/werkzeug/blob/0.11-maintenance/werkzeug/http.py#L25" rel="nofollow"><code>werkzeug.http.py</code></a>. The first <code>import</code> should work if you have python 2.x, the second should w... | 2 | 2016-06-05T22:44:14Z | [
"python",
"flask",
"uwsgi",
"werkzeug"
] |
Python Flask and Psycopg -- Query string request.get in WHERE | 37,647,258 | <p>What is the correct way to pass query string variables in flask to psycopg as a parameter in a WHERE clause?</p>
<p>Specifically, if the variable is not set, I do not want the variable added to the WHERE clause:</p>
<pre><code> id = int(request.args.get('id'))
cur.execute("SELECT * FROM data WHERE id = %s;", id)
... | 2 | 2016-06-05T22:06:35Z | 37,647,280 | <p>Just issue a different query if no (valid) <code>id</code> query parameter was provided:</p>
<pre><code>id = request.args.get('id', type=int)
if id is not None:
cur.execute("SELECT * FROM data WHERE id = %s", (id,))
else:
# No (valid) id given, give everything
cur.execute("SELECT * FROM data")
</code></... | 3 | 2016-06-05T22:09:30Z | [
"python",
"flask",
"psycopg"
] |
Wrong Output for Array Operations Using GPU | 37,647,363 | <p>I'm trying to write a function that performs element-wise addition, subtraction, multiplication, or division on 2d arrays using Anaconda Accelerate, but the function I wrote keeps getting the wrong answer. Not sure what's going on.</p>
<pre><code>import numpy as np
from numba import cuda
#Define functions
ADD, SUB... | 2 | 2016-06-05T22:21:50Z | 37,648,049 | <p>Your code works for me if I change the <code>jit</code> signature to:</p>
<pre><code>@cuda.jit('void(float64[:,:], float64[:,:], int64)')
</code></pre>
<p>or if I change the definition of <code>a</code> and <code>op</code> to:</p>
<pre><code>a = np.array([[1., 2], [3, 4]]).astype(np.complex64)
...
op = np.int8(AD... | 1 | 2016-06-06T00:15:55Z | [
"python",
"numpy",
"anaconda",
"numba"
] |
Internal Server Error on Azure Flask Web App | 37,647,368 | <p>I created a Flask web app hosted on Azure with a Dreamspark subscription. It uses libraries such as Numpy, Scipy and Theano.</p>
<p>When I deploy the app using a simple Theano calculations, it works perfectly. However, when I change the code to a more complex Theano calculation, I get an Internal Server Error.</p>
... | 0 | 2016-06-05T22:22:56Z | 37,651,478 | <p>There are many reasons for causing the issue with theano, such as multithreads, using GPUs, memory limits, etc. But according to the code and the error information, I can't be sure what the reason is. </p>
<p>I suggest that you can try to refer to the theano document "<a href="http://deeplearning.net/software/thean... | 0 | 2016-06-06T07:11:52Z | [
"python",
"azure",
"flask",
"fastcgi",
"theano"
] |
Expand index notation equation using sympy | 37,647,370 | <p>Below I have an equation written using index notation. This equation can be expressed with the six equations on the figure. </p>
<p><a href="http://i.stack.imgur.com/zYmIy.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/zYmIy.jpg" alt="Equation using index notation"></a></p>
<p>The first equation is expande... | 1 | 2016-06-05T22:23:08Z | 37,680,567 | <p>Currently, there is no straightforward way to do what you ask.</p>
<p>I shall suggest a trick that should work, by using <em>IndexedBase</em> (that is, symbols indexed by other symbols), followed by a replacement.</p>
<p>Declare your symbols:</p>
<pre><code>U = IndexedBase("U")
l = symbols("lambda")
var("mu u v w... | 2 | 2016-06-07T13:18:30Z | [
"python",
"sympy"
] |
Create dynamic text files with data from another CSV file using python | 37,647,393 | <p>I need to dynamically create .txt files with the some portion of data from another CSV file. The csv file contains-</p>
<blockquote>
<p>"Cox's Bazar is the longest natural sea beach in the world. The beach
in Cox's Bazar is an unbroken 125 km sandy sea beach with a gentle
slope.It is located 150 km south of t... | 0 | 2016-06-05T22:25:38Z | 37,647,635 | <p>The input is not in CSV (<em>comma separated values</em>) format, it is plain text. So you don't need to worry about the <code>csv</code> module.</p>
<p>Open the input file, read a line and, if it is not an blank line, open an outfile and write the line to it.</p>
<p>You already know how to detect blank lines usin... | 0 | 2016-06-05T23:01:24Z | [
"python",
"csv"
] |
Python-problems with parsing list in JSON Format | 37,647,444 | <p>I'm using python 2.7 to parse value in JSON format
there is my script:</p>
<pre><code>from collections import OrderedDict
import json
import os
import pickle
d=OrderedDict([(3215, False), (3216, False), (8004, False), (8002, False), (3589, False), (3753, False), (3752, True), (3755, False), (3754, False)]))... | -3 | 2016-06-05T22:32:28Z | 37,647,478 | <p>You double-encoded the dictionary to JSON, then to pickle, in the file:</p>
<pre><code>json_format = json.dumps(d.items())
Fichier =open('C:\\Users\\Dev\\Desktop\\file\\json.json','wb')
pickle.dump(json_format,Fichier)
</code></pre>
<p>That's writing the <code>json_format</code> <em>string</em> to the open file ob... | 2 | 2016-06-05T22:38:56Z | [
"python",
"json"
] |
Using py2exe to make a windows exe, but it seems to have an issue with my script, - pandas\io\excel.pyc object has no attribute version | 37,647,482 | <p>I am using <code>pandas</code> to create an excel file... my script works fine on pycharm and on the command line but as soon as I create an <code>exe</code> using <code>py2exe</code> and run that exe, it gives me this error:</p>
<pre><code>File "TESTEXE.py", line 44, in <module>
File "pandas\io\excel.pyc"... | 0 | 2016-06-05T22:39:11Z | 40,031,029 | <p>The problem appears to be openpyxl stores its version string in a text file called .constants.json
This does not get picked up by py2exe. This is in the main <strong>init</strong>.py file for openpyxl.</p>
<p>I did a quick hack to put the constants into the <strong>init</strong>.py file, but have not yet figured o... | 0 | 2016-10-13T21:08:22Z | [
"python",
"excel",
"pandas",
"py2exe",
"openpyxl"
] |
Using python, I need to average value based on two keys in two columns from a CSV file | 37,647,510 | <p>I have a csv file with 3 columns</p>
<pre><code>TMC, EPOCH, Time
11C12, 1, 24
11C12, 1, 34
11C12, 2, 56
11C12, 2, 78
11C13, 1, 56
11C13, 2, 45
11C13, 2, 64
11C13, 3, 32
11C13, 3, 28
</code></pre>
<p>Now I want to have average.py file which calculates average of time for each combination of TMC, EPOCH and write tha... | 0 | 2016-06-05T22:44:06Z | 37,647,577 | <p>Use a <code>defaultdict</code> to group the elements using the forst two columns as the key and appending the times then average and write to the new csv:</p>
<pre><code>import csv
from collections import defaultdict
with open("in.csv") as f, open("average.csv", "w") as out:
wr = csv.writer(out)
d = defaul... | 0 | 2016-06-05T22:53:43Z | [
"python",
"csv"
] |
Display a count of Booleans from database | 37,647,535 | <p>I'm using flask. Database is sqlite3.
In short. I can make lists and I can tick them off as "finished", I want to show the numbers of finished lists in the users profile.</p>
<p>At this time it shows the same as "all lists"..</p>
<p>This is my List model: </p>
<pre><code>class List(Model):
timestamp = DateTim... | 0 | 2016-06-05T22:47:52Z | 37,648,133 | <p>In your finished list function you select all lists corresponding to the user <strong>OR</strong> (|) finished . Both conditions should be true to select finished lists so you need <strong>and</strong> (&)</p>
| 1 | 2016-06-06T00:32:37Z | [
"python",
"python-3.x",
"flask",
"flask-wtforms"
] |
Performance of single segment operation vs multiple operations on segments | 37,647,564 | <p>Since currently there is no easy way to profile TensorFlow operations (<a href="http://stackoverflow.com/questions/34293714/tensorflow-can-i-measure-the-execution-time-of-individual-operations">Tensorflow: Can I measure the execution time of individual operations?</a>), can anyone help me understand the benefits of ... | 1 | 2016-06-05T22:51:49Z | 37,669,089 | <p>I've updated the SO question you link to with some information about CPU inference profiling tools we've recently released at:
<a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/benchmark" rel="nofollow">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/benchmark</a></... | 0 | 2016-06-07T01:19:31Z | [
"python",
"tensorflow"
] |
Python Maze Generation | 37,647,670 | <p>I am trying to make a python maze generator but I keep getting an IndexError: list index out of range. Any ideas? I'm kinda new to this stuff so I was using the code from <a href="http://rosettacode.org/wiki/Maze_generation#Python" rel="nofollow">rosetta code</a> on maze generation. I am not painting the maze right ... | -3 | 2016-06-05T23:07:31Z | 37,647,999 | <p>Your code has <em>some</em> resemblance to what rosetta code has. Here is my attempt. I haven't tested it.</p>
<pre><code>from random import shuffle, randrange
def make_maze(w = 16, h = 8):
vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
def walk(x, y):
vis[y][x] = 1
d = [(x - 1... | 0 | 2016-06-06T00:07:52Z | [
"python",
"maze"
] |
Set path to UWSGI correctly | 37,647,730 | <p>Im trying to setup my uwsgi and faced with a problem. When I set path to my project in my project folder, UWSGI saw my <code>wsgi.py</code> but doesn't saw any other apps, cause they are on one level up... But if I try to set path just to my project folder, UWSGI doesn't saw my <code>wsgi.py</code>... How can I set ... | 1 | 2016-06-05T23:18:59Z | 37,647,823 | <p>you need to change to <code>redish</code> and from there point to your settings.</p>
<pre><code>chdir=/root/reddish/reddish
env=DJANGO_SETTINGS_MODULE=myProject.settings
</code></pre>
| 1 | 2016-06-05T23:35:32Z | [
"python",
"django",
"uwsgi"
] |
Set path to UWSGI correctly | 37,647,730 | <p>Im trying to setup my uwsgi and faced with a problem. When I set path to my project in my project folder, UWSGI saw my <code>wsgi.py</code> but doesn't saw any other apps, cause they are on one level up... But if I try to set path just to my project folder, UWSGI doesn't saw my <code>wsgi.py</code>... How can I set ... | 1 | 2016-06-05T23:18:59Z | 37,647,835 | <p>If your manage.py is in reddish, create a directory 'settings' in the same directory your manage.py seats, create default settings file like this
./settings/settings.py</p>
<p>include: </p>
<pre><code>try:
from development_settings import *
except ImportError:
from default_settings import *
</code></pre... | 1 | 2016-06-05T23:37:19Z | [
"python",
"django",
"uwsgi"
] |
Set path to UWSGI correctly | 37,647,730 | <p>Im trying to setup my uwsgi and faced with a problem. When I set path to my project in my project folder, UWSGI saw my <code>wsgi.py</code> but doesn't saw any other apps, cause they are on one level up... But if I try to set path just to my project folder, UWSGI doesn't saw my <code>wsgi.py</code>... How can I set ... | 1 | 2016-06-05T23:18:59Z | 37,648,140 | <blockquote>
<p>Always avoid running your uWSGI instances as root. You can drop
privileges using the uid and gid options:</p>
</blockquote>
<p><a href="http://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#security-and-availability" rel="nofollow">http://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.... | 1 | 2016-06-06T00:34:03Z | [
"python",
"django",
"uwsgi"
] |
Moving a Ball in Random place with mouse click | 37,647,786 | <p>The following program I have provided below is one I developed to have a ball move around a screen randomly on its own free will. The next thing I have been trying to make it do is to have it move to a random location if you click the ball with a mouse. I've tried if statements but can not get any to work?? Any idea... | 0 | 2016-06-05T23:28:28Z | 37,651,146 | <p><strong>First you need to do is get a rect around your ball.</strong> </p>
<p>Ok, so basically what you need to do is , get the mouse coordinates and check if they collide with your ball image.<br>
You can use the following code in your loop to check if mouse coordinates collides with the ball(rect). </p>
<pre><c... | 0 | 2016-06-06T06:50:23Z | [
"python",
"button",
"pygame",
"mouse"
] |
OANDA execution order REST API | 37,647,795 | <p>I'm trying to create a code to automatic execute orders in OANDA API</p>
<p>This is the code of my order:</p>
<pre><code>class Execution(object):
def __init__(self, domain, access_token, account_id):
self.domain = domain
self.access_token = access_token
self.account_id = account_id
... | 0 | 2016-06-05T23:29:48Z | 37,648,402 | <p>Although code 52 is not specified in the troubleshooting errors, I'm pretty sure you got a 400 status code from your request:</p>
<blockquote>
<p>400 Bad Request Invalid or malformed argument: [arg] The argument
specified is not properly formatted or is an unaccepted value</p>
</blockquote>
<p>double chec... | 0 | 2016-06-06T01:22:38Z | [
"python",
"api",
"rest"
] |
Extract from directory inside zip file | 37,647,812 | <p>My existing code (a section) is loacted at the bottom of this post.</p>
<p>What I would like to do is extract all of the files from a directory <em>inside</em> of a zip file. Not the whole contents of a zip file, just the files in a directory (<code>/theme_files/</code>) that's inside of a zip. I have already impor... | 0 | 2016-06-05T23:33:37Z | 37,647,975 | <pre><code>for item in (f for f in theme_zip.filelist if 'theme_files/' in f.filename):
theme_zip.extract(item, output_dir)
</code></pre>
| 0 | 2016-06-06T00:03:03Z | [
"python",
"python-3.x",
"zip",
"zipfile"
] |
Extract from directory inside zip file | 37,647,812 | <p>My existing code (a section) is loacted at the bottom of this post.</p>
<p>What I would like to do is extract all of the files from a directory <em>inside</em> of a zip file. Not the whole contents of a zip file, just the files in a directory (<code>/theme_files/</code>) that's inside of a zip. I have already impor... | 0 | 2016-06-05T23:33:37Z | 37,648,806 | <p>Search the file names in the specific subfolders with regex. + Extract them file by file:</p>
<pre><code>with open('<file-name>.zip', 'rb') as f:
zf = zipfile.ZipFile(f)
for file in [m.group() for m in (re.search(r'/theme/(.+)', file) for file in file_list) if m]:
zf.extract(file)
</code></pre... | -1 | 2016-06-06T02:29:36Z | [
"python",
"python-3.x",
"zip",
"zipfile"
] |
Python - argmin / argmax for member function | 37,647,813 | <p>I would like to know if there is a "pythonic" way to use the mathematical argmin/argmax for a member function <strong>without</strong> using library like <strong>numpy</strong>.</p>
<p>I have a class with a member function inside which returns an integer.
I instantiate several objects of this class.
I'd like to kno... | 0 | 2016-06-05T23:33:49Z | 37,647,814 | <p>A good way to write this code in a more <em>pythonic</em> way is to use <strong>min</strong> function, which can actually be used like <strong>argmin</strong> function thanks to its parameter <strong>key</strong>.</p>
<p>If we replace the code between the tag <em>Code I'd like to improve</em> and <em>End of code I'... | 1 | 2016-06-05T23:33:49Z | [
"python",
"argmax"
] |
random.shuffle is acting strange in list of lists made with list multiplication | 37,647,863 | <p>My <code>createIndividual</code> function is trying to take a list of lists of lists called <code>courses</code>, and then add members of a global list variable (<code>PEOPLE</code>) to it randomly. The code is:</p>
<pre><code>def createIndividual(courses):
# Courses is equal to an individual, but
# without... | 4 | 2016-06-05T23:42:31Z | 37,647,889 | <p>You have to use <code>deepcopy</code> because your lists store another lists and you have to copy them too. Look for examples: <a href="http://www.python-course.eu/deep_copy.php" rel="nofollow">http://www.python-course.eu/deep_copy.php</a></p>
| 1 | 2016-06-05T23:47:01Z | [
"python",
"list",
"random"
] |
random.shuffle is acting strange in list of lists made with list multiplication | 37,647,863 | <p>My <code>createIndividual</code> function is trying to take a list of lists of lists called <code>courses</code>, and then add members of a global list variable (<code>PEOPLE</code>) to it randomly. The code is:</p>
<pre><code>def createIndividual(courses):
# Courses is equal to an individual, but
# without... | 4 | 2016-06-05T23:42:31Z | 37,666,211 | <p>This question really needs more detail to answer it with confidence, but since there's a common error that could produce this weird result (and since I wasn't able to reproduce it any other way)...</p>
<p>I think the problem is not in your <code>createIndividual</code> function, but in the data structure you're fee... | 4 | 2016-06-06T20:20:50Z | [
"python",
"list",
"random"
] |
How does pandas calculate skew | 37,647,961 | <p>I'm calculating a coskew matrix and wanted to double check my calculation with pandas built in <code>skew</code> method. I could not reconcile how pandas performing the calculation.</p>
<p>define my series as:</p>
<pre><code>import pandas as pd
series = pd.Series(
{0: -0.051917457635120283,
1: -0.070071... | 2 | 2016-06-06T00:00:10Z | 37,648,077 | <p>I found <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.stats.skew.html" rel="nofollow"><code>scipy.stats.skew</code></a> with parameter <code>bias=False</code> return equal output, so I think in <code>pandas skew</code> is <code>bias=False</code> by default:</p>
<blockquote>
<p>bias : b... | 2 | 2016-06-06T00:21:16Z | [
"python",
"pandas"
] |
deepcopy objects failed | 37,648,134 | <p>I am new to the community and appreciate any response from you. I learned Python recently and tried to write a function to deep-copy some objects. </p>
<pre><code>import copy
class node:
def __init__(self,x):
self.x=x
a=node(8)
d=node(10)
c=copy.deepcopy(d)
def copyNode(a):
c=copy.deepcopy(a)
copyN... | 0 | 2016-06-06T00:32:44Z | 37,648,187 | <p>The variable c in <code>c=copy.deepcopy(a)</code> is defined locally inside the copyNode function. You see that when you print c.x there:</p>
<pre><code>import copy
class node:
def __init__(self,x):
self.x=x
a=node(8)
d=node(10)
c=copy.deepcopy(d)
def copyNode(a):
c=copy.deepcopy(a)
print(c.x)
... | 0 | 2016-06-06T00:44:14Z | [
"python"
] |
Comparing two identical objects in Python (2.7) returns False | 37,648,137 | <p>I have a function in Python called <code>object_from_DB</code>. The definition isn't important except that it takes an ID value as an argument, uses the <code>sqlite3</code> library to pull matching values from a table in a .db file, and then uses those values as arguments in the initialization of an object. The dat... | 0 | 2016-06-06T00:33:11Z | 37,648,179 | <p>By default, two distinct instances of any user-defined class are unequal:</p>
<pre><code>>>> class X: pass
...
>>> a = X()
>>> b = X()
>>> a == b
False
</code></pre>
<p>If you want different behaviour, you have to define it:</p>
<pre><code>class Y:
def __init__(self, valu... | 3 | 2016-06-06T00:43:12Z | [
"python",
"python-2.7",
"sqlite3",
"compare"
] |
How do I associate python with py files in bash | 37,648,213 | <p>A common question is "how do I make <em>my</em> python script executable without explicitly calling python on the command line?", and the answer is <code>chmod +x</code> it and then add <code>#!/usr/bin/env python</code> at the start of the script.</p>
<p>That is <em>not</em> the question I'm asking.</p>
<p>What I... | 0 | 2016-06-06T00:48:10Z | 37,648,327 | <p>Do you mean <a href="https://en.wikipedia.org/wiki/Binfmt_misc" rel="nofollow">binfmt_misc</a>?</p>
<blockquote>
<p>binfmt_misc is a capability of the Linux kernel which allows arbitrary executable file formats to be recognized and passed to certain user space applications, such as emulators and virtual machines.... | 4 | 2016-06-06T01:08:39Z | [
"python",
"linux",
"bash"
] |
How do I associate python with py files in bash | 37,648,213 | <p>A common question is "how do I make <em>my</em> python script executable without explicitly calling python on the command line?", and the answer is <code>chmod +x</code> it and then add <code>#!/usr/bin/env python</code> at the start of the script.</p>
<p>That is <em>not</em> the question I'm asking.</p>
<p>What I... | 0 | 2016-06-06T00:48:10Z | 37,673,557 | <p>Rio6's answer is correct. Only it is supported on practically no operating systems. You will need binfmt, you can compile it yourself from source at <a href="http://git.savannah.gnu.org/cgit/binfmt-support.git" rel="nofollow">This git address</a></p>
| 1 | 2016-06-07T07:53:00Z | [
"python",
"linux",
"bash"
] |
commands through define | 37,648,221 | <p>I was making a program in python with pygame so that when you press a button on the screen, it does a command. I am doing this through a define but I can't seem to be able to use the command. Here is my code (btw I'm using python 2.7.11)</p>
<pre><code>from time import sleep
import pygame
from pygame.locals import ... | 0 | 2016-06-06T00:48:57Z | 37,648,769 | <p>When you put <code>msg()</code> in the argument list to <code>button</code>, you're not passing the function as an argument, but calling it immediately and passing its return value (<code>None</code> in this case) as the argument. Get rid of the parentheses and you'll be passing a reference to the function:</p>
<pr... | 0 | 2016-06-06T02:22:46Z | [
"python",
"function",
"pygame"
] |
Seaborn: Overlay line plot on top of bar chart | 37,648,266 | <p>Here is my dataframe -</p>
<pre><code> easy_donor length count freq
0 Donor 1 NS 0 15637 0.000188
1 Donor 1 NS 1 144539 0.001737
2 Donor 1 NS 2 129792 0.001560
3 Donor 1 NS 3 143610 0.001726
4 Donor 1 NS 4 189110 0.002273
5 Donor 1 NS 5 474718 0.005706
6 Donor 1 NS 6 ... | 0 | 2016-06-06T00:57:34Z | 37,648,647 | <p>You might find <a href="http://stackoverflow.com/questions/35303304/multiple-graphs-on-the-same-plot-in-seaborn">this previous question</a> useful which points to <a href="http://stanford.edu/~mwaskom/software/seaborn/tutorial/categorical.html" rel="nofollow">this seaborn tutorial.</a> </p>
<p>I think this snippet ... | 1 | 2016-06-06T02:04:04Z | [
"python",
"matplotlib",
"seaborn"
] |
Django Simple History Delete all History on Model Delete | 37,648,419 | <p>Using django simple history, is there a way to delete all the history associated with an object if the object itself is deleted? For example, if I have a User model:</p>
<pre><code>User.objects.filter(id=to_delete_id).delete()
</code></pre>
<p>That query will delete that User, but it doesn't erase all the history,... | 0 | 2016-06-06T01:24:27Z | 37,648,797 | <p>I think I found a solution, let me know if this is bad for some performance reason:</p>
<p>Override the delete() method on a User:</p>
<pre><code>class User(...):
...
def delete(self):
self.history.filter().delete()
super(User, self).delete()
</code></pre>
| 0 | 2016-06-06T02:28:05Z | [
"python",
"django",
"django-simple-history"
] |
XGBoost: what's wrong with xgb.cv call? | 37,648,443 | <p>I'm trying to use xgboost on Python.</p>
<p>Here is my code. <code>xgb.train</code> works but I get on error with <code>xgb.cv</code>
although it seems I used it the correct way.</p>
<p>The following works for me:</p>
<pre><code>###### XGBOOST ######
import datetime
startTime = datetime.datetime.now()
import xg... | 9 | 2016-06-06T01:28:33Z | 38,004,463 | <p>My understanding is that this error results from installing xgboost via pip, which is now out of date. XGBoost should instead be installed as follows:</p>
<pre><code>git clone --recursive https://github.com/dmlc/xgboost
cd xgboost; make -j4
cd python-package; sudo python setup.py install
</code></pre>
| 0 | 2016-06-24T01:47:06Z | [
"python",
"xgboost"
] |
XGBoost: what's wrong with xgb.cv call? | 37,648,443 | <p>I'm trying to use xgboost on Python.</p>
<p>Here is my code. <code>xgb.train</code> works but I get on error with <code>xgb.cv</code>
although it seems I used it the correct way.</p>
<p>The following works for me:</p>
<pre><code>###### XGBOOST ######
import datetime
startTime = datetime.datetime.now()
import xg... | 9 | 2016-06-06T01:28:33Z | 38,043,626 | <p>You can't use <code>evallist</code> in <code>cv</code>.
So you should remove <code>evallist</code> from the arguments of the <code>xgb.cv</code> call.
Put another way, you should try:</p>
<p><code>bst.res = xgb.cv(plst, dtrain, num_round, nfold=5, early_stopping_rounds=5)</code></p>
<p>instead of</p>
<p><code>bst... | 1 | 2016-06-26T22:02:48Z | [
"python",
"xgboost"
] |
Time comparison in python | 37,648,494 | <p>In a Django website I maintain, I need to check whether users logged in (and performed a certain task) during particular time windows every day. These time windows are fixed and recur daily. For instance, window # 1 is between <strong>3AM</strong> and <strong>6:30AM</strong> (inclusive), whereas window # 2 is <stron... | 0 | 2016-06-06T01:39:03Z | 37,648,933 | <p>A few comments.</p>
<ol>
<li><p>Yes, this is the correct way to compare datetime objects. The <a href="https://docs.python.org/2/library/datetime.html#datetime-objects" rel="nofollow">datetime docs</a> show that datetime objects support arithmetic, multiplicative, and comparative operations.</p></li>
<li><p>I doubt... | 1 | 2016-06-06T02:54:19Z | [
"python",
"django",
"datetime"
] |
Time comparison in python | 37,648,494 | <p>In a Django website I maintain, I need to check whether users logged in (and performed a certain task) during particular time windows every day. These time windows are fixed and recur daily. For instance, window # 1 is between <strong>3AM</strong> and <strong>6:30AM</strong> (inclusive), whereas window # 2 is <stron... | 0 | 2016-06-06T01:39:03Z | 37,649,559 | <p>I don't think you need to replace the <code>hour</code> and <code>minute</code> in current time. Because one you have obtained <code>time()</code> from <code>time_now</code>, you can just compare it with another <a href="https://docs.python.org/2/library/datetime.html#time-objects" rel="nofollow"><code>time</code></... | 1 | 2016-06-06T04:29:52Z | [
"python",
"django",
"datetime"
] |
How To Create Custom DataFrame From Subset Of CSV File | 37,648,544 | <p>I have a CSV file that looks like this:</p>
<pre><code> 1, 2, 3, 4, 5 ...
0, 1, 0, 1, 0 ...
0, 1, 0, 1, 0 ...
str1, str2, str3, str4, str5 ...
val1, val1.1, val1.2, val1.3, val1.4 ...
val2, val2.1, val2.2, val2.3, val2.4 ...
...
</code></pre>
<p>and I want to generate a dataframe that looks ... | 1 | 2016-06-06T01:47:29Z | 37,648,672 | <p>You can simply delete any undesired columns. Check out this discussion on deleting a Pandas DataFrame column: <a href="http://stackoverflow.com/questions/13411544/delete-column-from-pandas-dataframe">Delete column from pandas DataFrame</a></p>
<p>Then cruise on over to the documentation: <a href="http://pandas.pyda... | 1 | 2016-06-06T02:07:39Z | [
"python",
"pandas",
"dataframe"
] |
How To Create Custom DataFrame From Subset Of CSV File | 37,648,544 | <p>I have a CSV file that looks like this:</p>
<pre><code> 1, 2, 3, 4, 5 ...
0, 1, 0, 1, 0 ...
0, 1, 0, 1, 0 ...
str1, str2, str3, str4, str5 ...
val1, val1.1, val1.2, val1.3, val1.4 ...
val2, val2.1, val2.2, val2.3, val2.4 ...
...
</code></pre>
<p>and I want to generate a dataframe that looks ... | 1 | 2016-06-06T01:47:29Z | 37,652,220 | <p>IMO this can be done much more efficiently.</p>
<p>Parse (read) only the data that you really need - this will be much faster and will reduce the memory consumption dramatically. Beside that using <code>pd.concat()</code> once instead of adding each new DF using <code>df.append()</code> should be much faster.</p>
... | 2 | 2016-06-06T07:55:58Z | [
"python",
"pandas",
"dataframe"
] |
_curses.error: add_wch() returned an error | 37,648,557 | <p>I have the following code rendering the display for my roguelike game. It includes rendering the map.</p>
<pre><code> def render_all(self):
for y in range(self.height):
for x in range(self.width):
wall = self.map.lookup(x,y).blocked
if wall:
self.main.addch(y, x, "#")
el... | 0 | 2016-06-06T01:48:52Z | 37,653,222 | <p>That's expected behavior. Python uses ncurses, which does this because other implementations do this.</p>
<p>In the <a href="http://invisible-island.net/ncurses/man/curs_addch.3x.html" rel="nofollow">manual page</a> for <code>addch</code>:</p>
<blockquote>
<p>The <strong><code>addch</code></strong>, <strong><... | 1 | 2016-06-06T08:54:16Z | [
"python",
"curses",
"roguelike"
] |
Efficient sorting and aggregating data in Python? | 37,648,577 | <pre><code>srch_destination hotel_booked count
28 1 4
28 5 1
28 8 2
28 11 9
28 14 17
19 11 3
19 ... | 2 | 2016-06-06T01:52:25Z | 37,648,624 | <p>Use <code>nlargest</code> to get the top 3 based on the <code>count</code> column.</p>
<pre><code>>>> (df.groupby('srch_destination')
.apply(lambda group: group.nlargest(3, 'count').hotel_booked.tolist()))
srch_destination
19 [6, 5, 2]
28 [14, 11, 1]
dtype: object
</code></pre>
| 3 | 2016-06-06T02:01:03Z | [
"python",
"sorting",
"python-3.x",
"aggregate"
] |
Python 2.7.9 on Centos 6.7? | 37,648,665 | <p>I need to upgrade Python on my centos 6.7 machine to 2.7.9, but everything I've been reading has said that will break "yum" on my system. Does this issue still exist? I'm only finding much older posts confirming, and I don't really know what I'm doing so I don't want to break anything.</p>
| 0 | 2016-06-06T02:06:43Z | 37,648,869 | <p>I have had some trouble using Python on CentOS due to yum requring Python2.6. But you should be able to upgrade and run yum. <code>yum</code> is python script and if it doesn't work maybe you can run it with the right Python version. For example </p>
<pre><code>python2.7 /usr/bin/yum .....
</code></pre>
| 0 | 2016-06-06T02:41:36Z | [
"python",
"linux",
"centos"
] |
Python 2.7.9 on Centos 6.7? | 37,648,665 | <p>I need to upgrade Python on my centos 6.7 machine to 2.7.9, but everything I've been reading has said that will break "yum" on my system. Does this issue still exist? I'm only finding much older posts confirming, and I don't really know what I'm doing so I don't want to break anything.</p>
| 0 | 2016-06-06T02:06:43Z | 37,832,207 | <p>You can install additional version of Python:</p>
<pre><code>wget https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tar.xz
tar xf Python-2.7.9.tar.xz
cd Python-2.7.9
./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make
make altinstall
</code></pre>
<p>Finally check the Python... | 0 | 2016-06-15T10:02:24Z | [
"python",
"linux",
"centos"
] |
Python how to initiate and close a MySQL connection inside a class | 37,648,667 | <p>I am trying to create a class that holds all my database operations. I would like to initiate a MySQL connection whenever this class is called, perform whatever db operations it needs to do and close it after it's done.</p>
<p>This is what I have so far:</p>
<pre><code>import MySQLdb
class Database_Test(object):
... | 1 | 2016-06-06T02:06:49Z | 37,648,680 | <p>What you see printed is the <code>test</code> object <em>string representation</em>, but instead you meant to get and use the result of <code>get_row()</code> method call:</p>
<pre><code>test = Database_Test(db_config)
resultset = test.get_row(sql)
print(resultset)
</code></pre>
| 2 | 2016-06-06T02:09:09Z | [
"python",
"mysql",
"class"
] |
Python how to initiate and close a MySQL connection inside a class | 37,648,667 | <p>I am trying to create a class that holds all my database operations. I would like to initiate a MySQL connection whenever this class is called, perform whatever db operations it needs to do and close it after it's done.</p>
<p>This is what I have so far:</p>
<pre><code>import MySQLdb
class Database_Test(object):
... | 1 | 2016-06-06T02:06:49Z | 37,648,751 | <p>@Alecxe answer was about your statement execution, in case of you question about opening and closing a connection, you can use <a href="https://docs.python.org/2/reference/datamodel.html#context-managers" rel="nofollow">Context Managers</a> magic methods:</p>
<pre><code>import MySQLdb
class Database_Test(object):
... | 0 | 2016-06-06T02:20:34Z | [
"python",
"mysql",
"class"
] |
getting Monday , june 5 , 2016 instead of June 5 ,2016 using DateTimeField | 37,648,868 | <p>I have an app using Django an my my model has the following field: </p>
<pre><code>date = models.DateTimeField(auto_now_add=True,auto_now=False)
</code></pre>
<p>Using that I get this: June 5, 2016, 9:16 p.m.</p>
<p>but I need something like : Monday, June 5, 2016</p>
<p>How I can get that??</p>
<p>Any help w... | 0 | 2016-06-06T02:41:34Z | 37,651,466 | <p>It depends on the context. In a template you can use the <a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#date" rel="nofollow">date template tags</a>:</p>
<pre><code><span>{{ my_date|date:"l, F j, Y" }}
</code></pre>
<p>or in Python context <a href="https://docs.python.org/2/library/dat... | 1 | 2016-06-06T07:11:16Z | [
"python",
"django",
"django-models"
] |
Subproces.popen - slave write failed: Broken pipe; aborting | 37,648,896 | <p>TLDR: stuck with this <a href="https://code.google.com/archive/p/byte-unixbench/issues/1" rel="nofollow">https://code.google.com/archive/p/byte-unixbench/issues/1</a></p>
<p>Trying to run UnixBench using <code>subprocess.popen()</code> while capturing output and printing it out in realtime.</p>
<p>This is the subr... | 1 | 2016-06-06T02:46:44Z | 37,682,483 | <p>The bug is related to <a href="http://stackoverflow.com/q/22077881/4279">'yes' reporting error with subprocess communicate()</a> which provides the fix: reenable <code>SIGPIPE</code> signal in the child process using <code>preexec_fn</code> (or use Python 3).</p>
<hr>
<p>Unrelated: your code can deadlock if <code>... | 2 | 2016-06-07T14:44:19Z | [
"python",
"subprocess"
] |
Python 3.5 setup.py egg_info failed with error code 1 [Linux] | 37,648,930 | <p>Me and a friend are trying to setup a discord bot through DigitalOcean. However, when we run the command "<code>sudo -H pip3.5 install --upgrade -r requirements.txt</code>" or something along those lines it always ends up with the same error.
We have tried installing python, it's already up to date.</p>
<p>Here are... | 0 | 2016-06-06T02:53:33Z | 37,651,763 | <p>Pip tried to download PyNaCL which needs to compile a python extension module from source. For that you need to have the right development libraries installed and ofc a working compiler setup. Hence the message <code>no_working_compiler_found</code>. You can try to find a complete binary wheel for PyNaCL, install th... | 0 | 2016-06-06T07:28:02Z | [
"python",
"linux",
"pip",
"bots"
] |
Python 3.5 setup.py egg_info failed with error code 1 [Linux] | 37,648,930 | <p>Me and a friend are trying to setup a discord bot through DigitalOcean. However, when we run the command "<code>sudo -H pip3.5 install --upgrade -r requirements.txt</code>" or something along those lines it always ends up with the same error.
We have tried installing python, it's already up to date.</p>
<p>Here are... | 0 | 2016-06-06T02:53:33Z | 37,668,029 | <p>Well, I fixed the problem by asking the "Discord API."</p>
<p>Heres how I fixed it:</p>
<blockquote>
<p>sudo apt install build-essential</p>
</blockquote>
<p>and then</p>
<blockquote>
<p>sudo apt install build-essential libffi-dev python3.5-dev</p>
</blockquote>
<p>and then I ran my command</p>
| 0 | 2016-06-06T22:53:43Z | [
"python",
"linux",
"pip",
"bots"
] |
Python: BeautifulSoup Web Parser, How do I scrape text without returning the html tags and à | 37,649,036 | <p>So My code is returning html tags along with the symbol "Ã" How can I delete all the html tags and the symbol 'Ã'. I know for the symbol, I have to do something regarding the unicode.</p>
<pre><code>import csv
import requests
from bs4 import BeautifulSoup
from itertools import izip
grant_number = ['0901289','09... | 0 | 2016-06-06T03:09:02Z | 37,649,633 | <p>If you do this:</p>
<p><code>soup = BeautifulSoup(r.content, "html.parser")
print soup.get_text()
</code></p>
<p>You should get something like this:</p>
<pre><code>NSF Award Search: Award#0901289 - Rational points on elliptic curves over totally real fields and p-adic L-functions
var printFlag = false;
... | -1 | 2016-06-06T04:39:53Z | [
"python",
"beautifulsoup",
"html-parsing",
"bots"
] |
Python: BeautifulSoup Web Parser, How do I scrape text without returning the html tags and à | 37,649,036 | <p>So My code is returning html tags along with the symbol "Ã" How can I delete all the html tags and the symbol 'Ã'. I know for the symbol, I have to do something regarding the unicode.</p>
<pre><code>import csv
import requests
from bs4 import BeautifulSoup
from itertools import izip
grant_number = ['0901289','09... | 0 | 2016-06-06T03:09:02Z | 37,672,507 | <p>try importing:</p>
<pre><code>import sys
import requests
from BeautifulSoup import BeautifulSoup
reload(sys)
sys.setdefaultencoding("utf-8")
</code></pre>
| -1 | 2016-06-07T06:59:30Z | [
"python",
"beautifulsoup",
"html-parsing",
"bots"
] |
Python: BeautifulSoup Web Parser, How do I scrape text without returning the html tags and à | 37,649,036 | <p>So My code is returning html tags along with the symbol "Ã" How can I delete all the html tags and the symbol 'Ã'. I know for the symbol, I have to do something regarding the unicode.</p>
<pre><code>import csv
import requests
from bs4 import BeautifulSoup
from itertools import izip
grant_number = ['0901289','09... | 0 | 2016-06-06T03:09:02Z | 37,704,198 | <p>If you want to get only the text (is not understandable for me why you want this) ... you should do this:</p>
<pre><code>soup = BeautifulSoup(r.content, "html.parser")
soup_string = soup.text
</code></pre>
<p>If you want to strip the whitespaces do this:</p>
<pre><code>soup = BeautifulSoup(r.content, "html.parser... | 0 | 2016-06-08T13:40:31Z | [
"python",
"beautifulsoup",
"html-parsing",
"bots"
] |
Tensorflow: restoring a graph and model then running evaluation on a single image | 37,649,060 | <p>I think it would be immensely helpful to the Tensorflow community if there was a well-documented solution to the crucial task of testing a single new image against the model created by the <a href="https://www.tensorflow.org/versions/r0.8/tutorials/deep_cnn/index.html" rel="nofollow">convnet in the CIFAR-10 tutorial... | 2 | 2016-06-06T03:14:23Z | 37,669,221 | <p>I don't have working code for you I'm afraid, but here's how we often tackle this problem in production:</p>
<ul>
<li><p>Save out the GraphDef to disk, using something like <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/training_util.py#L53" rel="nofollow">write_graph</a>.<... | 0 | 2016-06-07T01:38:11Z | [
"python",
"python-3.x",
"machine-learning",
"tensorflow"
] |
Tensorflow: restoring a graph and model then running evaluation on a single image | 37,649,060 | <p>I think it would be immensely helpful to the Tensorflow community if there was a well-documented solution to the crucial task of testing a single new image against the model created by the <a href="https://www.tensorflow.org/versions/r0.8/tutorials/deep_cnn/index.html" rel="nofollow">convnet in the CIFAR-10 tutorial... | 2 | 2016-06-06T03:14:23Z | 37,738,000 | <p>Here's how I ran a single image at a time. I'll admit it seems a bit hacky with the reuse of getting the scope. </p>
<p>This is a helper function</p>
<pre><code>def restore_vars(saver, sess, chkpt_dir):
""" Restore saved net, global score and step, and epsilons OR
create checkpoint directory for later storage. "... | 1 | 2016-06-09T23:57:28Z | [
"python",
"python-3.x",
"machine-learning",
"tensorflow"
] |
How to filter on calculated model values using list comprehension | 37,649,078 | <p>I have a model where I calculate totals </p>
<pre><code>class Material(models.Model):
version = IntegerVersionField( )
code = models.CharField(max_length=30)
name = models.CharField(max_length=30)
slug = models.SlugField(max_length=80, blank=True)
description = models.TextField(null=True, blank=... | 0 | 2016-06-06T03:18:17Z | 37,811,289 | <p>I doubt you can call <code>F</code> on model class methods. You can instead call the methods directly from the objects in the list comprehension:</p>
<pre><code>po_list = [n for n in Material.objects.all() if (n.total_inventory['quantity__sum']
+ n.total_po['quantit... | 1 | 2016-06-14T11:54:25Z | [
"python",
"django"
] |
Django Bulk Model Deletion with Indices | 37,649,095 | <p>I recently deleted over 2 million rows from my db using this (I wanted to clean out any User history where the user doesn't exist any more). I'm using Django simple history.</p>
<pre><code>active_ids = User.objects.values_list("id", flat=True)
User.history.filter(~Q(id__in=active_ids)).delete()
</code></pre>
<p>Th... | 1 | 2016-06-06T03:21:30Z | 37,649,251 | <p>I would recommend on changing your database management. You can change to PostgreSQL since it is built for larger data storage. Or you can try big data. Just in case your data really gets very very large. Deleting data is not really recommended as you can use it later for analytics.</p>
<p>You can try django and ca... | 1 | 2016-06-06T03:45:10Z | [
"python",
"mysql",
"django",
"django-simple-history"
] |
Django Bulk Model Deletion with Indices | 37,649,095 | <p>I recently deleted over 2 million rows from my db using this (I wanted to clean out any User history where the user doesn't exist any more). I'm using Django simple history.</p>
<pre><code>active_ids = User.objects.values_list("id", flat=True)
User.history.filter(~Q(id__in=active_ids)).delete()
</code></pre>
<p>Th... | 1 | 2016-06-06T03:21:30Z | 37,650,095 | <p>These are mysql issues rather than django issues.</p>
<h2>Slow Delete.</h2>
<p>In any RDBMS, be it mysql or postgresql or anything else, bulk insert, delete and update will always be slow if you have indexes. That's the nature of the beast.</p>
<p>The best way to speed it up is to examine your indexes and drop an... | 1 | 2016-06-06T05:28:28Z | [
"python",
"mysql",
"django",
"django-simple-history"
] |
delete element from list | 37,649,143 | <p>i can't delete an element from a list, the list is loaded from a json file. </p>
<pre><code>elif choice == 'd':
# Delete a joke.
# See Point 7 of the "Requirements of admin.py" section of the assignment brief.
jokeIndex = input('Joke number to delete: ')
index = int(jokeIndex)
file = open('data.... | 0 | 2016-06-06T03:29:32Z | 37,649,187 | <p>You are deleting the list element only, you aren't deleting the element/line from the file.</p>
<p>What you may do is delete the element from the list and overwrite the file.</p>
| 0 | 2016-06-06T03:34:40Z | [
"python",
"json",
"list"
] |
delete element from list | 37,649,143 | <p>i can't delete an element from a list, the list is loaded from a json file. </p>
<pre><code>elif choice == 'd':
# Delete a joke.
# See Point 7 of the "Requirements of admin.py" section of the assignment brief.
jokeIndex = input('Joke number to delete: ')
index = int(jokeIndex)
file = open('data.... | 0 | 2016-06-06T03:29:32Z | 37,649,222 | <p>What you want to do is write back to the json file. I would use <code>json.dump(data, file, indent=4)</code>. See below.</p>
<pre><code># Delete a joke.
# See Point 7 of the "Requirements of admin.py" section of the assignment brief.
jokeIndex = input('Joke number to delete: ')
index = int(jokeIndex)
file = open('j... | 0 | 2016-06-06T03:39:44Z | [
"python",
"json",
"list"
] |
ImportError: DLL load failed: The specified module could not be found when loading __init__.py | 37,649,182 | <p>Unable to import pygame into my program</p>
<p><code>import pygame</code></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files (x86)\Python35-32\lib\site-packages\pygame\__init__.py", line 95, in <module>
from pygame.base import *
Im... | 0 | 2016-06-06T03:33:48Z | 37,651,251 | <p>I suspect you've mixed a x64 python with x86 pygame file, or vice versa.
Try to uninstall both your python version and pygame and try downloading it again. </p>
<p>Download python from <a href="https://www.python.org/downloads/" rel="nofollow">Here.</a><br>
Download pygame from <a href="http://www.pygame.org/down... | 0 | 2016-06-06T06:57:04Z | [
"python",
"python-3.x",
"pygame",
"python-import"
] |
Extracting repeated patterns from a text file in python | 37,649,230 | <p>I am looking to extract all the text between a repeating pattern in a text file. My text file XYZ.txt looks something like this:</p>
<pre><code>Start
This is a great day
End
Start
This is another great day
End
Start
This is 3rd great day
End
</code></pre>
<p>I am looking extract the all the text between every... | 0 | 2016-06-06T03:41:19Z | 37,649,309 | <p>You need to use <code>re.findall</code> to find all occurrences of regex.</p>
<pre><code>>>> lines
'Start\n\nThis is a great day\n\nEnd\n\nStart\nThis is another great day\n\nEnd\n\nStart\nThis is 3rd great day\nEnd\n'
>>>
>>> re.findall('This is.*day', lines)
['This is a great day', 'Thi... | 0 | 2016-06-06T03:53:35Z | [
"python",
"html"
] |
Extracting repeated patterns from a text file in python | 37,649,230 | <p>I am looking to extract all the text between a repeating pattern in a text file. My text file XYZ.txt looks something like this:</p>
<pre><code>Start
This is a great day
End
Start
This is another great day
End
Start
This is 3rd great day
End
</code></pre>
<p>I am looking extract the all the text between every... | 0 | 2016-06-06T03:41:19Z | 37,649,318 | <p>You could use string mutation and generators instead of re.</p>
<pre><code>def format_file(file, start, end):
f = open(file, 'r').read()
return tuple(x for x in ''.join(f.split(start)).replace('\n', '').split(end) if x != '')
print format_file('XYZ', 'Start', 'End')
</code></pre>
<p>Or pure generator</p>
... | 0 | 2016-06-06T03:54:32Z | [
"python",
"html"
] |
Extracting repeated patterns from a text file in python | 37,649,230 | <p>I am looking to extract all the text between a repeating pattern in a text file. My text file XYZ.txt looks something like this:</p>
<pre><code>Start
This is a great day
End
Start
This is another great day
End
Start
This is 3rd great day
End
</code></pre>
<p>I am looking extract the all the text between every... | 0 | 2016-06-06T03:41:19Z | 37,649,325 | <p>I would use the <code>readlines()</code> function and do something like this:</p>
<pre><code>with open('jokes.txt') as myfile:
for line in myfile.readlines():
if line.strip() != 'Start' and line.strip() != 'End' and line.strip():
print line[:-1]
</code></pre>
<p>This will give output:</p>
... | 0 | 2016-06-06T03:55:57Z | [
"python",
"html"
] |
Extracting repeated patterns from a text file in python | 37,649,230 | <p>I am looking to extract all the text between a repeating pattern in a text file. My text file XYZ.txt looks something like this:</p>
<pre><code>Start
This is a great day
End
Start
This is another great day
End
Start
This is 3rd great day
End
</code></pre>
<p>I am looking extract the all the text between every... | 0 | 2016-06-06T03:41:19Z | 37,649,576 | <p>If your text file looks like in your post, then you may not need <code>regex</code>, you can use <a href="https://docs.python.org/3.1/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>.</p>
<p>You can just store all the lines you want to extract in a list.</p>
<pre><code>lst = ... | 0 | 2016-06-06T04:32:59Z | [
"python",
"html"
] |
Django - Avoid writing duplicate code | 37,649,271 | <p>I want to create 2 web pages which use the same code but I don't want to copy/paste the code in 2 places. I'm sure I don't need to have the same code in 2 different places to use it on multiple pages. Can someone suggest a way to avoid creating duplicate code?</p>
<p>If required, I can provide some sample code whic... | 1 | 2016-06-06T03:47:45Z | 37,649,372 | <p>Use this built-in django template tag for that: </p>
<pre><code>{% include "subtemplate.html" %}
</code></pre>
| 0 | 2016-06-06T04:02:08Z | [
"python",
"django"
] |
Django - Avoid writing duplicate code | 37,649,271 | <p>I want to create 2 web pages which use the same code but I don't want to copy/paste the code in 2 places. I'm sure I don't need to have the same code in 2 different places to use it on multiple pages. Can someone suggest a way to avoid creating duplicate code?</p>
<p>If required, I can provide some sample code whic... | 1 | 2016-06-06T03:47:45Z | 37,649,412 | <p>For generating HTML on the frontend, you can use templates to create static content which can be used across multiple pages on your site. </p>
<p>For more information on how to use django templates, see: <a href="https://docs.djangoproject.com/en/1.9/topics/templates/" rel="nofollow">https://docs.djangoproject.com/... | 3 | 2016-06-06T04:07:04Z | [
"python",
"django"
] |
specifying libcpp.string type for __contains__ in cython | 37,649,286 | <p>I'm implementing a cython wrapper for some C++ data structure which will have c++ strings as both keys and values.</p>
<p>I have the C++ methods prototyped in a pxd, for a class with templated key/value types (sorry, I've never worked with C++, only C, so I'm not sure of the right terminology, let me know if this i... | 4 | 2016-06-06T03:49:57Z | 37,666,693 | <p>Ok, I managed to get your code working.
I'm not sure I know where your problem comes from, though: the only time I got an error about an integer being required was when I implemented the <code>__setitem__</code> method...</p>
<p>However, I think modifying the function like this should do the trick:</p>
<pre><code>... | 2 | 2016-06-06T20:50:52Z | [
"python",
"c++",
"cython"
] |
Trying to create a regexp | 37,649,319 | <p>I have a string which I want a string to parse via Java or Python regexp:</p>
<pre><code>something (\var1 \var2 \var3 $var4 #var5 $var6 *fdsfdsfd @uytuytuyt fdsgfdgfdgf aaabbccc)
</code></pre>
<p>The number of <code>var</code> is unknown. Their exact names are unknown. Their names may or may not start with "\" or ... | 1 | 2016-06-06T03:54:53Z | 37,649,369 | <p><code>something\s\((.+)\)</code> </p>
<p>In this regex you are capturing the string containing all the variables. split it based on whitespace since you are sure that they are delimited by whitespace.</p>
<pre><code>m = re.search('something\s\((.+)\)', input_string)
if m:
list_of_vars = m.group(1).split()
</co... | 1 | 2016-06-06T04:01:29Z | [
"java",
"python",
"regex"
] |
Matplotlib: How to make a histogram with bins of equal area? | 37,649,342 | <p>Given some list of numbers following some arbitrary distribution, how can I define bin positions for <code>matplotlib.pyplot.hist()</code> so that the area in each bin is equal to (or close to) some constant area, A? The area should be calculated by multiplying the number of items in the bin by the width of the bin ... | 3 | 2016-06-06T03:58:32Z | 37,667,480 | <p>I found this question intriguing. The solution depends on whether you want to plot a <strong>density function</strong>, or a <strong>true histogram</strong>. The latter case turns out to be quite a bit more challenging. <a href="http://stats.stackexchange.com/questions/2573/difference-between-histogram-and-pdf">Here... | 4 | 2016-06-06T21:57:19Z | [
"python",
"matplotlib",
"histogram",
"binning"
] |
Python pip install qibuild exception then I installed pip yet. | 37,649,397 | <p>I'm new on this forum and I will ask you to be friendly with my first publication. Thank you!!</p>
<p>So, here is my problem. I installed pip and now I try to install qibuild with it. But I've got a problem.
This is the command that I run:</p>
<pre><code>pip install qibuild
</code></pre>
<p>And this the error tha... | 0 | 2016-06-06T04:05:53Z | 39,495,954 | <p>Can you check the time on your system. Sometimes it so happens when your system time is inaccurate the pip installation fails. I have faced this issue once.</p>
<p>Change your system date to current date in accordance with your time zone ,
Hope this helps</p>
| 0 | 2016-09-14T16:59:02Z | [
"python",
"python-2.7",
"pip",
"robotics",
"debian-based"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.