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 |
|---|---|---|---|---|---|---|---|---|---|
Python Adding Methods at runtime | 37,783,506 | <p>I'm trying to dynamically add methods to classes at runtime, and am seeing some issues:</p>
<pre><code>#Here we define a set of symbols within an exec statement and put them into the dictionary d
d = {}
exec "def get_%s(self): return self.%s" % (attr_name, attr) in d
#Now, we bind the get method stored in d['get_%... | -1 | 2016-06-13T06:57:45Z | 37,784,598 | <pre><code>exec("%s.__dict__['get_%s'] = lambda self: self.%s" % (class_name, attr_name, attr_name))
</code></pre>
| 0 | 2016-06-13T08:06:21Z | [
"python",
"class",
"methods",
"class-method"
] |
Python Adding Methods at runtime | 37,783,506 | <p>I'm trying to dynamically add methods to classes at runtime, and am seeing some issues:</p>
<pre><code>#Here we define a set of symbols within an exec statement and put them into the dictionary d
d = {}
exec "def get_%s(self): return self.%s" % (attr_name, attr) in d
#Now, we bind the get method stored in d['get_%... | -1 | 2016-06-13T06:57:45Z | 37,785,011 | <p>You can easily dynamically add static methods or class methods:</p>
<pre><code>class A:
pass
@staticmethod
def foo0(x):
return x * 2
a = A()
A.foo = foo0
a.foo(3)
</code></pre>
<p>return <code>6</code></p>
<pre><code>class A:
val = 3
@classmethod
def foo0(cls, x):
return x * cls.val
a = A()
A.... | 3 | 2016-06-13T08:29:40Z | [
"python",
"class",
"methods",
"class-method"
] |
Python: How to read data from webpage and then write back from database? | 37,783,635 | <p>I am a beginner.
I want to read two inputs (probably from a slide down menu) from a web page and use them as variables to execute python program, then return the result to a database and also display it on the webpage. I`m using mySQL for database management.</p>
| -1 | 2016-06-13T07:05:13Z | 37,812,003 | <p>If you want to scrape through any other website and get details from their site.
There are two cases </p>
<hr>
<ol>
<li>Data does not change on the webpage once web page gets loaded in this case what you see in the view page source in the browser is as what you see in the web page then you can send a get request t... | 0 | 2016-06-14T12:27:00Z | [
"python",
"database",
"webpage",
"interactive"
] |
Python: How to read data from webpage and then write back from database? | 37,783,635 | <p>I am a beginner.
I want to read two inputs (probably from a slide down menu) from a web page and use them as variables to execute python program, then return the result to a database and also display it on the webpage. I`m using mySQL for database management.</p>
| -1 | 2016-06-13T07:05:13Z | 37,813,856 | <p>so, for take the value from the element you have to do it:</p>
<pre><code>from selenium import webdriver
from selenium import selenium
browser = webdriver.Firefox()
browser.get("yourwebpage")
item=browser.find_element_by_xpath("xpath of your element")
value=item.text
</code></pre>
<p>instead than text you can use ... | 0 | 2016-06-14T13:44:21Z | [
"python",
"database",
"webpage",
"interactive"
] |
How to create/save files within a loop in a function? | 37,783,641 | <p>How can I save/create a file within a loop in a function? In the following example I want to run a function which prints a message and saves a file with the message in every iteration. However, it prints the messages but only saves the very last file (10). I guess it doesnât look so advisable. The point is that my... | 0 | 2016-06-13T07:05:45Z | 37,783,707 | <p>You set <code>cap = no</code> every iteration, then use <code>cap</code> as file name, so you are overwriting the same file every time.</p>
<p>Delete <code>cap = no</code> and change <code>np.save(fname_template.format(cap=cap) , message )</code> to <code>np.save(fname_template.format(cap=i) , message )</code></p>
| 0 | 2016-06-13T07:09:45Z | [
"python",
"function",
"loops",
"output"
] |
How to create/save files within a loop in a function? | 37,783,641 | <p>How can I save/create a file within a loop in a function? In the following example I want to run a function which prints a message and saves a file with the message in every iteration. However, it prints the messages but only saves the very last file (10). I guess it doesnât look so advisable. The point is that my... | 0 | 2016-06-13T07:05:45Z | 37,783,771 | <p>You mistake <code>cap=no</code> where <code>no == 10</code> just change it to <code>cap=i</code> or use <code>i</code>:</p>
<pre><code>def worldloop(message='hello world',no=10):
import numpy as np
fname_template='/home/blubb/Desktop/blaa{cap}'
for i in range(no):
np.save(fname_template.... | 0 | 2016-06-13T07:15:16Z | [
"python",
"function",
"loops",
"output"
] |
How to search and replace tag and attribute value in xml using python | 37,783,655 | <p>I want to search <code>tag/child</code> value in XML file and replace/update value with new value and save changes to same XML file. </p>
| 0 | 2016-06-13T07:06:39Z | 37,784,135 | <p>Checkout the <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#example" rel="nofollow">ElementTree XML API</a> from Python standard library.</p>
| 0 | 2016-06-13T07:37:46Z | [
"python",
"xml-parsing"
] |
I cannot install Flask-Spyne, during instalation TypeError appear | 37,783,672 | <p>I am trying to install python module Flask-Spyne on Windows and when I type <code>pip install Flask-Spyne</code>, on Sec-Wall collecting TypeError appear.</p>
<p>I am using Python 3.5.1 on Windows 10</p>
<p>This is it:</p>
<pre><code>C:\Windows\system32>pip install flask-spyne
Collecting flask-spyne
Using cach... | 0 | 2016-06-13T07:07:35Z | 37,784,924 | <p>According to Spyne's <a href="http://spyne.io/docs/2.10/#requirements" rel="nofollow">documentation</a>, it's known to work with Python versions 2.6. and 2.7, but Python 3 support is not tested.</p>
<p>Also, the error you've got <code>TypeError: a bytes-like object is required, not 'str'</code> is what people often... | 0 | 2016-06-13T08:25:20Z | [
"python",
"windows",
"flask",
"suds",
"spyne"
] |
Python collections ValuesView abc: why doesn't it inherit from Iterable? | 37,783,754 | <p>I was just checking out some docs on ABCs for a project of mine, where I need to do some type-related work. Those are the official docs about the ValuesView type, in both Python 2 and 3:</p>
<p><a href="https://docs.python.org/2/library/collections.html#collections.ValuesView" rel="nofollow">https://docs.python.org... | 4 | 2016-06-13T07:13:32Z | 38,031,828 | <p>It really <strong>should</strong> from Iterable, and there is no good reason for it not to as far as I can tell.</p>
<p>It is quite clear as I'm sure you're aware as to why it doesn't inherit from Set as the rest of the Views do as it represents the values in a dictionary (<em>which evidently may contain duplicates... | 0 | 2016-06-25T18:45:48Z | [
"python",
"collections",
"abc"
] |
Is there a better way to use sam var multiple a string modulo formatting? | 37,783,759 | <p>I have a row counter in my python code and want to build a Excel formula based on this counter. At the moment I use this code, but I think it is not really python like. Is there a better way to express that?</p>
<pre><code>ws["K%d" % counter] = "=F%i*25+G%i*50+H%i*75+I%i*100" % (counter, counter, counter, counter... | 1 | 2016-06-13T07:14:19Z | 37,783,809 | <p>You can use one of the versions below:</p>
<pre><code># Still using the % operator:
ws["K%d" % counter] = "=F%(c)i*25+G%(c)i*50+H%(c)i*75+I%(c)i*100" % dict(c=counter)
# Using .format()
ws["K%d" % counter] = "=F{c}*25+G{c}*50+H{c}*75+I{c}*100".format(c=counter)
</code></pre>
| 1 | 2016-06-13T07:17:54Z | [
"python"
] |
Is there a better way to use sam var multiple a string modulo formatting? | 37,783,759 | <p>I have a row counter in my python code and want to build a Excel formula based on this counter. At the moment I use this code, but I think it is not really python like. Is there a better way to express that?</p>
<pre><code>ws["K%d" % counter] = "=F%i*25+G%i*50+H%i*75+I%i*100" % (counter, counter, counter, counter... | 1 | 2016-06-13T07:14:19Z | 37,783,873 | <p>Well there are plenty of methods to achieve desired output:</p>
<ol>
<li><p>With positional argument of <a href="https://docs.python.org/2/library/stdtypes.html?highlight=str.format#str.format" rel="nofollow">string.format</a></p>
<pre><code>ws["K%d" % counter] = "=F{0}*25+G{0}*50+H{0}*75+I%{0}*100".format(counter... | 0 | 2016-06-13T07:22:40Z | [
"python"
] |
Python and CSV; how to truncate all values in a column? | 37,783,760 | <p>Given a simple CSV file like this:</p>
<pre><code>Django,Gunslinger,101-707
KingSchultz,Dentist,205-707
Tatum,Marshall,615-707
Broomhilda,Wife,910-707
...,...,...
</code></pre>
<p>How do you truncate all the values in the last column so that only the first three digits remain? (unrelated: so they can be used in ... | 0 | 2016-06-13T07:14:37Z | 37,783,882 | <p><code>re.sub</code> returns the string with the substitution. it does not affect the third argument itself</p>
| 0 | 2016-06-13T07:23:18Z | [
"python",
"regex",
"csv"
] |
Python and CSV; how to truncate all values in a column? | 37,783,760 | <p>Given a simple CSV file like this:</p>
<pre><code>Django,Gunslinger,101-707
KingSchultz,Dentist,205-707
Tatum,Marshall,615-707
Broomhilda,Wife,910-707
...,...,...
</code></pre>
<p>How do you truncate all the values in the last column so that only the first three digits remain? (unrelated: so they can be used in ... | 0 | 2016-06-13T07:14:37Z | 37,783,928 | <p>First thing is <code>re.sub</code> returns a new value, it doesn't replace the value in the row.</p>
<p>secondly, <code>row</code> is a running variable, you should handle this within the loop.</p>
<p>Here your code modified to work correctly (for python3):</p>
<pre><code>import csv
import re
r = csv.reader(open(... | 0 | 2016-06-13T07:26:16Z | [
"python",
"regex",
"csv"
] |
Python and CSV; how to truncate all values in a column? | 37,783,760 | <p>Given a simple CSV file like this:</p>
<pre><code>Django,Gunslinger,101-707
KingSchultz,Dentist,205-707
Tatum,Marshall,615-707
Broomhilda,Wife,910-707
...,...,...
</code></pre>
<p>How do you truncate all the values in the last column so that only the first three digits remain? (unrelated: so they can be used in ... | 0 | 2016-06-13T07:14:37Z | 37,783,947 | <p>Without using <code>re</code> module,</p>
<pre><code>import csv
r = csv.reader(open("sample.csv", "rb"))
writer = csv.writer(open("output.csv", "wb"))
for row in r:
row[2] = row[2][:3]
writer.writerow(row)
</code></pre>
<p>As @TigerRedMike pointed out in Python 3.X, instead of <code>'rb'</code> and <code... | 0 | 2016-06-13T07:27:21Z | [
"python",
"regex",
"csv"
] |
Python and CSV; how to truncate all values in a column? | 37,783,760 | <p>Given a simple CSV file like this:</p>
<pre><code>Django,Gunslinger,101-707
KingSchultz,Dentist,205-707
Tatum,Marshall,615-707
Broomhilda,Wife,910-707
...,...,...
</code></pre>
<p>How do you truncate all the values in the last column so that only the first three digits remain? (unrelated: so they can be used in ... | 0 | 2016-06-13T07:14:37Z | 37,784,066 | <pre><code>import csv
import re
r = csv.reader(open('input.csv'))
writer = csv.writer(open('/tmp/output.csv', 'w'))
for row in r:
tmp = re.sub('\-.*', '', row)
writer.writerow(tmp)
</code></pre>
| 0 | 2016-06-13T07:33:40Z | [
"python",
"regex",
"csv"
] |
interpolate/extrapolate missing dates in python? | 37,783,842 | <p>lets say i have the following dataframe </p>
<pre><code>bb = pd.DataFrame(data = {'date' :['','','','2015-09-02', '2015-09-02', '2015-09-03','','2015-09-08', '', '2015-09-11','2015-09-14','','' ]})
bb['date'] = pd.to_datetime(bb['date'], format="%Y-%m-%d")
</code></pre>
<p>I want to interpolate and ex... | 1 | 2016-06-13T07:20:34Z | 37,784,096 | <p>To extrapolate you have to use <code>bfill()</code> and <code>ffill()</code>. Missing values will be assigned by back- (or forward) values.</p>
<p>To linear interpolate you have to use function <code>interpolate</code> but dates need to convert to numbers:</p>
<pre><code>import numpy as np
import pandas as pd
from... | 1 | 2016-06-13T07:35:35Z | [
"python",
"pandas",
"scipy",
"interpolation",
"extrapolation"
] |
Is it possible to get tkinter messagebox icon image files? | 37,783,878 | <p>I'm developing a python/tkinter application, and finding the default messagebox lacked flexibility, I programmed my own using <code>Toplevel</code>.
I was rather successful in recreating the messabox appearance, however, I could not find a way to obtain the icons displayed in normal tkinter messagebox (i.e. : error,... | 1 | 2016-06-13T07:23:09Z | 37,799,580 | <p>The rough equivalents are available as (tk global variables):</p>
<pre><code>::tk::icons::warning
::tk::icons::error
::tk::icons::information
::tk::icons::question
</code></pre>
<p>Like anything that is not documented, it is subject to change in the future, but these should be stable.</p>
| 0 | 2016-06-13T21:39:53Z | [
"python",
"python-3.x",
"tkinter",
"tk"
] |
Python 2.7 - weird behaviour on finally clause | 37,783,914 | <p>I've run into a very strange problem, that is making me wonder if I understand exception handling at all.</p>
<p>I have a code (that I'll post at the end) that looks more or less like this:</p>
<pre><code>try:
doSomething()
finally:
print 'bye'
</code></pre>
<p>The code in the finally clause is not being ... | 0 | 2016-06-13T07:25:19Z | 37,784,136 | <p>If your code does not handle the <code>KeyboardInterrupt</code> exception, the system has to do it: which means it kills the code. Instead, if you have an exception handler, your code takes over, leaves the loop and then executes the <code>finally</code> block.</p>
| 0 | 2016-06-13T07:37:47Z | [
"python",
"python-2.7",
"exception-handling",
"raspberry-pi"
] |
Python 2.7 - weird behaviour on finally clause | 37,783,914 | <p>I've run into a very strange problem, that is making me wonder if I understand exception handling at all.</p>
<p>I have a code (that I'll post at the end) that looks more or less like this:</p>
<pre><code>try:
doSomething()
finally:
print 'bye'
</code></pre>
<p>The code in the finally clause is not being ... | 0 | 2016-06-13T07:25:19Z | 37,800,923 | <p>Well, this seems to be a bug related to the way RPi.GPIO handles signals (such as KeyboardInterrupt). This module invokes some functions written in c. The function is sort of catching the KeyboardInterrupt and throwing an exception, but it doesn't do it properly. Instead of getting only one exception, the two except... | 0 | 2016-06-13T23:56:25Z | [
"python",
"python-2.7",
"exception-handling",
"raspberry-pi"
] |
django collectstatic does not exclude external folder | 37,783,943 | <p>I located my client project folder and django project folder under the root folder separately. I configured django settings.py to contain client's app folder to serve in development and dist folder to be gathered by collectstatic</p>
<pre><code>STATICFILES_DIRS = [os.path.join(BASE_DIR, "..", "Client/app"), # in de... | 0 | 2016-06-13T07:27:12Z | 37,784,475 | <p>You would not do that normally. You would define a different <code>STATICFILES_DIR</code> depending on what environment you run.</p>
<p>Very basic idea: </p>
<pre><code>if DEBUG:
STATICFILES_DIRS = [os.path.join(BASE_DIR, "..", "Client/app")]
else:
STATICFILES_DIRS = [os.path.join(BASE_DIR, "..", "Client/d... | 1 | 2016-06-13T07:59:13Z | [
"python",
"django",
"collectstatic"
] |
Neo4j ElasticSearch integration | 37,784,019 | <p><a href="http://neo4j.com/developer/elastic-search/#_push_to_elasticsearch" rel="nofollow">http://neo4j.com/developer/elastic-search/#_push_to_elasticsearch</a> says that we can use afterCommit notification method to push data into ES.</p>
<p>Can anybody help me how to do it in python?</p>
| -1 | 2016-06-13T07:30:48Z | 37,784,468 | <p>There is no way to do it in Python, only Java. There are modules that do it for you like <a href="https://github.com/graphaware/neo4j-to-elasticsearch" rel="nofollow">https://github.com/graphaware/neo4j-to-elasticsearch</a> </p>
| 1 | 2016-06-13T07:58:45Z | [
"python",
"elasticsearch",
"neo4j"
] |
Python module variable as central storage for data sharing and access in within threads | 37,784,053 | <p>In my current algorithm, I am doing some interaction with a robot. The robot is running a ROS master, which publishes all the datas itself. My computer, where the algorithm is running, is connected to the ROS master and controls the robot.</p>
<p>The calculations of the algorithm is based on the current state of th... | 0 | 2016-06-13T07:33:07Z | 37,784,509 | <p>You should be able to build a system like you suggested. As long as it's small you shouldn't have any problems, but you should reconsider if you want something that works in larger environments or for longer runs.</p>
<p>The main problems I've seen with designs like this:</p>
<ul>
<li>Clutter. There's always that ... | 0 | 2016-06-13T08:01:00Z | [
"python",
"multithreading",
"algorithm",
"ros"
] |
How do I optionally specify a function argument in Python? | 37,784,121 | <p>In this example, I have a function with an optional argument. E.g.</p>
<pre><code>def func_x(arg_foo='foo'):
# Do something
pass
</code></pre>
<p>While calling the function, I'd like to specify arguments only under certain conditions.</p>
<p>This is one way of doing it.</p>
<pre><code>if cond == True:
func... | 0 | 2016-06-13T07:37:04Z | 37,784,204 | <pre><code>kwargs = {}
if condition_a:
kwargs['arg_a'] = value_a
if condition_b:
kwargs['arg_b'] = value_b
...
long_func_call(**kwargs)
</code></pre>
<p>Use a dict of keyword arguments.</p>
| 4 | 2016-06-13T07:41:58Z | [
"python"
] |
How do I optionally specify a function argument in Python? | 37,784,121 | <p>In this example, I have a function with an optional argument. E.g.</p>
<pre><code>def func_x(arg_foo='foo'):
# Do something
pass
</code></pre>
<p>While calling the function, I'd like to specify arguments only under certain conditions.</p>
<p>This is one way of doing it.</p>
<pre><code>if cond == True:
func... | 0 | 2016-06-13T07:37:04Z | 37,784,341 | <p>You could use a lambda</p>
<pre><code>if cond:
func = lambda:func_x(arg_foo='coo')
else:
func = func_x
func()
</code></pre>
| 0 | 2016-06-13T07:50:41Z | [
"python"
] |
matplotlib scatter array lengths are not same | 37,784,165 | <p>i have 2 arrays like this </p>
<pre><code>x_test = [[ 14. 1.] [ 14. 2.] [ 14. 3.] [ 14. 4.] [ 14. 5.] [ 14. 6.] [ 14. 7.] [ 14. 8.] [ 14. 9.] [ 14. 10.] [ 14. 11.] [ 14. 12.]]
y_test = [ 254.7 255.4 476.5 19.5 85.6 352. 238.7 144.8 83.5 278.8 449.6 312.7]
</code></pre>
<p>i wa... | 0 | 2016-06-13T07:39:37Z | 37,784,261 | <p>The <code>x_test</code>, like you provided it, doesn't make sense for a scatter plot. And the arrays are actually not the same size:</p>
<pre><code>print(x_test.shape)
print(y_test.shape)
</code></pre>
<blockquote>
<p>(12, 2)</p>
<p>(12,)</p>
</blockquote>
<p>What you might want to have instead is somethin... | 1 | 2016-06-13T07:46:12Z | [
"python",
"arrays",
"matplotlib"
] |
Querying data in Python based on the business day (8am-10pm) and weekdays only | 37,784,280 | <p>My question is very much open ended and am looking for some advice on how to manipulate an array with the following format: </p>
<pre><code>list:
[datetime.datetime(2016, 5, 17, 11, 32, 25),
datetime.datetime(2016, 5, 17, 11, 33, 25),
datetime.datetime(2016, 5, 17, 11, 34, 25), ...
</code></pre>
<p>I'm looking to ... | 2 | 2016-06-13T07:47:39Z | 37,784,458 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.bdate_range.html" rel="nofollow">bdate_range()</a> for selecting only business days (1):</p>
<pre><code>In [96]: d.ix[pd.to_datetime(d.Date.dt.date).isin(pd.bdate_range(start='2016-05-16', end='2016-05-22'))]
Out[96]:
... | 3 | 2016-06-13T07:58:10Z | [
"python",
"arrays",
"datetime",
"numpy",
"pandas"
] |
Theano - Sum by group | 37,784,296 | <p>I'm working on a custom likelihood function for Theano (Attempting to fit a conditional logistic regression.)</p>
<p>The likelihood requires summing values <strong><em>by group</em></strong>. In R we have the "ave()" function, in Python Pandas we have "groupby()". How would I do something similar in Theano?</p>
... | 1 | 2016-06-13T07:48:24Z | 38,650,293 | <p>Let say you have "X" (a list of all your etas), with the dim. Nx1 (I guess) and a matrix H. H is a NxG matrix that has a on-hot encoding of the groups.</p>
<p>The you you write something like:</p>
<pre><code>import numpy as np
from numpy import newaxis as na
import theano.tensor as T
X = T.vector()
H = T.matrix()... | 1 | 2016-07-29T03:58:40Z | [
"python",
"theano"
] |
Need help understanding section of code | 37,784,315 | <p>I wrote a piece of code, it was marked by an auto machine-bot.</p>
<p>We are not allowed to question this bot, its "100% correct".</p>
<p>I got 90%. Professor wont go over it, and we are "meant to" pay a higher year student to help us if we have troubles, because this is a basic level course.</p>
<p>Here is the c... | -3 | 2016-06-13T07:49:03Z | 37,784,450 | <p>Your error handling will currently return the list if a value inside can't be converted to a int. it should instead go to the next item.</p>
<pre><code>def something(placeholder):
"""
append intengers
"""
siba = list()
for items in placeholder:
try:
siba.append(int(items))
... | 2 | 2016-06-13T07:57:51Z | [
"python"
] |
split one python list or dataframe with single column into a pandas dataframe multiple columns | 37,784,365 | <p>I have a dataframe and a list with 290 items in it (index 0-289) and I'm wondering how to split this long list into a dataframe with 10 columns and 29 rows.</p>
| -4 | 2016-06-13T07:52:26Z | 37,784,446 | <p>I think you can create <code>numpy.array</code> and then <a href="http://docs.scipy.org/doc/numpy-1.10.4/reference/generated/numpy.reshape.html" rel="nofollow"><code>numpy.reshape</code></a> with <code>DataFrame</code> constructor:</p>
<pre><code>#python 3
L = list(range(290))
#python 2
#L = range(290)
print (L)
[0... | 2 | 2016-06-13T07:57:31Z | [
"python",
"pandas",
"dataframe"
] |
Functional Programming using python for extracting consecutive capitalized words | 37,784,414 | <p>I am now using python to extract consecutive capitalized words (at least two) in a text. </p>
<p>For example, there is a sentence</p>
<blockquote>
<p>Hollywood is a neighborhood in the central region of Los Angeles.</p>
</blockquote>
<p>Then the expected output should be</p>
<blockquote>
<p>Los Angeles</p>
<... | 0 | 2016-06-13T07:55:18Z | 37,784,777 | <p>Is not really a good practice in python, but the shortest way is to reduce the splited text:</p>
<pre><code>p = "Hollywood is a neighborhood in the central region of Los Angeles.".split()
t, _ = reduce(lambda (l, v), x: (l+[v, x], x) if v[0].isupper() and x[0].isupper() else (l, x), p, ([], "a"))
['Los', 'Angeles.'... | 1 | 2016-06-13T08:16:48Z | [
"python"
] |
Functional Programming using python for extracting consecutive capitalized words | 37,784,414 | <p>I am now using python to extract consecutive capitalized words (at least two) in a text. </p>
<p>For example, there is a sentence</p>
<blockquote>
<p>Hollywood is a neighborhood in the central region of Los Angeles.</p>
</blockquote>
<p>Then the expected output should be</p>
<blockquote>
<p>Los Angeles</p>
<... | 0 | 2016-06-13T07:55:18Z | 37,784,914 | <p>Have a look at this:</p>
<pre><code>from itertools import takewhile
text = "Take any tram, U-bahn or bus which stops at Düsseldorf Hauptbahnhof (HBF). Leave the station via the main exit Konrad Adenauer Platz, you will see trams and buses in front of the station. Walk up Friedrich Ebert StraÃe turning right into... | 1 | 2016-06-13T08:24:43Z | [
"python"
] |
Functional Programming using python for extracting consecutive capitalized words | 37,784,414 | <p>I am now using python to extract consecutive capitalized words (at least two) in a text. </p>
<p>For example, there is a sentence</p>
<blockquote>
<p>Hollywood is a neighborhood in the central region of Los Angeles.</p>
</blockquote>
<p>Then the expected output should be</p>
<blockquote>
<p>Los Angeles</p>
<... | 0 | 2016-06-13T07:55:18Z | 37,785,057 | <p>I think the entry call would be <code>ngram_phrase(text.split(), 2)</code> and OP is looking for <em>all the occurrence of phrases whose number of consecutive capitalized initials is at least 2</em>, e.g. running the code snippet together with <code>text</code> would result <code>["Düsseldorf Hauptbahnhof", "Konrad... | 1 | 2016-06-13T08:31:48Z | [
"python"
] |
Functional Programming using python for extracting consecutive capitalized words | 37,784,414 | <p>I am now using python to extract consecutive capitalized words (at least two) in a text. </p>
<p>For example, there is a sentence</p>
<blockquote>
<p>Hollywood is a neighborhood in the central region of Los Angeles.</p>
</blockquote>
<p>Then the expected output should be</p>
<blockquote>
<p>Los Angeles</p>
<... | 0 | 2016-06-13T07:55:18Z | 37,785,332 | <p>I would have provided on of the answers above but they were already provided! So I wrote the following function to allow you to see the flow.</p>
<pre><code>def find_proper(text):
text = text.rstrip().split(' ')
proper = []
data, cnt, pos, str = [x[0].isupper() for x in text], 0, 0, ''
while True:
... | 1 | 2016-06-13T08:47:48Z | [
"python"
] |
Django Rest Framework way to ingest json data? | 37,784,538 | <p>Hey guys I'm trying to ingest some data from a third party API when a DRF endpoint is called.</p>
<p>I can easily build the get request using urllib2 and deserialize the json, but is there some way to use django serializers and do it the drf way? Or am I just overthinking this?</p>
<pre><code>import json, urllib2
... | 0 | 2016-06-13T08:02:44Z | 37,784,877 | <p>From your example code,</p>
<pre><code>import requests
class IngestThirdPartyView():
def post(self, request):
data = request.data
url = 'https://third_party.com/media/{}'.format(data['item_id]')
item = requests.get(url).json() # this will retrieve json response
# then you could ... | 0 | 2016-06-13T08:22:09Z | [
"python",
"json",
"django",
"rest"
] |
(Python) run another python file and store/search it's output | 37,784,611 | <p>So ok.
I'm new to coding python so if it's very easy please don't blame me. (also for my english)
So I want to make an automatic sql injector using sqlmap. I have done the dork search'er.What I want to do is after a sql vulnerable link found it will launch sqlmap with parameters[ -u %s(vulnerable link) ] That's good... | 0 | 2016-06-13T08:07:13Z | 37,785,621 | <p>Don't sure It will help you but you can export all Python output of a Python script. To do that you can set <code>sys.stdout</code> to an file object. Here an example:</p>
<pre><code>import sys
sys.stdout = open('file', 'w')
print 'test'
</code></pre>
| 0 | 2016-06-13T09:03:13Z | [
"python",
"sqlmap"
] |
Unable to insert an article into MySQL Python | 37,784,656 | <p>I'm trying to insert full article to MySQL database, but it didn't work..
i think i have an encoding issues because when i print, it started
with <code>'[u'</code> .. i've tried some code but it didn't work. the content/article might be containing <code>,</code> and <code>"</code> resulting the sql text messed up</... | 0 | 2016-06-13T08:09:50Z | 37,785,458 | <p>Hi which library do you use?</p>
<p>As far as i know the most libraries implements DB-API commons. So you can send the data via parameterization which prevents sql injections.</p>
<p>I am using oursql in python and the syntax is:</p>
<pre><code>curs.execute('SELECT * FROM `some_table` WHERE `col1` = ? AND `col2` ... | 0 | 2016-06-13T08:54:42Z | [
"python",
"mysql",
"scrapy"
] |
Python: Update a Dict using data from a pandas dataframe | 37,784,660 | <p>So, I have a pandas dataframe like this.</p>
<pre><code> mac_address City
0 00:03:7f:05:c0:06 Kolkata
1 00:08:22:1c:50:07 Bhubaneswar
2 00:08:22:1c:50:07 Mumbai
3 00:08:22:1c:50:07 Mumbai
4 00:08:22:1c:50:07 Kolkata
5 00:08:22:24:cc:fb Bhubaneswar
6 00:08:22:24:f8:02 ... | 4 | 2016-06-13T08:10:06Z | 37,785,166 | <p>you can construct your dictionary, that might be saved as the JSON file like this:</p>
<pre><code>In [129]: %paste
(df.groupby(['mac_address','City'])
.size()
.reset_index()
.rename(columns={'City':'name',0:'count'})
.groupby('mac_address')
.apply(lambda x: {'mac_address':x.name, 'cities': x[['name',... | 2 | 2016-06-13T08:38:12Z | [
"python",
"dictionary",
"pandas"
] |
Can I Cache/Save Expensive SQL Queries for a week? | 37,784,721 | <p>I have a very large DB with 50 million records. I
I have some very expensive queries that I want to run for indepth statistics purposes. These queries will slow down the server/database. So i dont want to run them more than once - I want to run them on a sunday night and store the results for the week.</p>
<p>I don... | 1 | 2016-06-13T08:13:12Z | 37,995,744 | <p>I use the <a href="https://msdn.microsoft.com/en-us/library/ms189237.aspx" rel="nofollow">job agent</a> that comes with <a href="https://msdn.microsoft.com/en-us/library/mt238290.aspx" rel="nofollow">SQL Server Management Studio</a> for similar purposes. If your DB is not SQL Server you can add it as a <a href="http... | 0 | 2016-06-23T15:21:13Z | [
"python",
"sql"
] |
Openpyxl with python2.7 | 37,784,728 | <p>I wanted to open excel file on python with using this code.</p>
<pre><code>import openpyxl
wb= openpyxl.load_workbook('testfile.xlsx')
</code></pre>
<p>Error:No such file or directory: 'testfile.xlsx'</p>
<p>Where should I locate this file?</p>
<p>I am using Python2.7 on Spyder</p>
| -1 | 2016-06-13T08:13:52Z | 37,784,771 | <p>Make sure that there is that file in the folder... Try this command to list the files in that folder just to make sure that python atleast recognizes or reads the files.</p>
<pre><code>import os
print (os.listdir('your path'))
</code></pre>
<p>Try giving an absolute path. I mean give a leading slash which means an... | 0 | 2016-06-13T08:16:34Z | [
"python",
"python-2.7",
"openpyxl"
] |
Capturing rows till first response for a campaign in python | 37,784,795 | <p>I have email campaign data capturing the time, target and response (whether the user opens the link). A response of 1 means that user has opened the content.</p>
<p>Sample Data:</p>
<pre><code>senddate userid content response
2016-06-01 100 50505 NaN
2016-06-01 100 50505 NaN
2016-06-01 100 ... | 2 | 2016-06-13T08:17:41Z | 37,784,928 | <p>You can use <a href="http://pandas.pydata.org/" rel="nofollow"><code>pandas</code></a> to achieve this:</p>
<p>If you <code>groupby</code> on the 'senddate' column we can generate a boolean mask comparing the index against the <code>first_valid_index</code>, this will create a multi-index where the first level are ... | 1 | 2016-06-13T08:25:37Z | [
"python"
] |
Gmail Api return Unauthorized client or scope in request | 37,785,048 | <p>I have struggled to make this work but did half the job.</p>
<p>Actually I can only read messages from Gmail API, If I try to use the gmail.modify Scope I get an error:</p>
<p><strong>HttpAccessTokenRefreshError: unauthorized_client: Unauthorized client or scope in request.</strong></p>
<p>Here is my code:</p>
<... | 0 | 2016-06-13T08:31:28Z | 37,807,055 | <p>Based from this <a href="https://developers.google.com/+/domains/authentication/delegation" rel="nofollow">documentation</a>, you need to use the client ID from your "Developers Console" as the Client Name in the "Manage API client access" when you're setting your API scopes. Google API does not work as expected wit... | 0 | 2016-06-14T08:43:48Z | [
"python",
"authorization",
"gmail-api"
] |
Unable to start Airflow worker/flower and need clarification on Airflow architecture to confirm that the installation is correct | 37,785,061 | <p>Running a worker on a different machine results in errors specified below. I have followed <a href="https://pythonhosted.org/airflow/configuration.html" rel="nofollow">the configuration instructions</a> and have sync the dags folder.</p>
<p>I would also like to confirm that RabbitMQ and PostgreSQL only needs to be ... | 1 | 2016-06-13T08:32:00Z | 37,835,768 | <p>You need to ensure to install Celery Flower. That is, <code>pip install flower</code>.</p>
| 4 | 2016-06-15T12:41:01Z | [
"python",
"rabbitmq",
"celery",
"airflow"
] |
Unable to start Airflow worker/flower and need clarification on Airflow architecture to confirm that the installation is correct | 37,785,061 | <p>Running a worker on a different machine results in errors specified below. I have followed <a href="https://pythonhosted.org/airflow/configuration.html" rel="nofollow">the configuration instructions</a> and have sync the dags folder.</p>
<p>I would also like to confirm that RabbitMQ and PostgreSQL only needs to be ... | 1 | 2016-06-13T08:32:00Z | 39,967,889 | <p>The <code>ImportError: No module named postgresql</code> error is due to the invalid prefix used in your <code>celery_result_backend</code>. When using a database as a Celery backend, the connection URL must be prefixed with <code>db+</code>. See <a href="http://docs.celeryproject.org/en/latest/configuration.html#co... | 0 | 2016-10-10T22:46:54Z | [
"python",
"rabbitmq",
"celery",
"airflow"
] |
Error when using os.system in python but not in shell | 37,785,106 | <p>I am trying to redirect the out of gnu make.
Want to redirect ALL to both STDOUT and all.log and error only to error.log.</p>
<p>Below is my program</p>
<pre><code>#!/usr/bin/env python
import optparse
import os
import sys
import commands
command = 'make all > >(tee -a all.log ) 2>&1 2> >(tee ... | 1 | 2016-06-13T08:34:30Z | 37,785,278 | <p><code>os.system()</code> calls *nix <code>system()</code> call.</p>
<blockquote>
<p>The system() library function uses fork(2) to create a child process
that executes the shell command specified in command using execl(3)
as follows:
execl("/bin/sh", "sh", "-c", command, (char *) 0);... | 0 | 2016-06-13T08:44:31Z | [
"python",
"linux",
"bash",
"shell"
] |
Error when using os.system in python but not in shell | 37,785,106 | <p>I am trying to redirect the out of gnu make.
Want to redirect ALL to both STDOUT and all.log and error only to error.log.</p>
<p>Below is my program</p>
<pre><code>#!/usr/bin/env python
import optparse
import os
import sys
import commands
command = 'make all > >(tee -a all.log ) 2>&1 2> >(tee ... | 1 | 2016-06-13T08:34:30Z | 37,785,433 | <p><code>os.system</code> start <code>/bin/sh</code> and you have bashism in your command:</p>
<pre><code>>(....)
</code></pre>
<p>You will need to start bash:</p>
<pre><code>os.system("bash -c '{}'".format(command))
</code></pre>
<p>Also remember if you use single quotes in your command they need to be escaped ... | 0 | 2016-06-13T08:53:20Z | [
"python",
"linux",
"bash",
"shell"
] |
Python regex extracting floatin values | 37,785,131 | <p>I have data that has strings with floating numbers like </p>
<pre><code>"['0.0'" and '82.00.0' and '82.0\n'
</code></pre>
<p>and I only want to extract floating points till two/one decimal points like so-</p>
<pre><code>"['0.0'" and '82.00.0' and '82.0\n' to 0.0, 82.0, 82.0
</code></pre>
<p>The data structure is... | 1 | 2016-06-13T08:35:53Z | 37,785,977 | <p>Try this:</p>
<pre><code>import re
s = '82.00\n 1.3000 9.1'
result = re.findall(r'\d+\.\d{1,2}', s)
print result
</code></pre>
<p><strong>Output:</strong> ['82.00', '1.30', '9.1']</p>
| 0 | 2016-06-13T09:19:12Z | [
"python",
"regex",
"floating-point",
"decimal"
] |
Python regex extracting floatin values | 37,785,131 | <p>I have data that has strings with floating numbers like </p>
<pre><code>"['0.0'" and '82.00.0' and '82.0\n'
</code></pre>
<p>and I only want to extract floating points till two/one decimal points like so-</p>
<pre><code>"['0.0'" and '82.00.0' and '82.0\n' to 0.0, 82.0, 82.0
</code></pre>
<p>The data structure is... | 1 | 2016-06-13T08:35:53Z | 37,788,804 | <p>There are several issues:</p>
<ul>
<li>You did not assign the split chunks to a variable (see <code>tempprices.split(',')</code>)</li>
<li>You actually have to extract 1 value, so the <code>re.sub</code> can work, but a <code>re.search</code> is safer</li>
</ul>
<p>You may use the following fix:</p>
<pre><code>im... | 1 | 2016-06-13T11:35:19Z | [
"python",
"regex",
"floating-point",
"decimal"
] |
Getting the correct axes label in imshow in python | 37,785,191 | <p>I am using the following code to generate some contour plots,</p>
<pre><code>from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
import numpy as np
from numpy import exp,arange
import matplotlib.pyplot as plt
def z_func(x,y):
func = 3.0*(1.0 - x)**2*np.exp(-x**2 - (y+1.0)**2) - 10.0*(x... | 1 | 2016-06-13T08:39:23Z | 37,785,753 | <p>Try this code, you have to set limits in both functions <code>contour</code> and <code>imshow</code> as I did:</p>
<pre><code>import matplotlib.pylab as plt
import numpy as np
x = np.arange(-4.0,4.0,0.1)
y = np.arange(-4.0,4.0,0.1)
X,Y = np.meshgrid(x, y) # grid of point
Z = X**2. * np.sin(Y)
fig = plt.figure(fig... | 1 | 2016-06-13T09:09:48Z | [
"python",
"matplotlib",
"imshow"
] |
Permission denied in mounted volume in docker | 37,785,220 | <p>I'm mounting a volume from my local host in a docker container using docker-compose (added the <code>volumes</code> entry id docker-compose.yml)</p>
<p>This works well, but when I try to run py.test I get permission errors:</p>
<p><code>OSError: [Errno 13] Permission denied: '/foo/bar/.coverage'</code> etc</p>
<p... | 1 | 2016-06-13T08:40:38Z | 37,826,289 | <p>You can do anything (like a volume mount) in the docker container as long as the Docker itself has the right permission. You should exec your container using following:</p>
<p>docker exec -it -u 0 Container_NAME /bin/bash</p>
<p>And then execute py.test, I just hope you're not doing su - to some user within py.tes... | 0 | 2016-06-15T04:40:29Z | [
"python",
"docker",
"py.test"
] |
How to install MySQL-python on Amazon Web Services EC2 instance? | 37,785,330 | <p>I have a EC2 instance created on AWS and use PuTTY to connect to it.<br>
I'm unable to install <strong><em>MySQL-python</em></strong> using python <strong><em>pip</em></strong> command as follows:
<br>
<strong><em>pip install MySQL-python</em></strong>(via root privileges)
<br>
<br>
Here is the console output of the... | 0 | 2016-06-13T08:47:42Z | 37,785,489 | <p>It looks like mysql_config is missing, so make sure mysql_config is really installed.</p>
<p>For example on Debian/Ubuntu you must install the package:</p>
<pre><code>sudo apt-get install libmysqlclient-dev
</code></pre>
| 0 | 2016-06-13T08:56:45Z | [
"python",
"mysql",
"amazon-web-services",
"amazon-ec2",
"setup.py"
] |
Sync Choregraphe and Matlab | 37,785,380 | <p>I have a Wizard of Oz experiment using Choregraphe to make a NAO perform certain tasks running on machine A. The participant interacting with the NAO also interacts with a machine B. When I start the experiment (in Choregraphe on machine A) I want a certain MATLAB script to start on machine B. I.e. Choregraphe will ... | 0 | 2016-06-13T08:50:40Z | 37,796,440 | <p>Using NAO C++ SDK, it may be possible to make a MEX-FILE in Matlab that "listens" to NAO. Then NAO just has to raise an event in its memory (ALMemory) that Matlab would catch to start running the script.</p>
| 0 | 2016-06-13T18:08:12Z | [
"python",
"c++",
"matlab",
"nao-robot"
] |
Count number of words in a file using dictionary comprehension - python | 37,785,412 | <p>In the following code using dictionary comprehension am trying to count the total number of words with duplicates but this results in <code>{'count': 1, 'words.As': 1, 'said': 1, 'file.\n': 1, 'this': 1, 'text': 1, 'is': 1, 'of': 1, 'some': 1, ',i': 1, 'to': 1, 'only': 1, 'Hi': 1, 'a': 1, 'file': 1, 'recognize': 1, ... | 0 | 2016-06-13T08:52:11Z | 37,785,565 | <p>You can't use dictionary comprehension. Because <code>di</code> doesn't change during it's creation and your code will raise a <code>NameError</code> if you didn't defined the dictionary already.</p>
<pre><code>>>> s = """Hi this is some text to recognize the count of words.
... As said before this is only... | 2 | 2016-06-13T09:00:56Z | [
"python"
] |
Count number of words in a file using dictionary comprehension - python | 37,785,412 | <p>In the following code using dictionary comprehension am trying to count the total number of words with duplicates but this results in <code>{'count': 1, 'words.As': 1, 'said': 1, 'file.\n': 1, 'this': 1, 'text': 1, 'is': 1, 'of': 1, 'some': 1, ',i': 1, 'to': 1, 'only': 1, 'Hi': 1, 'a': 1, 'file': 1, 'recognize': 1, ... | 0 | 2016-06-13T08:52:11Z | 37,785,591 | <p>You can't access <code>di</code> while it is being populated.</p>
<p>Instead, simply use a <code>Counter</code></p>
<pre><code>from collections import Counter
counter = Counter()
with open('test_readme.txt') as f:
for line in f:
counter += Counter(line.split())
</code></pre>
| 2 | 2016-06-13T09:01:51Z | [
"python"
] |
Count number of words in a file using dictionary comprehension - python | 37,785,412 | <p>In the following code using dictionary comprehension am trying to count the total number of words with duplicates but this results in <code>{'count': 1, 'words.As': 1, 'said': 1, 'file.\n': 1, 'this': 1, 'text': 1, 'is': 1, 'of': 1, 'some': 1, ',i': 1, 'to': 1, 'only': 1, 'Hi': 1, 'a': 1, 'file': 1, 'recognize': 1, ... | 0 | 2016-06-13T08:52:11Z | 37,785,649 | <p>I would use counter but on the whole string:</p>
<pre><code>from collections import Counter
with open('readme.txt') as f:
s = Counter(f.read().replace('\n', '').split(' '))
#Out[8]: Counter({'this': 2, 'is': 2, 'test': 2, 'count': 1, 'words.As': 1, 'said': 1, 'text': 1, 'of': 1, 'some': 1, ',i': 1, 'to': 1, 'o... | 1 | 2016-06-13T09:04:49Z | [
"python"
] |
Count number of words in a file using dictionary comprehension - python | 37,785,412 | <p>In the following code using dictionary comprehension am trying to count the total number of words with duplicates but this results in <code>{'count': 1, 'words.As': 1, 'said': 1, 'file.\n': 1, 'this': 1, 'text': 1, 'is': 1, 'of': 1, 'some': 1, ',i': 1, 'to': 1, 'only': 1, 'Hi': 1, 'a': 1, 'file': 1, 'recognize': 1, ... | 0 | 2016-06-13T08:52:11Z | 37,785,759 | <p>A very readable solution would be</p>
<pre><code>Thedict = {}
fo = open('sample.txt')
for line in fo:
for word in line.split(' '):
word = word.strip('.').strip()
if(word in Thedict):
Thedict[word] = Thedict[word] + 1
else:
Thedict[word] = 0
print(Thedict)
</code>... | 1 | 2016-06-13T09:10:03Z | [
"python"
] |
Count number of words in a file using dictionary comprehension - python | 37,785,412 | <p>In the following code using dictionary comprehension am trying to count the total number of words with duplicates but this results in <code>{'count': 1, 'words.As': 1, 'said': 1, 'file.\n': 1, 'this': 1, 'text': 1, 'is': 1, 'of': 1, 'some': 1, ',i': 1, 'to': 1, 'only': 1, 'Hi': 1, 'a': 1, 'file': 1, 'recognize': 1, ... | 0 | 2016-06-13T08:52:11Z | 37,785,786 | <p>Yet another <code>Counter</code> solution, runs the file through in a single call to <code>Counter</code> iteratively using a nested generator expression:</p>
<pre><code>from collections import Counter
with open('test_readme.txt') as f:
counts = Counter(word for line in f for word in line.strip().split())
</co... | 1 | 2016-06-13T09:11:30Z | [
"python"
] |
canny detection in python with openCV | 37,785,432 | <p>i applied a canny edges detection on an image and i get as a result this image </p>
<p><a href="http://i.stack.imgur.com/PTmQ0.png" rel="nofollow"><img src="http://i.stack.imgur.com/PTmQ0.png" alt="enter image description here"></a></p>
<p>i get the coordinates of this, using :</p>
<pre><code>ans = []
for y in ra... | 0 | 2016-06-13T08:53:19Z | 37,785,618 | <p>You should try using hierarcy in the contour to define which is parent and which is child, and then you can loope inside the hierarcy and draw only the parent contours (or the outermost contours).</p>
<p>For example take a look at this image</p>
<p><a href="http://i.stack.imgur.com/uzrTF.png" rel="nofollow"><img s... | 2 | 2016-06-13T09:03:00Z | [
"python",
"opencv",
"contour"
] |
Unable to serve static files with Django runserver | 37,785,682 | <p>I have this configuration in my settings.py file</p>
<pre><code>INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'dashboard',
)
MIDDLEWA... | 0 | 2016-06-13T09:05:56Z | 37,786,843 | <p>Please try specifying <code>STATICFILES_DIRS</code> in <code>settings.py</code> file.</p>
<pre><code>STATICFILES_DIRS = '/home/workspace/app-toscana/django/djangoapptoscana/djangoapptoscana/static'
</code></pre>
<p><code>STATIC_ROOT</code> is the absolute path to the directory where <code>./manage.py collectstatic... | 1 | 2016-06-13T10:01:29Z | [
"python",
"django",
"static",
"django-staticfiles"
] |
Distributing Hadoop Streaming Output files on basis of Keys | 37,785,726 | <p>I have written a mapper function that parses the XML and outputs the result as columns separted by "\t" as shown below</p>
<pre><code>Name Age
ABC 23
XYZ 24
ERT 25
</code></pre>
<p>Using the Hadoop Streaming Code as mentioned below, I am trying to partition the data on the basis of key. I want to make differ... | 0 | 2016-06-13T09:08:08Z | 37,872,451 | <p>I think you need a jar like this.</p>
<pre><code>import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.lib.MultipleTextOutputFormat;
public class TestMultipleOutputFormat extends MultipleTextOutputFormat<Text, Text> {
protected String generateFileNameForKeyValue(Text key, Text value, Strin... | 0 | 2016-06-17T03:04:50Z | [
"python",
"hadoop",
"mapreduce",
"hadoop-streaming",
"hadoop-partitioning"
] |
Is there a way to give a sequence to initializer of Union in Python typing | 37,785,783 | <p>I have code that looks like this:</p>
<pre><code>MY_SPECIAL_CLASSES = (Foo, Bar, Spam, Eggs)
</code></pre>
<p>I have many functions that take any of those as the input parameter,</p>
<p>so their signature is e.g.:</p>
<pre><code>def whatever(obj: Union[Foo, Bar, Spam, Eggs]) -> None:
</code></pre>
<p>To me, ... | 0 | 2016-06-13T09:11:19Z | 37,817,367 | <p>You're misreading the PEP. The default invariance of type variables means that it's an error to pass a <code>Foo[Subclass]</code> where a <code>Foo[Superclass]</code> is expected, but it's fine to pass a <code>Subclass</code> to a parameter annotated as <code>SuperClass</code>.</p>
<p>As long as your function accep... | 1 | 2016-06-14T16:21:53Z | [
"python",
"type-hinting"
] |
how to run httpie from script.py | 37,785,808 | <p>I need to send forms to a rest service from py-scripts. i try to do it using httpie.</p>
<p>when i invoke <code>run(['http', '--help'])</code> i've got expected result.
if i invoke <code>run(['http', 'http://site/page'])</code> the script is stuck and nothig happens.</p>
<p>I also tried to place running of httpie ... | 0 | 2016-06-13T09:12:18Z | 37,789,076 | <p>Try to include the <code>--ignore-stdin</code> option:</p>
<pre><code>run(['http', '--ignore-stdin', 'http://site/page'])
</code></pre>
<blockquote>
<p>The <code>--ignore-stdin</code> option prevents HTTPie from reading data from
stdin, which is usually not desirable during non-interactive
invocations. </p>
... | 1 | 2016-06-13T11:49:26Z | [
"python",
"httpie"
] |
Append millions of JSON files into a single file efficiently | 37,785,825 | <p>I have millions of json files which I need to append to a single json file as a list of json dicts:</p>
<p>Each json file contains following dict:</p>
<pre><code>{
"finent": "abc",
"findeplabel": "lbl",
}
</code></pre>
<p>Should be combined into a single json file as a list of dicts:</p>
<pre><code>[{
"fin... | 0 | 2016-06-13T09:12:55Z | 37,791,818 | <p>I can't speak about its efficiency, but with jq, it's just a matter of slurping all files together:</p>
<pre><code>jq -s '.' *.json
</code></pre>
| 0 | 2016-06-13T14:05:14Z | [
"python",
"json",
"large-files",
"large-data",
"jq"
] |
Append millions of JSON files into a single file efficiently | 37,785,825 | <p>I have millions of json files which I need to append to a single json file as a list of json dicts:</p>
<p>Each json file contains following dict:</p>
<pre><code>{
"finent": "abc",
"findeplabel": "lbl",
}
</code></pre>
<p>Should be combined into a single json file as a list of dicts:</p>
<pre><code>[{
"fin... | 0 | 2016-06-13T09:12:55Z | 37,804,300 | <p>I found an excellent efficient way of doing it:</p>
<pre><code> ls |xargs -n 10000 -P 8 jq -s '.' >>../jsonparsed
</code></pre>
<p>This spawn 8 concurrent processes each having 10k arguments and writes to a single jsonfile jsonparsed</p>
| 0 | 2016-06-14T06:18:27Z | [
"python",
"json",
"large-files",
"large-data",
"jq"
] |
Append millions of JSON files into a single file efficiently | 37,785,825 | <p>I have millions of json files which I need to append to a single json file as a list of json dicts:</p>
<p>Each json file contains following dict:</p>
<pre><code>{
"finent": "abc",
"findeplabel": "lbl",
}
</code></pre>
<p>Should be combined into a single json file as a list of dicts:</p>
<pre><code>[{
"fin... | 0 | 2016-06-13T09:12:55Z | 37,892,844 | <p>The following script (slurp.sh) exemplifies a direct approach using bash.
It can easily be modified depending on how the relevant JSON files are to be specified.</p>
<p>I suspect that it would take much longer to develop and test a more complex solution than doing so will save in execution time, but if you want to ... | 1 | 2016-06-18T03:05:12Z | [
"python",
"json",
"large-files",
"large-data",
"jq"
] |
Python/Django - Same Try / Except | 37,785,829 | <p>Actually I have 3 try / Except in the same view, because I'm using 3 objects in my models. The problem is I'm reapeating in my code and I don't like that.</p>
<p>Here is the code :</p>
<pre><code> try:
menuDetail = Menu.objects.get(id=menuId)
except Menu.DoesNotExist:
return logoutUser(request)
try:
... | 0 | 2016-06-13T09:13:06Z | 37,786,222 | <p>Posting here for readability.</p>
<p>You can rewrite your code as so :</p>
<pre><code>try:
menuDetail = Menu.objects.get(id=menuId)
menuItem = MenuItem.objects.get(id=menuItemId)
menuItemProd = MenuItemProd.objects.get(id=menuItemId)
except (Menu.DoesNotExist, MenuItem.DoesNotExist, MenuItemProd.DoesNo... | 1 | 2016-06-13T09:31:09Z | [
"python",
"django"
] |
Is it possible to create a HTTP response via scapy | 37,785,839 | <p>I want to send a HTTP response via scapy to a target system. I know scapy uses layered implementation to create a packet like IP/TCP/ETHER. To send a simple TCP packet we can use the following scapy script.</p>
<pre><code>#!/usr/bin/python
from scapy.all import *
ip=IP(src="10.10.1.207", dst="10.10.1.60")
payload... | 0 | 2016-06-13T09:13:23Z | 37,792,032 | <p>Scapy does not have a native HTTP layer dissector, however, you can send an HTTP request/response easily as it is a textual protocol:</p>
<pre><code>RESP = "HTTP/1.1 200 OK\r\n"
RESP += "Server: exampleServer\r\n"
RESP += "Content-Length: 6\r\n"
RESP += "\r\n"
RESP += "A body"
IP(src="10.10.1.207", dst="10.10.1.6... | 1 | 2016-06-13T14:14:20Z | [
"python",
"http",
"tcp",
"scapy"
] |
Project Euler - #1 Python wrong solution | 37,785,902 | <p>I am relatively new to coding in general and started Project Euler to bring my coding a bit further. Spent some time thinking of how to work the first question on my own and tried using recursive functions, unfortunately always getting the same mistake (266333). What did i miss? Any big mistake to learn from?</p>
<... | 0 | 2016-06-13T09:16:05Z | 37,786,097 | <p>Your mistake is that you are including numbers divisible by 15 twice: Once as a multiple of 3, and once as a multiple of 5.</p>
<p>For what it's worth, here's a concise way of computing this sum:</p>
<pre><code>sum(i for i in range(1000) if not (i % 3 and i % 5))
</code></pre>
| 1 | 2016-06-13T09:25:02Z | [
"python",
"recursion",
"sum",
"project"
] |
Project Euler - #1 Python wrong solution | 37,785,902 | <p>I am relatively new to coding in general and started Project Euler to bring my coding a bit further. Spent some time thinking of how to work the first question on my own and tried using recursive functions, unfortunately always getting the same mistake (266333). What did i miss? Any big mistake to learn from?</p>
<... | 0 | 2016-06-13T09:16:05Z | 37,786,651 | <p>I'd strongly advise against recursion, since it might work for small number but not for bigger ones, and even if the solution might work, it would teach you a wrong approach.</p>
<pre><code>def euler_1(sum, range_beg, range_end):
for number in range( range_beg, range_end):
if (( number % 3 ) == 0) or ((... | 0 | 2016-06-13T09:52:17Z | [
"python",
"recursion",
"sum",
"project"
] |
MySQL, fetchone and LIMIT | 37,785,965 | <p>Here is a sample of python code:</p>
<pre><code>query = "SELECT * FROM users WHERE id = 17"
cursor.execute(query)
row = cursor.fetchone()
</code></pre>
<p>In this example, the query is meant to return at most a single row; but sometimes I want to fetch a single row from a multiple-row result with the same code, fo... | 1 | 2016-06-13T09:18:53Z | 37,786,038 | <p>No, the LIMIT clause is executed after the SELECT on the Result set. if you have much rows with the id = 17 , you must transfer a little bit more from the server to the client if you do not use LIMIT.</p>
| 0 | 2016-06-13T09:22:09Z | [
"python",
"mysql",
"mysql-python",
"query-performance"
] |
What is the name of the DirectShow dataflow pattern? | 37,785,987 | <p>I am trying to code a simple filter chain in python that works well with multiple inputs (camera, keyboard, mouse) and outputs (video, audio).</p>
<p>I have previously developed DirectShow filters and I really like the architecture, but I have the feeling that it is too complex for my needs, though I might be mista... | 0 | 2016-06-13T09:19:33Z | 37,788,663 | <p>DirectShow and other multimedia frameworks use a <a href="https://en.wikipedia.org/wiki/Pipeline_(software)" rel="nofollow">pipeline model</a>. This is a good way to get separation of concerns, because you can idealy use every pipeline element (filter in directshow) independent of others.</p>
| 2 | 2016-06-13T11:29:09Z | [
"python",
"directshow",
"dataflow"
] |
write the output to a dynamically created file from the XML parser | 37,785,993 | <p>I want to call this python script from another python script file. The output generated needs to be written to a file that is passed as a parameter. How could I do that? I'm a beginner and would appreciate the minor details. Thanks.</p>
<p>PS: the problem is not writing to the file, but to pass the name of the outp... | 0 | 2016-06-13T09:19:53Z | 37,832,034 | <pre><code>You can import sys module and use it.
sys.argv[] holds the command line arguments passed to the python interpreter.
sys.argv[0] is your python file name.
sys.argv[1] is the path to the output file you want to write.
From the main method you can pass this sys.argv[1] to class MovieHandler.
Below is the sampl... | 1 | 2016-06-15T09:55:18Z | [
"python",
"sax"
] |
How to convert RA-Dec coordinates to galactic coordinates in python | 37,785,995 | <p>I was converting a pixel coordinate fits file to world coordinates in Python. The header shows that this fits file is in RA-Dec coordinate system . I want to convert this to galactic coordinates. Here is what I've tried.</p>
<pre><code>from astropy import coordinates as coord
from astropy import units as u
c=coord.... | -2 | 2016-06-13T09:20:00Z | 37,805,120 | <p>According to the <a href="http://docs.astropy.org/en/stable/coordinates/" rel="nofollow">Astropy documentation</a>, the syntax is:</p>
<pre><code>from astropy import units as u
from astropy.coordinates import SkyCoord
c = SkyCoord(ra=wx*u.degree, dec=wy*u.degree, frame='icrs')
c.galactic
</code></pre>
| 2 | 2016-06-14T07:05:20Z | [
"python",
"python-2.7",
"astropy",
"fits"
] |
How to show a 'processing' or 'in progress' view while pyramid is running a process? | 37,786,004 | <p>I've got a simple pyramid app up and running, most of the views are a fairly thin wrapper around an sqlite database, with forms thrown in to edit/add some information.</p>
<p>A couple of times a month a new chunk of data will need to be added to this system (by csv import). The data is saved in an SQL table (the wh... | 1 | 2016-06-13T09:20:22Z | 37,800,940 | <p>You're right, doing long calculations in a view function is generally frowned upon - I mean, if it's a typical website with random visitors who are able to hung a webserver thread for a minute then it's a recipe for a DoS vulnerability. But in some situations (internal website, few users, only admin has access to th... | 0 | 2016-06-13T23:58:34Z | [
"python",
"pyramid"
] |
How to show a 'processing' or 'in progress' view while pyramid is running a process? | 37,786,004 | <p>I've got a simple pyramid app up and running, most of the views are a fairly thin wrapper around an sqlite database, with forms thrown in to edit/add some information.</p>
<p>A couple of times a month a new chunk of data will need to be added to this system (by csv import). The data is saved in an SQL table (the wh... | 1 | 2016-06-13T09:20:22Z | 37,839,498 | <p>So is the long running process triggered by browser action? I.e., the user is uploading the CSV that gets processed and then the view is doing the processing right there? For short-ish running browser processes I've used a loading indicator via jQuery or javascript, basically popping a modal animated spinner or s... | 0 | 2016-06-15T15:19:44Z | [
"python",
"pyramid"
] |
Install and use OpenCV from source | 37,786,039 | <p>I have tried <a href="https://help.ubuntu.com/community/OpenCV" rel="nofollow">this</a> to install opencv. The terminal output after installing was:</p>
<pre><code>OpenCV 2.4.13 ready to be used
</code></pre>
<p>But when I try to import the module, it says the module doesn't exist. </p>
<p>When I tried:</p>
<pre... | 2 | 2016-06-13T09:22:10Z | 37,786,661 | <p>Since you are using <code>Python3</code>, You can only choose to build your own <code>cv2.pyd</code>. There is no pre-built version for you to download.</p>
<p>I found another <a href="http://docs.opencv.org/2.4/doc/tutorials/introduction/linux_install/linux_install.html" rel="nofollow"><strong>link</strong></a> of... | 0 | 2016-06-13T09:52:56Z | [
"python",
"opencv",
"ubuntu"
] |
How to plot and change the plotfunction at the same time? | 37,786,277 | <p>I want to plot points, and while doing so have a slidebar that I can adjust, which changes the function.
I found this example <a href="http://matplotlib.org/1.4.2/examles/widgets/slider_demo.html" rel="nofollow">here</a> that works. Now I want to plot points in a loop and change the function while the loop is still... | 1 | 2016-06-13T09:34:03Z | 37,787,521 | <p>Your code has a lot of misprints. A new point is plotted in the button because you do not set an axis where to draw but the button has current axis (it is last object).</p>
<p>You have to define plot function with axis argument like here:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matpl... | 0 | 2016-06-13T10:35:44Z | [
"python",
"matplotlib"
] |
How to delete row/rows from a qtableview in pyqt? | 37,786,299 | <p>I am using QStandardItemModel for my qtableview.</p>
<pre><code>import ui_my_viewlogs
import os
from PyQt4 import QtCore, QtGui
class my_viewlogs(QtGui.QDialog, ui_my_viewlogs.Ui_viewlogs):
def __init__(self):
super(my_viewlogs, self).__init__()
self.setupUi(self)
self.model = QtGui.QSt... | 1 | 2016-06-13T09:35:10Z | 37,852,048 | <p>the method model.removeRow(index.row()) removes the row selected.</p>
<pre><code>model = self.model
indices = self.tableView.selectionModel().selectedRows()
for index in sorted(indices):
model.removeRow(index.row())
</code></pre>
<p>in the indices variable we get the selected row, then we delete ... | 0 | 2016-06-16T07:03:23Z | [
"python",
"qt",
"pyqt",
"pyqt4",
"qtableview"
] |
Rotating image increases its size? | 37,786,313 | <p>I am trying to rotate some images whose width is more than height about the left-top corner, by 90 degrees. I have written this :</p>
<pre><code>from PIL import Image
import sys, csv, os, traceback, glob
import shutil, math
src_im = Image.open("Test.png")
print src_im.size[0] , ',' , src_im.size[1]
src_im = src_i... | 1 | 2016-06-13T09:35:33Z | 37,797,037 | <p>PNG compress the image by "filtering" each line, trying to predict the values for each pixel as a function of the "past" neighbours (previous row and/or column), and then compressing the prediction error by using ZLIB (Deflate).
The issue here seems to be this: the vertical image has almost vertical stripes; when sc... | 1 | 2016-06-13T18:46:06Z | [
"python",
"image",
"algorithm",
"png",
"image-compression"
] |
Trying to create a button per object instance | 37,786,477 | <p>I'm trying to make a list of buttons, each corresponding to an object in my database. However, when I press one of them, it is always the value of the last button generated which is sent back to the view:</p>
<pre><code> {% if segmenter %}
<form method="post">
{% csrf_token %}
&... | 0 | 2016-06-13T09:44:07Z | 37,786,726 | <p>Form items are distinguished by <code>name</code> but you're using the same <code>name</code> for your inputs. Besides using one form means you intend to send all the inputs when the inputs are differentiated.</p>
<p>You should do:</p>
<pre><code>{% if segmenter %}
{% csrf_token %}
<ul>
{% for segment in... | 0 | 2016-06-13T09:56:31Z | [
"python",
"django",
"python-3.x",
"django-1.9"
] |
How to define policies for Python application in Bluemix Autoscaling service? | 37,786,536 | <p>I noticed that the policy types depend on the target runtime. For example, for Java it is possible to define policies based on memory, throughput, response time... etc. The only possibility for Python is memory based policy. Is there any workaround for that? </p>
| 0 | 2016-06-13T09:47:05Z | 37,796,468 | <p>Bluemix Auto scaling service for Liberty for Java⢠applications, supports scaling rules for JVM Heap, Memory, and Throughput. Actually, Auto Scaling services on Bluemix works with IBM JVM. </p>
<p>For other types of runtimes, including Python runtime, there is only <a href="https://console.ng.bluemix.net/docs/ser... | 0 | 2016-06-13T18:09:35Z | [
"python",
"ibm-bluemix",
"autoscaling"
] |
Python external project script execution | 37,786,591 | <p>After many researches on the web, on many different topics, I wasn't able to find the solution answering my problem. </p>
<p>I am developing a tool (with graphic interface) allowing to process python scripts from different projects.
To not have any problem of dependences, I ask the user to target the project direc... | 3 | 2016-06-13T09:49:54Z | 37,790,550 | <p>To run an "external project script", install it e.g.: <code>pip install project</code> (run it in a virtualenv if you'd like) and then run the script as you would with any other executable:</p>
<pre><code>#!/usr/bin/env python
import subprocess
subprocess.check_call(['executable', 'arg 1', '2'])
</code></pre>
<p>... | 0 | 2016-06-13T13:01:36Z | [
"python",
"import",
"path",
"subprocess",
"sys"
] |
Python external project script execution | 37,786,591 | <p>After many researches on the web, on many different topics, I wasn't able to find the solution answering my problem. </p>
<p>I am developing a tool (with graphic interface) allowing to process python scripts from different projects.
To not have any problem of dependences, I ask the user to target the project direc... | 3 | 2016-06-13T09:49:54Z | 37,791,235 | <p>There are 3 problems I see that you have to fix:</p>
<ol>
<li>In order to import from module2, you need to turn that directory into a package by placing an empty <code>*__init__.py</code> file in it</li>
<li>When executing <code>test_script.py</code>, you need the full path to the file, not just file name</li>
<li>... | 0 | 2016-06-13T13:36:10Z | [
"python",
"import",
"path",
"subprocess",
"sys"
] |
Countdown with timer using python decorator | 37,786,642 | <pre><code>import time
def sleep_dec(function):
def wrapper(*args, **kwargs):
time.sleep(2)
return function(*args, **kwargs)
return wrapper
@sleep_dec
def countdown(n):
while n > 0:
print(n)
n -= 1
print(countdown(5))
</code></pre>
<p>Am trying to do a countdown function but with a sleep of... | -1 | 2016-06-13T09:51:51Z | 37,786,823 | <pre><code>def countdown(n):
while n > 0:
return n
n -= 1
</code></pre>
<p><code>n -= 1</code> will never be reached. In fact, the <code>while</code> loop will only iterate once and your function simply return <code>n</code>.</p>
<p>You want to use <code>yield</code> instead.</p>
<p>But, it st... | 1 | 2016-06-13T10:00:38Z | [
"python",
"decorator"
] |
Execute python code on uploaded files | 37,786,742 | <p>I have a django application where I upload 2 files and want to run a python script on them (proto2.py).</p>
<p>In my html code I added a button to execute a file but it didn't work :</p>
<pre><code><div>Relay 1:
<form action="{% url "nettoyage"%}" method="POST">
{% csrf_token %}
<... | 1 | 2016-06-13T09:57:19Z | 37,815,871 | <p>Problem lies here :</p>
<pre><code><form action="{% url "nettoyage"%}" method="POST">
</code></pre>
<p>Change it by :</p>
<pre><code><form action="{% url 'nettoyage'%}" method="POST">
</code></pre>
<p>The doubles quotes interfere with the <code>action</code> attribute, therefore closing it and leavin... | 0 | 2016-06-14T15:10:45Z | [
"python",
"html",
"django"
] |
Is an object created before assignment in python? | 37,786,750 | <p>How many objects are created when the below mentioned program is run in python 2.7.6?
*I'm aware that an error message occurs after the execution and I'm also aware that strings are immutable and that's the reason behind the error message. What I really want to know is to find whether an object 's' is being created ... | 1 | 2016-06-13T09:57:41Z | 37,786,944 | <p>It is. A call <code>string.__setitem__(1, "s")</code> will be made. So, the string object has to exist to make the call. The call is BTW not guaranteed to fail. <code>__setitem__</code> can be overridden and have nearly any behavior.</p>
| 2 | 2016-06-13T10:06:40Z | [
"python",
"object"
] |
Is an object created before assignment in python? | 37,786,750 | <p>How many objects are created when the below mentioned program is run in python 2.7.6?
*I'm aware that an error message occurs after the execution and I'm also aware that strings are immutable and that's the reason behind the error message. What I really want to know is to find whether an object 's' is being created ... | 1 | 2016-06-13T09:57:41Z | 37,787,603 | <p>The following interactive session suggests that the right-hand side of the assignment is evaluated first:</p>
<pre><code>>>> string[1] = raw_input('Enter value: ')
Enter value: s
Traceback (most recent call last):
File "<ipython-input-51-a1be6bbb7f5b>", line 1, in <module>
s[1] = raw_inp... | 0 | 2016-06-13T10:39:42Z | [
"python",
"object"
] |
Is an object created before assignment in python? | 37,786,750 | <p>How many objects are created when the below mentioned program is run in python 2.7.6?
*I'm aware that an error message occurs after the execution and I'm also aware that strings are immutable and that's the reason behind the error message. What I really want to know is to find whether an object 's' is being created ... | 1 | 2016-06-13T09:57:41Z | 37,787,768 | <p>In the code:</p>
<pre><code>string = "abcd"
</code></pre>
<p>An immutable <code>str</code> object will be created from <code>"abcd"</code>. The name <code>string</code> becomes a <em>reference</em> to that object, and the reference count is incremented. Note that there is a name in the standard library called <c... | 1 | 2016-06-13T10:47:20Z | [
"python",
"object"
] |
Python dict.get method apply some function on a key | 37,786,788 | <p>Modified to make it more understandable.</p>
<p>I am testing out the python's dict.get method and need some help on that.</p>
<p>What I am trying to do is that I have a dictionary with some values. I am trying to copy that one value to another dictionary after applying a method on the value of the dictionary. here... | 0 | 2016-06-13T09:59:29Z | 37,786,886 | <p>If the values are not empty, then:</p>
<pre><code>result_dict['name'] = test_dict.get('name', '').upper() or 'Default'
</code></pre>
| 0 | 2016-06-13T10:03:33Z | [
"python",
"dictionary"
] |
Python dict.get method apply some function on a key | 37,786,788 | <p>Modified to make it more understandable.</p>
<p>I am testing out the python's dict.get method and need some help on that.</p>
<p>What I am trying to do is that I have a dictionary with some values. I am trying to copy that one value to another dictionary after applying a method on the value of the dictionary. here... | 0 | 2016-06-13T09:59:29Z | 37,786,928 | <p>Try something like this</p>
<pre><code>test_dict = defaultdict(lambda: 'default')
test_dict.get('name').capitalize()
</code></pre>
<p>or</p>
<pre><code>test_dict = {}
test_dict.setfdefault('default')
test_dict.get('name').capitalize()
</code></pre>
| 0 | 2016-06-13T10:06:01Z | [
"python",
"dictionary"
] |
Pip install does not fetch the latest version | 37,786,871 | <p>I want to install the latest <code>django-froala-editor</code> version.</p>
<p>But <code>pip install</code> keeps installing the <code>django-froala-editor</code> version 2.0.1.</p>
<h3>Steps to reproduce the problem.</h3>
<p>(using virtualenvwrapper to ease the test)</p>
<pre><code>mktmpenv
pip search froala
pi... | 0 | 2016-06-13T10:02:49Z | 37,787,000 | <p>Install directly from <code>git</code> if you can't get the latest version from pypi:</p>
<pre><code>pip install git+https://github.com/froala/django-froala-editor
</code></pre>
<p>This can be included in your requirements.txt as <code>git+https://github.com/froala/django-froala-editor</code></p>
<p>Generally, </... | 1 | 2016-06-13T10:09:15Z | [
"python",
"django",
"pip",
"froala"
] |
Flask dev server in threaded mode still waits for first thread to finish | 37,786,989 | <p>I have a Flask view that sleeps while generating a response to simulate a long request for a web service. I am running the dev server with <code>threaded=True</code>. When opening three tabs in the browser the second tab doesn't show any updates until the first thread has finished. But the third tab <em>does</em> ... | 0 | 2016-06-13T10:08:52Z | 37,791,268 | <p>The problem seems to be the browser. When I test with Google chrome I get the behaviour described in the question: the second thread doesn't start before the first one has finished. </p>
<p>Testing with:</p>
<pre><code>wget -qO- http://localhost:5002/wait
</code></pre>
<p>I experience the correct response. Each c... | 0 | 2016-06-13T13:37:49Z | [
"python",
"flask",
"werkzeug"
] |
Python xpath to extract the first part html from html which has more than three same div | 37,787,093 | <p>The python xpath is used to extract the div html from the html. For example, as shown the following html.</p>
<pre><code> <html>
<body>
<div class="main">
<div class="headline">
<h2>123</h2>
</div>
<div class="headline">
<h2>abc<... | 0 | 2016-06-13T10:14:30Z | 37,787,281 | <p>If you want to get this part:</p>
<pre><code><div class="headline">
<h2>123</h2>
</div>
</code></pre>
<p>Use this Xpath:</p>
<pre><code>(//div[contains(@class, "headline")])[1]
</code></pre>
<p>Your xpath returned a List of matching elements, the <code>()[1]</code> part returns the first ... | 0 | 2016-06-13T10:24:42Z | [
"python",
"html",
"xpath"
] |
How to animate the background color of a QPushButton in qt? | 37,787,101 | <p>I did everything [till what i know] to animate the background color of a button but i can't do it. Here are one of my tries:</p>
<pre><code> # I set the style of the button by setstylesheet()
animation = QPropertyAnimation(btn, "style",btn)
animation.setDuration(1000)
animation.setStartValue(QStyle("... | 0 | 2016-06-13T10:15:02Z | 37,788,066 | <p>C++, Qt5, buy may work in Qt4</p>
<pre><code>QGraphicsColorizeEffect *eEffect= new QGraphicsColorizeEffect(btn);
btn->setGraphicsEffect(eEffect);
QPropertyAnimation *paAnimation = new QPropertyAnimation(eEffect,"color");
paAnimation->setStartValue(QColor(Qt::blue));
paAnimation->setEndValue(QColor(Qt::red)... | 0 | 2016-06-13T11:01:06Z | [
"python",
"c++",
"qt",
"animation",
"pyqt4"
] |
How to Reduce Running (for loop), Python | 37,787,200 | <ol>
<li>Following Code is taking too much running time (more than 5min)</li>
<li><p>Is there any good ways to reduce running time. </p>
<pre><code>data.head() # more than 10 year data, Total iteration is around 4,500,000
Open High Low Close Volume Adj Close \
Date ... | -4 | 2016-06-13T10:19:45Z | 37,801,955 | <p>Rather than iterating over the 4.5MM rows in your data, use pandas' built-in indexing features. I've re-written the loop at the end of your code as below:</p>
<pre><code>data.loc[data.Close/data.Close.shift(1) <= Cut_Pct,'Cut_Off'] = 1
</code></pre>
<p>.loc locates rows that meet the criteria in the first argum... | 0 | 2016-06-14T02:16:58Z | [
"python",
"loops",
"pandas",
"time"
] |
Building a Python C++ extension | 37,787,206 | <p>I'd like to build a C++ extension for Python. I took a simple C file from a tutorial and wrote the setup.py file. But when I run the command:</p>
<pre><code>python setup.py build_ext --inplace
</code></pre>
<p>I get the following error:</p>
<pre><code>error: Unable to find vcvarsall.bat
</code></pre>
<p>This fil... | 0 | 2016-06-13T10:20:02Z | 38,307,047 | <p>Make sure you are using the latest version of python27
Download Microsoft visual compiler for python 2.7</p>
<p>In your setup script, write <strong><em>from setuptools import setup, Extension</em></strong> instead of <strong><em>from distutils.core import setup, Extension</em></strong></p>
<p>refer to
<a href="ht... | 0 | 2016-07-11T12:33:57Z | [
"python",
"c++"
] |
Python wb writes to memory address instead of path | 37,787,288 | <p>For some reason this codes saves the file to a memory address instead of the specified path Oo, anyone any ideas on how to solve this :)</p>
<pre><code>def save_csv(self, path, trend_name):
fileName = "~/Videos" + "data" + ".csv"
with open(fileName, mode='wb') as f:
f.write(self.decode_data.encode('... | -1 | 2016-06-13T10:25:02Z | 37,787,415 | <p>As it was mentioned in the comments, you should use the path directly like this:</p>
<pre><code>fileName = "home/<username>/Videos/" + "data" + ".csv"
</code></pre>
<p>as only bash expands <code>~</code> to full <code>home/<username></code> path.</p>
<p>Also, it uses memory, but then you don't know wh... | 0 | 2016-06-13T10:31:03Z | [
"python"
] |
Python wb writes to memory address instead of path | 37,787,288 | <p>For some reason this codes saves the file to a memory address instead of the specified path Oo, anyone any ideas on how to solve this :)</p>
<pre><code>def save_csv(self, path, trend_name):
fileName = "~/Videos" + "data" + ".csv"
with open(fileName, mode='wb') as f:
f.write(self.decode_data.encode('... | -1 | 2016-06-13T10:25:02Z | 37,787,506 | <p>It is the shell that converts <code>~</code> to the home path. Python does, however, have its own function for that, <a href="https://docs.python.org/3/library/os.path.html#os.path.expanduser" rel="nofollow"><code>os.path.expanduser()</code></a>:</p>
<pre><code>from os.path import expanduser
def save_csv(self, pa... | 0 | 2016-06-13T10:35:01Z | [
"python"
] |
How to merge two tables and transpose rows to columns | 37,787,289 | <p>I have these two tables:</p>
<p><strong>T1</strong></p>
<pre><code>id x y
8 42 1.9
9 30 1.9
</code></pre>
<p><strong>T2</strong></p>
<pre><code>id signal
8 55
8 56
8 59
9 57
9 58
9 60
</code></pre>
<p>The goal is to get the new table T3:</p>
<pre><code>id x y ... | 2 | 2016-06-13T10:25:04Z | 37,787,602 | <p><strong>UPDATE:</strong></p>
<p>as @Jeff has written in his comment @ubuntu's solution should be faster and more idiomatic compared to mine:</p>
<pre><code>In [40]: T1.merge(
....: T2.pivot_table(index='id',
....: values='signal',
....: columns='s' + T2.groupby(['... | 4 | 2016-06-13T10:39:37Z | [
"python",
"pandas",
"dataframe"
] |
How to merge two tables and transpose rows to columns | 37,787,289 | <p>I have these two tables:</p>
<p><strong>T1</strong></p>
<pre><code>id x y
8 42 1.9
9 30 1.9
</code></pre>
<p><strong>T2</strong></p>
<pre><code>id signal
8 55
8 56
8 59
9 57
9 58
9 60
</code></pre>
<p>The goal is to get the new table T3:</p>
<pre><code>id x y ... | 2 | 2016-06-13T10:25:04Z | 37,787,946 | <p>Here is my way of using <code>groupby</code> and <code>unstack</code>:</p>
<pre><code>df = df1.merge(df2.groupby('id')['signal'].apply(lambda x: x.reset_index(drop=True)).unstack().reset_index())
df
Out[63]:
id x y 0 1 2
0 8 42 1.9 55 56 59
1 9 30 1.9 57 58 60
</code></pre>
<p>If I se... | 2 | 2016-06-13T10:55:10Z | [
"python",
"pandas",
"dataframe"
] |
How to merge two tables and transpose rows to columns | 37,787,289 | <p>I have these two tables:</p>
<p><strong>T1</strong></p>
<pre><code>id x y
8 42 1.9
9 30 1.9
</code></pre>
<p><strong>T2</strong></p>
<pre><code>id signal
8 55
8 56
8 59
9 57
9 58
9 60
</code></pre>
<p>The goal is to get the new table T3:</p>
<pre><code>id x y ... | 2 | 2016-06-13T10:25:04Z | 37,788,957 | <p>Yet another way is to use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">groupby</a>/<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow">cumcount</a>/<a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.... | 2 | 2016-06-13T11:43:48Z | [
"python",
"pandas",
"dataframe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.