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
TypeError: not all arguments converted during string formatting postgres
38,553,237
<p>I try to add data to the database (use psycopg2.connect): </p> <pre><code>cand = Candidate('test', datetime.now(), 'test@test.t', '123123', "21", 'test', 'test', 'test', datetime.now(), "1", "1", 'test', 'M', "18", "2", "2") db.addCandidate(cand) </code></pre> <p>my function add:</p> <pre><code>def addCandidate(s...
0
2016-07-24T14:40:01Z
38,554,448
<p>I solved my problem, I wrote 15 '%s', instead of 16</p>
0
2016-07-24T16:52:24Z
[ "python", "postgresql", "psycopg2" ]
Python numpy: Matrix multiplication giving wrong result
38,553,238
<p>I'm using matrices in numpy python. I have a matrix A and I then I calculate its inverse. Now I multiply A with its inverse, and I'm not getting the identity matrix. Can anyone point out what's wrong here?</p> <pre><code>A = matrix([ [4, 3], [3, 2] ]); print (A.I) # prints [[-2 3], ...
1
2016-07-24T14:40:04Z
38,553,285
<p>You are using dot on the matrix and the transposed matrix (not the inverse) ... </p> <pre><code>In [16]: np.dot(A.I, A) Out[16]: matrix([[ 1., 0.], [ 0., 1.]]) </code></pre> <p>With the transposed you have the result you showed:</p> <pre><code>In [17]: np.dot(A.T, A) Out[17]: matrix([[25, 18], [...
4
2016-07-24T14:45:11Z
[ "python", "numpy", "matrix" ]
Python numpy: Matrix multiplication giving wrong result
38,553,238
<p>I'm using matrices in numpy python. I have a matrix A and I then I calculate its inverse. Now I multiply A with its inverse, and I'm not getting the identity matrix. Can anyone point out what's wrong here?</p> <pre><code>A = matrix([ [4, 3], [3, 2] ]); print (A.I) # prints [[-2 3], ...
1
2016-07-24T14:40:04Z
38,553,771
<p>Here is another method: </p> <p><code>I</code> works only on <code>matrix</code></p> <p>you can use <code>np.linalg.inv(x)</code> for <code>inverse</code></p> <pre><code>In [11]: import numpy as np In [12]: A = np.array([[4, 3], [3, 2]]) In [13]: B = np.linalg.inv(A) In [14]: A.dot(B) Out[14]: array([[ 1., 0...
1
2016-07-24T15:37:40Z
[ "python", "numpy", "matrix" ]
how to scrape multipage website with python and export data into .csv file?
38,553,317
<p>I would like to scrape the following website using python and need to export scraped data into a CSV file:</p> <p><a href="http://www.swisswine.ch/en/producer?search=&amp;&amp;" rel="nofollow">http://www.swisswine.ch/en/producer?search=&amp;&amp;</a></p> <p>This website consist of 154 pages to relevant search. I n...
0
2016-07-24T14:48:41Z
38,553,355
<p>You should put your HTML parsing code to <em>under the loop</em> as well. And you are not incrementing the <code>i</code> variable correctly (thanks @MattDMo):</p> <pre><code>import csv import requests from bs4 import BeautifulSoup i = 0 while i &lt; 153: url = ("http://www.swisswine.ch/en/producer?sea...
1
2016-07-24T14:53:26Z
[ "python", "csv", "beautifulsoup" ]
Import across modules in Google App Engine
38,553,318
<p>I have a Python Google App Engine project structured as follows:</p> <pre><code>app/ handlers/ register_user.py models/ user.py </code></pre> <p>The <code>user.py</code> file contains a class <code>User(ndb.Model)</code>.</p> <p>I'm trying to access the <code>User</code> class from <code>r...
0
2016-07-24T14:48:58Z
38,554,298
<p>The way I approached this was using <a href="https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27#installing_a_library" rel="nofollow">the GAE 3rd party lib vendoring technique</a>:</p> <ul> <li>created <code>appengine_config.py</code>:</li> </ul> <p>content:</p> <pre><code>from google.a...
0
2016-07-24T16:34:56Z
[ "python", "google-app-engine", "python-import", "google-app-engine-python" ]
Import across modules in Google App Engine
38,553,318
<p>I have a Python Google App Engine project structured as follows:</p> <pre><code>app/ handlers/ register_user.py models/ user.py </code></pre> <p>The <code>user.py</code> file contains a class <code>User(ndb.Model)</code>.</p> <p>I'm trying to access the <code>User</code> class from <code>r...
0
2016-07-24T14:48:58Z
38,557,611
<p>I think Dan is on the right track, however there is no need to vendor your own code. The vendoring system is to manage third-party dependencies with pip and should be totally unnecessary for your use case, and vendoring your own code would violate the conventions.</p> <p>Based on what you've told us, you should be ...
1
2016-07-24T22:50:20Z
[ "python", "google-app-engine", "python-import", "google-app-engine-python" ]
Python - Checking whether any of multiple conditions are true
38,553,410
<p>I am trying to modify a list in place to remove entries where the file extension does not match. I got this working by writing multiple 'or' conditions</p> <pre><code>from os import listdir image_extensions = ['jpg','.png'] files = listdir('/home') files = [x for x in files if '.jpg' in x or '.png' in x] print fi...
0
2016-07-24T15:00:22Z
38,553,427
<p>This should do:</p> <pre><code>files = [x for x in files if any(s in x for s in image_extensions)] # |&lt;--&gt;| </code></pre> <p>Check if <em>any</em> of the extensions is contained in the file name <code>x</code></p>
3
2016-07-24T15:02:11Z
[ "python", "list", "list-comprehension", "any" ]
Python - Checking whether any of multiple conditions are true
38,553,410
<p>I am trying to modify a list in place to remove entries where the file extension does not match. I got this working by writing multiple 'or' conditions</p> <pre><code>from os import listdir image_extensions = ['jpg','.png'] files = listdir('/home') files = [x for x in files if '.jpg' in x or '.png' in x] print fi...
0
2016-07-24T15:00:22Z
38,554,541
<p>Alternative solution to that:</p> <pre><code>&gt;&gt;&gt; filter(lambda f: filter(f.endswith, image_extensions), files) </code></pre> <p>Time profiling this expression compared to the previous answer, reveals that there is a bit of improvement on the previous one:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt...
0
2016-07-24T17:02:57Z
[ "python", "list", "list-comprehension", "any" ]
How should i decode this data/these strings
38,553,545
<p>I am currently trying to work through an OLD python CTF challenge, the script of the server is provided, and the idea is to send the correct data to this server,</p> <pre><code>#!/usr/bin/env python3 # from dis import dis import socketserver import types class RequestHandler(socketserver.BaseRequestHandler): ...
2
2016-07-24T15:13:55Z
38,554,453
<p>Start an interactive Python 3 session. If you use the plain python interpreter, type</p> <pre><code>import types help(types.CodeType) </code></pre> <p>If you're using IPython, you might instead write</p> <pre><code>import types types.CodeType? </code></pre> <p>You'll learn that <code>types.CodeType</code> is the...
3
2016-07-24T16:52:45Z
[ "python", "string", "decompiling" ]
How should i decode this data/these strings
38,553,545
<p>I am currently trying to work through an OLD python CTF challenge, the script of the server is provided, and the idea is to send the correct data to this server,</p> <pre><code>#!/usr/bin/env python3 # from dis import dis import socketserver import types class RequestHandler(socketserver.BaseRequestHandler): ...
2
2016-07-24T15:13:55Z
38,600,702
<p>Riffing off of das-g's answer, this code works. Sorta. </p> <pre><code>import uncompyle6 import types code_obj = types.CodeType( 1, 0, 5, 32, 67, b'd\x01\x00d\x02\x00d\x03\x00d\x04\x00d\x05\x00d\x06\x00d\x05\x00d\x07' b'\x00d\x08\x00d\x05\x00d\t\x00d\x08\x00d\n\x00d\x01\x00d\x07\x00d\x07' b'...
1
2016-07-26T22:11:01Z
[ "python", "string", "decompiling" ]
Is O(1) complexity of len(...) guaranteed by some PEP for built-in sequence types?
38,553,561
<p>Many questions about cost of <code>len(...)</code> are answered but I haven't found any link to Python documentation.</p> <p>Is it by standard (documented in some PEP) or just way how it's currently implemented in most Python implementations?</p>
3
2016-07-24T15:16:04Z
38,553,638
<p>Documentation about time complexity for certain built-in python objects is <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">here</a>.</p> <p>The <code>len()</code> function in python just calls the <code>__len__</code> method in your class. So if you built a custom class</p> <pre><code>class Sl...
2
2016-07-24T15:24:10Z
[ "python" ]
Unable to upgrade ovirt-3.6 to ovirt-4.0 in CentOS 6.8
38,553,604
<p>Trying to upgrade using a command <code>yum update "ovirt-engine-setup*"</code> detailed link is <a href="http://www.ovirt.org/release/4.0.0/" rel="nofollow">here.</a></p> <p><code>Error: Package: ovirt-engine-lib-4.0.1.1-1.el7.centos.noarch (ovirt-4.0) Requires: python(abi) = 2.7 Installed: p...
0
2016-07-24T15:21:02Z
38,568,976
<p>from Ovirt's website:</p> <blockquote> <p>oVirt 4.0 is intended for production use and is available for the following platforms:</p> <ul> <li>Fedora 23 </li> <li>Red Hat Enterprise Linux 7.2 or later</li> <li>CentOS 7.2 or later</li> <li>Scientific Linux 7.2 or later</li> </ul> </blockquote> <...
0
2016-07-25T13:23:44Z
[ "python", "linux", "python-2.7", "centos", "dependencies" ]
Unable to upgrade ovirt-3.6 to ovirt-4.0 in CentOS 6.8
38,553,604
<p>Trying to upgrade using a command <code>yum update "ovirt-engine-setup*"</code> detailed link is <a href="http://www.ovirt.org/release/4.0.0/" rel="nofollow">here.</a></p> <p><code>Error: Package: ovirt-engine-lib-4.0.1.1-1.el7.centos.noarch (ovirt-4.0) Requires: python(abi) = 2.7 Installed: p...
0
2016-07-24T15:21:02Z
39,077,321
<p>please follow <a href="http://www.ovirt.org/documentation/migration-engine-3.6-to-4.0/" rel="nofollow">http://www.ovirt.org/documentation/migration-engine-3.6-to-4.0/</a> for upgrading from 3.6 el6 to 4.0 el7.</p> <p>If you're on hosted engine also read <a href="https://www.ovirt.org/documentation/how-to/hosted-eng...
0
2016-08-22T10:36:03Z
[ "python", "linux", "python-2.7", "centos", "dependencies" ]
Convert string to json data
38,553,610
<p>I am converting string to json format as below</p> <pre><code>data = """ S3F4 accept reply: true """ </code></pre> <p>And json data is <code>[{"header":{"stream":3,"function":4,"reply":True}}]</code></p> <p>I can use regex and search pattern <code>S3F4</code> and add to dict.</p> <p>But is there any better way...
-1
2016-07-24T15:21:41Z
38,553,730
<p>Not sure about all the variations of the input string and what is the scope of characters <code>stream</code>, <code>function</code> and <code>reply</code> can have, but here is what you can start with:</p> <pre><code>S(?P&lt;stream&gt;\d)F(?P&lt;function&gt;\d)\naccept reply: (?P&lt;reply&gt;\w+) </code></pre> <p...
1
2016-07-24T15:33:41Z
[ "python", "json", "regex" ]
How can I stop opencv from making calls to qDebug?
38,553,902
<p>I've just started using OpenCv 3.1 and have encountered the following annoying behavior. Whenever I make an initial call to <code>imshow</code> (actually <code>cv2.imshow</code>, since I'm using the Python interface), I get this output to my screen:</p> <pre><code>init done opengl support available </code></pre> <...
1
2016-07-24T15:52:16Z
38,553,931
<p><code>qDebug</code> is a preprocessor-controlled, but it has its own special macro, <code>QT_NO_DEBUG_OUTPUT</code>. If you add that to your Release build defines, it will be removed.</p>
1
2016-07-24T15:55:11Z
[ "python", "c++", "opencv" ]
python dictionary key error excel
38,553,919
<p>I'm sure I'm doing something rather silly, but I'm just not seeing it!</p> <p>Here's the code I'm trying to run:</p> <pre><code>import pandas as pd geo_dic = pd.read_excel('cityzip.xlsx', index_col=0).to_dict() print geo_dic[' Longitude']['601'][0] </code></pre> <p>cityzip.xlsx contains these rows (and many more...
1
2016-07-24T15:54:05Z
38,554,922
<p><a href="http://i.stack.imgur.com/BsAEE.png" rel="nofollow"><img src="http://i.stack.imgur.com/BsAEE.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/1x93t.png" rel="nofollow"><img src="http://i.stack.imgur.com/1x93t.png" alt="enter image description here"></a></p> <p>Just try ...
0
2016-07-24T17:43:02Z
[ "python", "pandas", "geopy" ]
How to recall a method without parameters using Threading getting AssertionError
38,553,948
<p>So I have some methods that compile and work on the main thread, but I wanted to run a collection of methods at a certain time in the future after they successful run. I looked into importing the threading, time, and datetime classes. The next_call_auto variable in Thread() is an integer that waits for ~3 hours wort...
-1
2016-07-24T15:57:36Z
38,556,189
<p>According to the <a href="https://docs.python.org/2/library/threading.html#threading.Thread" rel="nofollow">docs for the Threading class</a>, this call:</p> <pre><code>Thread(next_call_auto, target=auto_follow_others_thread) </code></pre> <p>is the same as:</p> <pre><code>Thread(group = next_call_auto, target = a...
0
2016-07-24T19:59:36Z
[ "python", "multithreading" ]
Python numpy - Giving identity matrix with non-diognal elements non-zero
38,553,967
<p>I'm using python numpy for matrix operations. Calculation of identity matrix is giving unexpected results - Not getting the standard identity matrix.</p> <pre><code>R0 = matrix([ [0.02187598, 0.98329681, -0.18068986], [0.99856708, -0.01266115, 0.05199501], [0.04883878, -0.18156839, -0.9821648] ]); pr...
0
2016-07-24T15:59:25Z
38,554,118
<p>The problem is that even though mathematically the result of dot(R, R.I) is equal to I, due to numerical errors in the floating point numbers, numpy returns something very close to I, but not exactly equal to it.</p> <p>The values with e-17 are very close approximations of 0.</p> <p>If you want to generate the exa...
2
2016-07-24T16:16:20Z
[ "python", "numpy", "matrix", "linear-algebra", "mat" ]
Adding certain elements of list
38,553,983
<p>I want to add elements in a list every ten elements. For example:</p> <pre><code>a = [5, 31, 16, 31, 19, 5, 25, 34, 8, 13, 17, 17, 43, 9, 29, 41, 8, 24, 48, 1, 28, 20, 37, 40, 32, 35, 9, 36, 17, 46, 10, 30, 49, 28, 2, 3, 8, 11, 36, 20, 7, 24, 29, 15, 0, 4, 35, 11, 42, 7, 28, 40, 31, 45, 6, 45, 15, 27, 39, 6] </cod...
0
2016-07-24T16:00:48Z
38,554,019
<p>Use <code>map</code> on an iterator of the list:</p> <pre><code>&gt;&gt;&gt; it = iter(a) &gt;&gt;&gt; map(lambda *x: sum(x), *(it,)*10) [187, 237, 300, 197, 174, 282] </code></pre> <p>Create an iterator for your list. Pass the items to <code>map</code> in 10s using the iterator and use <code>map</code> to return ...
1
2016-07-24T16:04:59Z
[ "python", "list", "sum" ]
Adding certain elements of list
38,553,983
<p>I want to add elements in a list every ten elements. For example:</p> <pre><code>a = [5, 31, 16, 31, 19, 5, 25, 34, 8, 13, 17, 17, 43, 9, 29, 41, 8, 24, 48, 1, 28, 20, 37, 40, 32, 35, 9, 36, 17, 46, 10, 30, 49, 28, 2, 3, 8, 11, 36, 20, 7, 24, 29, 15, 0, 4, 35, 11, 42, 7, 28, 40, 31, 45, 6, 45, 15, 27, 39, 6] </cod...
0
2016-07-24T16:00:48Z
38,554,052
<p>You can use nested comprehensions with a list iterator:</p> <pre><code>i= iter(a) s= [sum(next(i) for _ in range(10)) for _ in range(len(a)//10)] print s </code></pre> <p>Note that this will silently ignore any leftover values:</p> <pre><code>a= [1]*11 #&lt;- list has 11 elements i= iter(a) s= [sum(next(i) for _ ...
0
2016-07-24T16:08:18Z
[ "python", "list", "sum" ]
Adding certain elements of list
38,553,983
<p>I want to add elements in a list every ten elements. For example:</p> <pre><code>a = [5, 31, 16, 31, 19, 5, 25, 34, 8, 13, 17, 17, 43, 9, 29, 41, 8, 24, 48, 1, 28, 20, 37, 40, 32, 35, 9, 36, 17, 46, 10, 30, 49, 28, 2, 3, 8, 11, 36, 20, 7, 24, 29, 15, 0, 4, 35, 11, 42, 7, 28, 40, 31, 45, 6, 45, 15, 27, 39, 6] </cod...
0
2016-07-24T16:00:48Z
38,554,054
<pre><code>In [25]: map(sum, zip(*[iter(a)]*10)) Out[25]: [187, 237, 300, 197, 174, 282] </code></pre>
2
2016-07-24T16:08:39Z
[ "python", "list", "sum" ]
Adding certain elements of list
38,553,983
<p>I want to add elements in a list every ten elements. For example:</p> <pre><code>a = [5, 31, 16, 31, 19, 5, 25, 34, 8, 13, 17, 17, 43, 9, 29, 41, 8, 24, 48, 1, 28, 20, 37, 40, 32, 35, 9, 36, 17, 46, 10, 30, 49, 28, 2, 3, 8, 11, 36, 20, 7, 24, 29, 15, 0, 4, 35, 11, 42, 7, 28, 40, 31, 45, 6, 45, 15, 27, 39, 6] </cod...
0
2016-07-24T16:00:48Z
38,554,680
<p>How about list comprehension, like this one:</p> <pre><code>&gt;&gt;&gt; step = 10 &gt;&gt;&gt; &gt;&gt;&gt; [sum(a[x:x+step]) for x in range(0, len(a), step)] [187, 237, 300, 197, 174, 282] </code></pre>
0
2016-07-24T17:18:45Z
[ "python", "list", "sum" ]
Seaborn - Logarithmic scaling of the "z axis" in a bivariate KDE plot?
38,553,998
<p>I am currently plotting some data using Seaborn's <code>JointPlot</code>:</p> <pre><code>pitch = pd.Series(angles[:, 0], name="Pitch") roll = pd.Series(angles[:, 1], name="Roll") plot = sns.jointplot(pitch, roll, kind="kde", space=0.3) </code></pre> <p><a href="http://i.stack.imgur.com/h3Zww.png" rel="nofollow"><i...
1
2016-07-24T16:02:58Z
38,557,487
<p>I guess you want to make log scale of y-axis for x auxiliary plot and make log scale of x-axis for y auxiliary plot? If I am right look at this example:</p> <pre><code>import matplotlib.pylab as plt import seaborn as sns import numpy as np iris = sns.load_dataset("iris") plot = sns.jointplot("sepal_width", "petal_...
0
2016-07-24T22:33:23Z
[ "python", "matplotlib", "seaborn" ]
Installing modules in Python 3.5.2 error
38,554,020
<p>Sorry if I will sound really dumb but I get an error while trying to install python 3.5.2 modules using pip. The whole error screen is the following: </p> <p><a href="http://i.stack.imgur.com/NZCgX.png" rel="nofollow"><img src="http://i.stack.imgur.com/NZCgX.png" alt="The error from the command line"></a></p> <p>T...
0
2016-07-24T16:05:04Z
38,554,092
<p>Do you have administrator privileges? Looks like you don't have privileges to access files</p>
1
2016-07-24T16:12:03Z
[ "python", "pip" ]
Python logging message not getting output as expected in simplest scenario
38,554,040
<p>I am not getting any output from <code>logging.debug</code> in the simplest possible situation. (I do get output from <code>logger.warn</code>.)</p> <pre><code>import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.warn('Logger is warning') logger.debug('Logger is debugging') print(logger...
0
2016-07-24T16:06:42Z
38,563,489
<p>The reason is that you haven't specified a handler. On Python 3.5, an internal <a href="https://docs.python.org/3.2/library/logging.html#logging.lastResort" rel="nofollow">"handler of last resort"</a> is used when no handler is specified by you, but that internal handler has a level of <code>WARNING</code> and so wo...
0
2016-07-25T08:58:45Z
[ "python", "logging" ]
Can't select a row from a pandas dataframe, read from a csv
38,554,122
<p>I have a csv with some data that I'm reading into pandas:</p> <pre><code>filename = sys.argv[1] data = pd.read_csv(filename, sep=';', header=None) xy = data print str(xy) </code></pre> <p>Result:</p> <pre><code> 0 1 0 label data 1 x ...
0
2016-07-24T16:16:27Z
38,555,522
<p>Try this: </p> <pre><code>filename = sys.argv[1] df = pd.read_csv(filename, sep=';') xy = df </code></pre> <p>Do not name your dataframe "data"; One of your column headers is named <code>data!</code>. Then: for i, row in df.iterrows(): a = str(df['label'][i]) b = str(df['data'][i]) print (...
1
2016-07-24T18:44:07Z
[ "python", "csv", "pandas", "dataframe", "row" ]
Limiting execution time of embedded Python
38,554,126
<p>If I embed the Python interpreter in a C or C++ program, as in <a href="https://docs.python.org/2.7/extending/embedding.html#pure-embedding">this example</a>, is there any way to limit how long the interpreter runs for? Is there anything to stop the Python code from entering an infinite loop and thus preventing <cod...
10
2016-07-24T16:16:49Z
38,598,920
<p>As you can see in <a href="https://docs.python.org/3/c-api/object.html#c.PyObject_CallObject">the docs</a>, <code>PyObject_CallObject</code> has no mechanism for limiting how long the function runs. There is also no Python C API function that I am aware of that allows you to pause or kill a thread used by the inter...
6
2016-07-26T20:03:13Z
[ "python", "infinite-loop", "sandbox", "python-embedding" ]
Limiting execution time of embedded Python
38,554,126
<p>If I embed the Python interpreter in a C or C++ program, as in <a href="https://docs.python.org/2.7/extending/embedding.html#pure-embedding">this example</a>, is there any way to limit how long the interpreter runs for? Is there anything to stop the Python code from entering an infinite loop and thus preventing <cod...
10
2016-07-24T16:16:49Z
38,689,940
<p>If You need control lag and jitter in some realtime system, embed "StacklessPython" - Python with support co-routines. Used in "Twisted Web Server".</p>
1
2016-08-01T01:42:45Z
[ "python", "infinite-loop", "sandbox", "python-embedding" ]
Scraping excel from website using python with _doPostBack link url hidden
38,554,235
<p>For last few days I am trying to scrap the following website (link pasted below) which has a few excels and pdfs available in a table. I am able to do it for the home page successfully. There are total 59 pages from which these excels/ pdfs have to be scrapped. In most of the websites I have seen till now there is a...
1
2016-07-24T16:28:36Z
38,557,881
<p>For aspx sites, you need to look for things like <code>__EVENTTARGET</code>, <code>__EVENTVALIDATION</code> etc.. and post those parameters with each request, this will get all the pages and using <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a> with <em>bs4</em>:</p> <pre><code>imp...
0
2016-07-24T23:30:10Z
[ "python", "web-scraping", "dopostback" ]
How do I plot observations each with multiple values in python?
38,554,287
<p>I have data for each individual participant from a survey. Each individual has a vector of data for example :</p> <pre><code>#[a,b,c] [1,2,5] # 1 participant ... ... ... [1,3,4] </code></pre> <p>Instead of having that kind of data, I have the data column wise. Example :</p> <pre><code>a = [1...1] # has n values e...
1
2016-07-24T16:33:33Z
38,554,334
<p>Use each list as <code>xaxis</code>, <code>yaxis</code>, and <code>zaxis</code> data. This is especially useful when you know the lists are the same length, and each column represents one object. For example, <code>(a[0], b[0], c[0])</code> represent a trait of the same object. The <code>a-</code>, <code>b-</code> a...
4
2016-07-24T16:38:40Z
[ "python", "matplotlib", "plot" ]
How to return the original data frame with only the rows selected using value_counts()
38,554,381
<p>the original dataframe:</p> <pre><code>from pandas import Series, DataFrame import pandas as pd %pylab inline df=pd.read_csv('NYC_Restaurants.csv', dtype=unicode) </code></pre> <p><img src="http://i.stack.imgur.com/Be5Gg.png" alt="original df"></p> <p>I used a mask to isolate the desired rows (those that occur o...
0
2016-07-24T16:44:14Z
38,557,643
<p>Instead of using value_counts(); I used groupby which provided exactly what I was looking for.</p> <pre><code>mask = df.groupby("DBA").filter(lambda x: len(x) == 1) </code></pre>
0
2016-07-24T22:54:58Z
[ "python", "pandas" ]
Function appears to run faster each time it is called within a for loop
38,554,495
<p>I have written a very crude hill-climb/greedy algorithm for solving the travelling salesman problem. The aim was to use this as a benchmark and continually improve running time and optimise the solution at the same time. </p> <p><strong>EDIT: On the suggestion of Stefan Pochmann, this appears to be related to hardw...
0
2016-07-24T16:56:56Z
38,562,303
<p>This issue is related to OS/hardware allocation of resources to the CPU, not CPU branch prediction. On Windows 7, running another script concurrently that simply does:</p> <pre><code>for x in range(10): a = sum(xrange(10**8)) </code></pre> <p>will cause massive acceleration in the execution of the script in th...
1
2016-07-25T07:49:44Z
[ "python", "algorithm" ]
Beautfil Soup Error with simple script
38,554,550
<p>I am running Beautiful Soup 4.5 with Python 3.4 on Windows 7. Here is my script:</p> <pre><code>from bs4 import BeautifulSoup import urllib3 http = urllib3.PoolManager() url = 'https://scholar.google.com' response = http.request('GET', url) html2 = response.read() soup = BeautifulSoup([html2]) print (type(soup)...
-2
2016-07-24T17:04:06Z
38,554,568
<p>Not sure why are you putting the html string into the list here:</p> <pre><code>soup = BeautifulSoup([html2]) </code></pre> <p>Replace it with:</p> <pre><code>soup = BeautifulSoup(html2) </code></pre> <p>Or, you can also pass the response file-like object, <code>BeautifulSoup</code> would read it for you:</p> <...
0
2016-07-24T17:06:03Z
[ "python", "python-3.x", "beautifulsoup" ]
Mac OS X /bin/bash: python: command not found in some IDE
38,554,566
<p>When I compiled <code>test.py</code>(a very simple Python file) in Sublime Text or CodeRunner, I got the error:<code>/bin/bash: python: command not found</code>. Then I input <code>python test.py</code> in the Terminal app, it worked. Later I downloaded Pycharm and compiled the file again, it worked too! </p> <p>So...
4
2016-07-24T17:05:46Z
38,554,744
<p>The Terminal loads a number of files that can modify your PATH variable, including <code>~/.profile</code>, <code>~/.bashrc</code>, <code>~/.bash_profile</code>, etc. These do not get loaded when the Mac OS X system UI is started / when you login to your user profile via the Finder app. Consequently, apps started vi...
4
2016-07-24T17:25:23Z
[ "python", "bash", "osx", "sublimetext3", "coderunner" ]
Mac OS X /bin/bash: python: command not found in some IDE
38,554,566
<p>When I compiled <code>test.py</code>(a very simple Python file) in Sublime Text or CodeRunner, I got the error:<code>/bin/bash: python: command not found</code>. Then I input <code>python test.py</code> in the Terminal app, it worked. Later I downloaded Pycharm and compiled the file again, it worked too! </p> <p>So...
4
2016-07-24T17:05:46Z
38,566,731
<p>Thank everyone who helps. I've solved the problem myself.</p> <p>I've always been using zsh instead of bash. After updating CodeRunner to the newest version, the app uses bash by default. So I just need go to Preference>Advanced menu and untick the checkbox <strong>invoke bash in login mode when running code</stron...
0
2016-07-25T11:37:08Z
[ "python", "bash", "osx", "sublimetext3", "coderunner" ]
Finding number of cells visited in given explanation
38,554,587
<p>This is a Hackerrank question.</p> <p>Babai is standing in the top left cell (1,1) of an N*M table. The table has N rows and M columns. </p> <p>Initially he is facing its right cell. He moves in the table in the following manner:</p> <blockquote> <ol> <li>He moves one step forward</li> <li>He turns to its r...
0
2016-07-24T17:07:57Z
38,554,824
<p>The answer lies in the <code>9x9</code> matrix that you showed. The base conditions are trivial.</p> <p>First suppose that N is even. Lets say 8. Then the path shall terminate at the cell that is marked 16 because all the 3 neighbouring cells would be already visited and no further path would be possible. Hence <co...
1
2016-07-24T17:33:23Z
[ "python", "algorithm" ]
Finding number of cells visited in given explanation
38,554,587
<p>This is a Hackerrank question.</p> <p>Babai is standing in the top left cell (1,1) of an N*M table. The table has N rows and M columns. </p> <p>Initially he is facing its right cell. He moves in the table in the following manner:</p> <blockquote> <ol> <li>He moves one step forward</li> <li>He turns to its r...
0
2016-07-24T17:07:57Z
38,554,936
<p>The code is almost correct.</p> <p>It identifies 4 cases. The first two are trivial:</p> <pre><code>if m == 0 or n == 0: return 0 elif m == 1 and n == 1: return 1 </code></pre> <p>Those are obviously correct return values, and also serve as an end point to the recursion that is used in the third case.</p>...
2
2016-07-24T17:44:10Z
[ "python", "algorithm" ]
hi § symbol unrecognized
38,554,621
<p>good morning. I'm trying to do this and not leave me .</p> <p>Can you help me?</p> <p>thank you very much</p> <pre><code> soup = BeautifulSoup(html_page) titulo=soup.find('h3').get_text() titulo=titulo.replace('§','') titulo=titulo.replace('§','') UnicodeDecodeError: 'ascii' codec can't deco...
0
2016-07-24T17:11:54Z
38,554,668
<p><a href="http://stackoverflow.com/questions/3170211/why-declare-unicode-by-string-in-python">Define the <code>coding</code></a> and operate with <em>unicode strings</em>:</p> <pre><code># -*- coding: utf-8 -*- from bs4 import BeautifulSoup html_page = u"&lt;h3&gt;§ title here&lt;/h3&gt;" soup = BeautifulSoup(htm...
3
2016-07-24T17:17:06Z
[ "python", "beautifulsoup", "symbol" ]
hi § symbol unrecognized
38,554,621
<p>good morning. I'm trying to do this and not leave me .</p> <p>Can you help me?</p> <p>thank you very much</p> <pre><code> soup = BeautifulSoup(html_page) titulo=soup.find('h3').get_text() titulo=titulo.replace('§','') titulo=titulo.replace('§','') UnicodeDecodeError: 'ascii' codec can't deco...
0
2016-07-24T17:11:54Z
38,555,143
<p>I'll explain you clearly what's the problem:</p> <p>By default Python does not recognize particular characters like "à" or "ò". To make Python recognize those characters you have to put at the top of your script:</p> <pre><code># -*- coding: utf-8 -*- </code></pre> <p>This codes makes Python recognize particula...
0
2016-07-24T18:05:54Z
[ "python", "beautifulsoup", "symbol" ]
Python pysft/paramiko 'EOF during negotiation' error
38,554,629
<p>I'm using pysftp to download and upload some files. This exact same code I just run an hour before and was fine, but now I got this 'EOF during negotiation' error. What am I missing here?</p> <pre><code>&gt;&gt;&gt; sftp = pysftp.Connection(host, username=user, password=pasw) &gt;&gt;&gt; sftp &lt;pysftp.Connection...
1
2016-07-24T17:13:13Z
38,956,472
<p>Turns out this was a connection issue in the SFTP server. Contacted the SFTP admin who fixed it, and now the same code works fine.</p>
0
2016-08-15T13:57:21Z
[ "python", "python-2.7", "paramiko", "pysftp" ]
django channels message.reply_channel no attribute send
38,554,631
<p>I've been trying to get my head around the channels of Django and I can't get my message to be sent to my websocket.</p> <p>Here is my <code>consumers.py</code></p> <pre><code>import logging from django.contrib.sites.models import Site from django.utils import timezone from channels import Group from .models impor...
2
2016-07-24T17:13:20Z
38,555,119
<p>I assume you are calling <code>"send-free"</code> from your view like this...</p> <pre><code>Channel('send-free').send({'message': 'your message'}) </code></pre> <p>Then <code>send_free</code> doesn't have the <code>message.reply_channel</code>...</p> <p>In other word once the <code>WebSocket packet is sent to us...
1
2016-07-24T18:03:20Z
[ "python", "django", "django-channels" ]
Add border under column headers in QTableWidget
38,554,640
<p>I have a table widget with two column header in a dialog that looks like this:</p> <p><a href="http://i.stack.imgur.com/Gws4x.png" rel="nofollow"><img src="http://i.stack.imgur.com/Gws4x.png" alt="enter image description here"></a> </p> <p>There is a separation between the column headers named "Index" and "Label",...
1
2016-07-24T17:14:16Z
38,804,069
<p>I had the same problem. The first thing to note is that this only happens on Windows 10. On other OS, there is nothing to repair, it just works. On Windows 10 however, the painting primitives are not painting the bottom border (which is the default Windows 10 table header style - as can be seen in windows file explo...
1
2016-08-06T12:00:27Z
[ "python", "qt", "pyqt", "border", "qtablewidget" ]
How to stop (and restart!) a Tornado server?
38,554,694
<p>I want to be able to stop and restart a Tornado server for testing and demo purposes. But it doesn't seem to release the port.</p> <p>The following code is based on <a href="http://stackoverflow.com/a/17325148/487992">answer showing how to properly stop Tornado</a>. I just added the code at the bottom that tries to...
1
2016-07-24T17:20:14Z
38,557,549
<p>Don't use threads like this unless you <em>really</em> need to - they complicate things quite a bit. For tests, use <code>tornado.testing.AsyncTestCase</code> or <code>AsyncHTTPTestCase</code>. </p> <p>To free the port, you need to stop the <code>HTTPServer</code>, not just the <code>IOLoop</code>. In fact, you mig...
1
2016-07-24T22:40:27Z
[ "python", "python-2.7", "tornado" ]
Python dict to DataFrame Pandas - levels
38,554,706
<p>Few months ago @Romain X. helped me a lot with this question:</p> <p><a href="http://stackoverflow.com/questions/32770359/python-dict-to-dataframe-pandas/32771114#32771114">Python dict to DataFrame Pandas</a></p> <p>Now I´m trying to do the same with deeper levels, here is the example:</p> <pre><code> {u'instru...
1
2016-07-24T17:22:06Z
38,555,280
<p>Here you go,</p> <pre><code>df = pd.DataFrame.from_dict(d)\ .join(pd.DataFrame.from_dict(d['instruments']))\ .drop('instruments', axis=1) df2 = pd.DataFrame.from_dict(df.interestRate[0]) df2 = pd.DataFrame.transpose(df2) df2 = df2.reset_index() df2.columns.values[0] = 'instrument' print (df2) instrument ask...
1
2016-07-24T18:21:24Z
[ "python", "pandas", "dictionary" ]
Django file size & content_type restriction at form level vs model?
38,554,728
<p>I am trying to implement file size &amp; content_type restriction for my django file uploads. Ideally,i would like to validate before i upload. Initially i am using this reproduced code but it is not working.</p> <pre><code>class ContentTypeRestrictedFileField(FileField): """ Same as FileField, but you can specify:...
0
2016-07-24T17:24:20Z
38,557,134
<p>The answer is in the question. Model validations happen after the file has been uploaded to temp holding place in django while form validations happen before upload. So , the second part is the correct answer.</p>
0
2016-07-24T21:44:42Z
[ "python", "django", "validation" ]
Can't update DNS record on Route 53 using boto3
38,554,754
<p>I'm trying to get an dynamic DNS updater script working using AWS Route 53, python3 and boto3. It functions as follows:</p> <ol> <li>Retrieve machine IP from an internet service</li> <li>Retrieve current IP in Route 53 DNS</li> <li>Check if they match (if so, exit)</li> <li>Update DNS (replace old IP with current o...
1
2016-07-24T17:26:01Z
38,556,615
<p>I solved the problem. The <code>Region</code> option must only be set for latency-based record sets; commenting it out solved the problem.</p>
2
2016-07-24T20:46:21Z
[ "python", "dns", "amazon-route53", "boto3" ]
How to return the value of a variable only when a button has been clicked?
38,554,807
<p>My code:</p> <pre><code>def file_exists(f_name): select = 0 def skip(): nonlocal select select = 1 err_msg.destroy() def overwrite(): nonlocal select select = 2 err_msg.destroy() def rename(): glob...
0
2016-07-24T17:32:15Z
38,555,212
<p>You can make use of the <a href="http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.update-method" rel="nofollow"><code>.update()</code></a> function to block without freezing the GUI. Basically you call <code>root.update()</code> in a loop until a condition is fulfilled. An example:</p> <pre><code>def block()...
-1
2016-07-24T18:13:30Z
[ "python", "tkinter" ]
Search for a specific element in one array and copy the entire corresponding row in other array
38,554,861
<p>I have the following problem to which i haven't found any helpful hints anywhere so far.</p> <p>I have two arrays which look like this:</p> <pre><code>sample_nodes = [[ ID_1 x1 y1 z1] [ ID_2 x2 y2 z2] [ ID_3 x3 y3 z4] . . ...
2
2016-07-24T17:37:07Z
38,555,340
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> to form the original row order and then simply indexing into <code>sample_nodes</code> with it would give us the desired output. Thus, we would have an implementation like...
1
2016-07-24T18:26:37Z
[ "python", "arrays", "numpy" ]
Search for a specific element in one array and copy the entire corresponding row in other array
38,554,861
<p>I have the following problem to which i haven't found any helpful hints anywhere so far.</p> <p>I have two arrays which look like this:</p> <pre><code>sample_nodes = [[ ID_1 x1 y1 z1] [ ID_2 x2 y2 z2] [ ID_3 x3 y3 z4] . . ...
2
2016-07-24T17:37:07Z
38,555,347
<p>The <a href="https://pypi.python.org/pypi/numpy-indexed" rel="nofollow">numpy_indexed</a> package has a function to solve the key step of your problem (finding the indices of one sequence in another). If you are unfamiliar with numpy, and care about efficiency at all, make sure to read up on that as well!</p> <pre>...
1
2016-07-24T18:27:08Z
[ "python", "arrays", "numpy" ]
Why does this code returns last line of T matrix
38,555,034
<pre><code>class Solution: """ rotates, queries and stuff blah blah blah """ def mains(self): pass def rotate(self,A): n = len(A[0]) T = [[0]*n]*n # the above part is erraneous probably, on individual initialization it works! for i in xrange(n): for j in xrange(n)...
0
2016-07-24T17:54:55Z
38,555,068
<p>With your approach, the same <em>sublist</em> is duplicated <code>n</code> times:</p> <pre><code>T = [[0]*n]*n </code></pre> <p>So changes are reflected across them simultaneously.</p> <hr> <p>You should instead set up <code>T</code> like so:</p> <pre><code>T = [[0]*n for _ in range(n)] </code></pre> <p>This ...
1
2016-07-24T17:59:07Z
[ "python", "list" ]
Why does this code returns last line of T matrix
38,555,034
<pre><code>class Solution: """ rotates, queries and stuff blah blah blah """ def mains(self): pass def rotate(self,A): n = len(A[0]) T = [[0]*n]*n # the above part is erraneous probably, on individual initialization it works! for i in xrange(n): for j in xrange(n)...
0
2016-07-24T17:54:55Z
38,555,075
<p>This is because <code>[[0]*n]*n</code> creates a list of size <code>n</code> filled with <em>references to the same list</em> (<code>[0]*n</code>), so when you're accessing <code>T[i][j]</code>, you're using the same memory location.</p> <p>Here are some examples of different setup:</p> <pre><code>&gt;&gt;&gt; T=[...
1
2016-07-24T18:00:00Z
[ "python", "list" ]
Why does this code returns last line of T matrix
38,555,034
<pre><code>class Solution: """ rotates, queries and stuff blah blah blah """ def mains(self): pass def rotate(self,A): n = len(A[0]) T = [[0]*n]*n # the above part is erraneous probably, on individual initialization it works! for i in xrange(n): for j in xrange(n)...
0
2016-07-24T17:54:55Z
38,555,081
<p>You got caught by the mutability of <code>list</code> instances. Here</p> <pre><code>T = [[0]*n]*n </code></pre> <p>The inner multiplication creates <code>n</code> references to an <code>int</code> instance. Since Python's <code>int</code>s are immutable, when you change one, a new object and a new reference is c...
1
2016-07-24T18:00:21Z
[ "python", "list" ]
Why does this code returns last line of T matrix
38,555,034
<pre><code>class Solution: """ rotates, queries and stuff blah blah blah """ def mains(self): pass def rotate(self,A): n = len(A[0]) T = [[0]*n]*n # the above part is erraneous probably, on individual initialization it works! for i in xrange(n): for j in xrange(n)...
0
2016-07-24T17:54:55Z
38,555,186
<p>You could also build your list while looping:</p> <pre><code>&gt;&gt;&gt; T = [] &gt;&gt;&gt; &gt;&gt;&gt; for i in xrange(3): T.append([]) for j in xrange(3): T[i].append(l[j][i]) &gt;&gt;&gt; T [[1, 4, 7], [2, 5, 8], [3, 6, 9]] </code></pre>
0
2016-07-24T18:09:56Z
[ "python", "list" ]
In Django REST is there a way of setting the key in a RetrieveAPIView, rather than filtering in a ListAPIView?
38,555,057
<p>In Django REST I have a ListAPIView, which I use to fetch records (usually just the one) based on the request user:</p> <pre><code>class UserPageView(ListAPIView): serializer_class = UserPageSerializer def get_queryset(self): return User.objects.filter(pk=self.request.user.pk) </code></pre> <p>Beca...
1
2016-07-24T17:58:06Z
38,557,900
<p><code>ListAPIView</code> and <code>DetailAPIView</code> are <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py" rel="nofollow">GenericAPIViews</a>, with standard implementations of list-detail-create-update-delete <a href="https://github.com/tomchristie/django-rest-f...
0
2016-07-24T23:33:38Z
[ "python", "django", "django-rest-framework" ]
Finding most occuring substing in list
38,555,061
<p>I have a long list of sub-stings that I want to search through and find how many times two particular sub-stings occur. The following code is what I have started:</p> <pre><code>dataA = ['0000000001001000', '0000000010010001', '0000000100100011', '0000001001000100', '0000010010001010', '0000100100010100', '00010010...
0
2016-07-24T17:58:41Z
38,556,385
<p>I think what you want is something like the following. It sounds like you want to check the next item after a match against the first search.</p> <pre><code>for i,text in enumerate(dataA): if joined_A_Search_1 == text: if joined_A_Search_2 == dataA[i+1][:-1]: print 'logic stream 1' ...
0
2016-07-24T20:18:15Z
[ "python", "list", "for-loop", "substring" ]
Splitting large file into smaller file giving memory error
38,555,067
<p>This is the python code i'm using. I have a 5gb file which i need to split in around 10-12 files according to line numbers. But this code gives a memory error. Please can someone tell me what is wrong with this code?</p> <pre><code>from itertools import izip_longest def grouper(n, iterable, fillvalue=None): "C...
0
2016-07-24T17:58:59Z
38,555,531
<p>Just use groupby, so you don't need to create 386972 iterators:</p> <pre><code>from itertools import groupby n = 386972 with open('reviewsNew.txt','rb') as f: for idx, lines in groupby(enumerate(iterable), lambda (idx, _): idx // n): with open('small_file_{0}'.format(idx * n), 'wb') as fout: ...
0
2016-07-24T18:44:50Z
[ "python" ]
python list of list unlinking the object
38,555,102
<p>I have two list that I combine into a single list. Later I want to make a copy of this list so I can do some manipulation of this second list without affecting my first list. My understanding is if you use this [:] it should unlink the list and make a second copy of the list in a independent memory location. My prob...
0
2016-07-24T18:02:01Z
38,555,138
<p><code>[:]</code> only makes a shallow copy. That is, it copies the list itself but not the items in the list. You should use <code>copy.deepcopy</code>. </p> <pre><code>import copy d = copy.deepcopy(c) </code></pre> <p>Think of a list as having pointers to objects. Now your variable is a pointer to the list. What ...
2
2016-07-24T18:05:35Z
[ "python", "python-3.x" ]
python list of list unlinking the object
38,555,102
<p>I have two list that I combine into a single list. Later I want to make a copy of this list so I can do some manipulation of this second list without affecting my first list. My understanding is if you use this [:] it should unlink the list and make a second copy of the list in a independent memory location. My prob...
0
2016-07-24T18:02:01Z
38,555,192
<p>You have come across the concept of shallow and deep copy in Python.</p> <p>The slice operator works well when the list structures do not have any sublists. </p> <pre><code>list1 = ['a', 'b', 'c', 'd'] list2 = list1[:] list2[1] = 'x' print list1 ['a', 'b', 'c', 'd'] print list2 ['a', 'x', 'c', 'd'] </code></pre> ...
0
2016-07-24T18:10:50Z
[ "python", "python-3.x" ]
Hardware requirements to deal with a big matrix - python
38,555,120
<p>I am working on a python project where I will need to work with a matrix whose size is around 10000X10000X10000.</p> <p>Considering that:</p> <ul> <li>The matrix will be dense, and should be stored in the RAM.</li> <li>I will need to perform linear algebra (with numpy, I think) on that matrix, with around O(n^3) w...
1
2016-07-24T18:03:25Z
38,555,206
<p>Actually, the memory would be a big issue here. Depending on the type of the matrix elements. Each float takes 24 bytes for example as it is a boxed object. As your matrix is 10^12 you can do the math. Switching to C would probably make it more memory-efficient, but not faster, as numpy is essentially written in C ...
0
2016-07-24T18:13:09Z
[ "python", "numpy", "matrix" ]
Hardware requirements to deal with a big matrix - python
38,555,120
<p>I am working on a python project where I will need to work with a matrix whose size is around 10000X10000X10000.</p> <p>Considering that:</p> <ul> <li>The matrix will be dense, and should be stored in the RAM.</li> <li>I will need to perform linear algebra (with numpy, I think) on that matrix, with around O(n^3) w...
1
2016-07-24T18:03:25Z
38,555,266
<p>Well, the first question is, wich type of value will you store in your matrix? Suposing it will be of integers (and suposing that every bytes uses the ISO specification for size, 4 bytes), you will have 4*10^12 bytes to store. That's a large amount of information (4 TB), so, in first place, I don't know from where y...
4
2016-07-24T18:19:43Z
[ "python", "numpy", "matrix" ]
Hardware requirements to deal with a big matrix - python
38,555,120
<p>I am working on a python project where I will need to work with a matrix whose size is around 10000X10000X10000.</p> <p>Considering that:</p> <ul> <li>The matrix will be dense, and should be stored in the RAM.</li> <li>I will need to perform linear algebra (with numpy, I think) on that matrix, with around O(n^3) w...
1
2016-07-24T18:03:25Z
38,558,638
<p>Maybe something like <a href="http://dask.pydata.org/en/latest/" rel="nofollow">dask</a> would be a good fit for you? There are other ways to do this with numpy like using memory mapped arrarys and doing operations in parallelizable chunks, but will be a bit more difficult especially if you are still getting comfort...
1
2016-07-25T01:46:53Z
[ "python", "numpy", "matrix" ]
Scrapy: Custom Call-Backs do not work
38,555,128
<p>I'm at a loss for why my spider doesn't work! I am by <strong>no</strong> means a programmer so please be kind! haha</p> <p><strong>Background:</strong> I'm trying to scrape the information pertaining to books found on Indigo with the use of "Scrapy".</p> <p><strong>Problem:</strong> My code does not enter any of...
1
2016-07-24T18:04:10Z
38,555,269
<p>One of the first ploblems I've noticed is that your <code>allowed_domains</code> class attribute is broken. It should contain <strong>domains</strong> (thus the name).</p> <p>Correct value in your case would be: </p> <pre><code>allowed_domains = [ "chapters.indigo.ca", # subdomain.domain.top_level_domain ] <...
1
2016-07-24T18:20:09Z
[ "python", "callback", "scrapy", "web-crawler" ]
AttributeError: 'module' object has no attribute 'compile'
38,555,161
<p>I have the following code that I saved as re.py </p> <pre><code>import sys pattern ="Fred" import re regexp = re.compile(pattern) for line in sys.stdin: result = regexp.search(line) if result: sys.stdout.write(line) </code></pre> <p>When I execute this file in terminal - </p> <pre><code>$python ...
0
2016-07-24T18:07:50Z
38,555,177
<p>Rename your script from <code>re.py</code> to something else. The name you have chosen is <em>shadowing</em> the <code>re</code> module you intend to use.</p>
2
2016-07-24T18:08:51Z
[ "python", "regex" ]
Callback at random times from a child process with infinite loop, and termination
38,555,189
<p>I need to react in a main process to random events happening in a child process. I have implemented this with a queue between the main and the child process, and a 'queue poller' running in a secondary thread of the main process and calling a callback function each time it finds an item in the queue. The code is bel...
0
2016-07-24T18:10:15Z
38,556,065
<p>General observations:</p> <p><strong>class MyChildProcess</strong></p> <p>You don't need to create separate classes for the child process and listener thread. Simple functions can work.</p> <p><strong>pollQueue</strong></p> <p>You can use a blocking get() call in the listener thread. This will make that thread m...
0
2016-07-24T19:46:03Z
[ "python", "multithreading", "multiprocessing" ]
Get all twitter mentions using tweepy for users with Millions of followers
38,555,191
<p>I have had a project in mind where I would download all the tweets sent to celebrities for the last one year and do a sentiment analysis on them and evaluate who had the most positive fans.</p> <p>Then I discovered that you can at max retrieve twitter mentions for the last 7 days using tweepy/twitter API. I scaveng...
1
2016-07-24T18:10:45Z
39,671,701
<p>I would use the search api. I did something similar with the following code. It appears to have worked exactly as expected. I used it on a specific movie star, and pulled 15568 tweets, upon a quick scan all of which appear to be @mentions of them. (I pulled from their entire timeline.)</p> <p>In your case, on a...
1
2016-09-24T01:42:02Z
[ "python", "twitter", "tweepy", "sentiment-analysis" ]
tornado async post error 500 but curl OK
38,555,201
<p>URL is <code>http://*.*.*.*/100/?id=1&amp;version=1</code></p> <p>params is </p> <pre><code>{"cityId": "110000", "query": {"queryStr": "line1", "queryExp": ""}, "channelId": "house"} </code></pre> <p>curl command is: </p> <pre><code>curl -X POST -H "Content-Type: application/json" -d '{"cityId": "110000", "query...
0
2016-07-24T18:11:49Z
38,559,139
<p>You're sending <code>'content-type': 'application/json',</code> but encoding the data with <code>body=urllib.urlencode(data).encode('utf-8')</code>. Use <code>json.dumps</code> instead of <code>urllib.urlencode</code>. </p>
0
2016-07-25T03:06:34Z
[ "python", "tornado" ]
Python script is killed from within, but the process doesn't die
38,555,202
<p>I'm trying to execute a python script using php with an exec command like this:</p> <pre><code>exec("python /address/to/script.py"); </code></pre> <p>I don't need the script to run to completion, so after it does what I need, I call <code>sys.exit()</code> from within it. Execution is passed back to the php script...
1
2016-07-24T18:12:13Z
38,555,308
<p>The script could still be executing some cleanup code, or you could be calling <code>sys.exit()</code> from a child process which will essentially be calling <code>thread.exit()</code>, leaving the parent process running.</p> <p>Check that the <code>sys.exit()</code> call is in the main part of the script and that ...
0
2016-07-24T18:23:50Z
[ "php", "python", "linux", "exec" ]
filtering index Pandas groupby
38,555,215
<p>I have a frame like this</p> <pre><code>frame=pd.DataFrame({'Team':['USA','GER','CAN','USA','GER','CAN'], 'MOV':[-5,2,0,0,3,4]}) </code></pre> <p>I can do a groupby to get the mean 'MOV' for each team</p> <pre><code>print (frame.groupby('Team')['MOV'].mean()) </code></pre> <p>which outputs</p> <...
-1
2016-07-24T18:13:44Z
38,555,271
<pre><code>means = frame.groupby('Team')['MOV'].mean() print (list(means[means &gt; 0].index)) </code></pre> <p><code>means</code> is a series which you can then filter by taking all values in that series that are greater than 0. Then take the index of that filtered series (which will contain the country names) and ...
1
2016-07-24T18:20:21Z
[ "python", "pandas" ]
Remove Objects Containing certain Data from a list
38,555,253
<p>We are all well aware that we can insert a vast array of datatypes into a python list. For eg. a list of characters </p> <pre><code>X=['a','b','c'] </code></pre> <p>To remove 'c' all i have to do is</p> <pre><code>X.remove('c') </code></pre> <p>Now What I need is to remove an object containing a certain string.<...
0
2016-07-24T18:18:17Z
38,555,399
<p>For the list</p> <pre><code>X = [('a',0),('b',0),('c',0)] </code></pre> <p>If you know that the first item of a tuple is always a string, and you want to remove that string if it has a distinct value, then use a list comprehension:</p> <pre><code>X = [('a',0),('b',0),('c',0)] X = [(i,j) for i, j in X if i != '...
0
2016-07-24T18:32:19Z
[ "python", "python-3.x" ]
Remove Objects Containing certain Data from a list
38,555,253
<p>We are all well aware that we can insert a vast array of datatypes into a python list. For eg. a list of characters </p> <pre><code>X=['a','b','c'] </code></pre> <p>To remove 'c' all i have to do is</p> <pre><code>X.remove('c') </code></pre> <p>Now What I need is to remove an object containing a certain string.<...
0
2016-07-24T18:18:17Z
38,555,471
<p>I think what you want is this:</p> <pre><code>&gt;&gt;&gt; class MyObject: ... def __init__(self, i, j): ... self.i = i ... self.j = j ... def __repr__(self): ... return '{} - {}'.format(self.i, self.j) ... &gt;&gt;&gt; x = [MyObject(1, 'c'), MyObject(2, 'd'), MyObject(3, 'e')] &gt;&gt;&gt; re...
1
2016-07-24T18:38:34Z
[ "python", "python-3.x" ]
Remove Objects Containing certain Data from a list
38,555,253
<p>We are all well aware that we can insert a vast array of datatypes into a python list. For eg. a list of characters </p> <pre><code>X=['a','b','c'] </code></pre> <p>To remove 'c' all i have to do is</p> <pre><code>X.remove('c') </code></pre> <p>Now What I need is to remove an object containing a certain string.<...
0
2016-07-24T18:18:17Z
38,555,666
<p>The following function will remove <strong>in place</strong> all the items for them condition is <code>True</code>:</p> <pre><code>def remove(list,condtion): ii = 0 while ii &lt; len(list): if condtion(list[ii]): list.pop(ii) continue ii += 1 </code></pre> <p...
1
2016-07-24T18:59:41Z
[ "python", "python-3.x" ]
Is there any function in openCV or another library that can tile squares within an arbitrary contour?
38,555,275
<p>I have images where I've found some contours around dogs, e.g.:</p> <p><a href="http://i.stack.imgur.com/RLX2L.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/RLX2L.jpg" alt="dog contour"></a></p> <p>I want to tile squares/rectangles inside of the contour. Is there an openCV (or other library) function for...
0
2016-07-24T18:20:43Z
38,557,098
<p>I was able to solve this by first drawing rectangles over the entire image, then checking which ones were in the area with the dog:</p> <pre><code># the image here is stored as the variable fg # with b, g, r, and alpha channels # the alpha channel is masking the dog part of the image import cv2 b, g, r, a = cv2.sp...
0
2016-07-24T21:40:56Z
[ "python", "python-3.x", "opencv", "computer-vision" ]
python regex matching between two strings
38,555,310
<p>I have the following string:</p> <pre><code>property some_property_name; @(posedge some_clock) disable iff (some_other_signal) signalA &amp;&amp; signalB || !($isunknown(some_other_signal)) &amp;&amp; |-&gt; !($isunknown(should_not_match_this)) endproperty more_random_code property some_other_proper...
1
2016-07-24T18:23:59Z
38,555,454
<p>I would use something like</p> <pre><code>(?&lt;=@\(posedge).*?(\!\(\$isunknown\(.*?\)\)).*?\|-&gt; </code></pre> <p><img src="https://www.debuggex.com/i/S5hvPO6L2aUjLsUN.png" alt="Regular expression visualization"></p> <p><a href="https://www.debuggex.com/r/S5hvPO6L2aUjLsUN" rel="nofollow">Debuggex Demo</a></p> ...
1
2016-07-24T18:37:16Z
[ "python", "regex", "pattern-matching" ]
extract hours and minutes from string python
38,555,327
<p>I have a string that is in the format of '00:00' displaying the time, it can be any time. I would like to extract the hours and minutes into individual variables. </p>
0
2016-07-24T18:25:27Z
38,555,350
<p>The <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow">split</a> function is your friend here:</p> <pre><code>&gt;&gt;&gt; time = "11:23" &gt;&gt;&gt; hours, minutes = time.split(":") &gt;&gt;&gt; print hours 11 &gt;&gt;&gt; print minutes 23 </code></pre>
1
2016-07-24T18:27:27Z
[ "python", "python-2.7", "python-3.x" ]
extract hours and minutes from string python
38,555,327
<p>I have a string that is in the format of '00:00' displaying the time, it can be any time. I would like to extract the hours and minutes into individual variables. </p>
0
2016-07-24T18:25:27Z
38,555,359
<p>If it always in the same format you could <code>split</code> it by the colons:</p> <pre><code>hours, minutes = "00:00".split(":") </code></pre>
1
2016-07-24T18:28:03Z
[ "python", "python-2.7", "python-3.x" ]
extract hours and minutes from string python
38,555,327
<p>I have a string that is in the format of '00:00' displaying the time, it can be any time. I would like to extract the hours and minutes into individual variables. </p>
0
2016-07-24T18:25:27Z
38,555,367
<p>You may want <code>hours</code> and <code>minutes</code> be integers:</p> <pre><code>hours, minutes = map(int, "00:00".split(':')) </code></pre> <hr> <h2>How this works</h2> <ol> <li><code>str.split(delim)</code> splits a <code>str</code> using <code>delim</code> as delimiter. Returns a list: <code>"00:00".split...
3
2016-07-24T18:28:42Z
[ "python", "python-2.7", "python-3.x" ]
extract hours and minutes from string python
38,555,327
<p>I have a string that is in the format of '00:00' displaying the time, it can be any time. I would like to extract the hours and minutes into individual variables. </p>
0
2016-07-24T18:25:27Z
38,555,558
<p>For parsing times, use the <code>datetime</code>-class:</p> <pre><code>import datetime time = datetime.datetime.strptime('23:43', '%H:%M') print time.hour, time.minute </code></pre>
1
2016-07-24T18:47:57Z
[ "python", "python-2.7", "python-3.x" ]
Google app engine endpoints api python
38,555,353
<p>I am facing a problem in endpoint. I am using google app engine on local machine. I am trying to make a endpoint api. The api is created successfully but when i open explorer and select my api give some parameters to it. It does not return response. In response it said 404 not found</p> <p>Here is the code:</p> <p...
1
2016-07-24T18:27:31Z
38,570,856
<p>@Scarygami Answere is correct. I have to remove the hostname because i am using it on local host.</p>
1
2016-07-25T14:45:33Z
[ "python", "google-app-engine", "google-cloud-endpoints", "webapp2" ]
Removing duplicate edges from graph in Python list
38,555,385
<p>My program returns a list of tuples, which represent the edges of a graph, in the form of:</p> <pre><code>[(i, (e, 130)), (e, (i, 130)), (g, (a, 65)), (g, (d, 15)), (a, (g, 65))] </code></pre> <p>So, (i, (e, 130)) means that 'i' is connected to 'e' and is 130 units away.</p> <p>Similarly, (e, (i, 130)) means that...
6
2016-07-24T18:30:45Z
38,555,503
<p>If a tuple <code>(n1, (n2, distance))</code> represents a bidirectional connection, I would introduce a normalization property which constraints the ordering of the two nodes in the tuple. This way, each possible edge has exactly one unique representation.</p> <p>Consequently, a normalization function would map a g...
7
2016-07-24T18:41:32Z
[ "python" ]
Removing duplicate edges from graph in Python list
38,555,385
<p>My program returns a list of tuples, which represent the edges of a graph, in the form of:</p> <pre><code>[(i, (e, 130)), (e, (i, 130)), (g, (a, 65)), (g, (d, 15)), (a, (g, 65))] </code></pre> <p>So, (i, (e, 130)) means that 'i' is connected to 'e' and is 130 units away.</p> <p>Similarly, (e, (i, 130)) means that...
6
2016-07-24T18:30:45Z
38,555,525
<p>Reconstruct each edge to take its alternate form and check if the alternate form is already in a new set. If it is not then add to the set:</p> <pre><code>lst = [('i', ('e', 130)), ('e', ('i', 130)), ('g', ('a', 65)), ('g', ('d', 15)), ('a', ('g', 65))] r = set() for e, v in lst: if (v[0], (e, v[1])) in r: ...
2
2016-07-24T18:44:26Z
[ "python" ]
Removing duplicate edges from graph in Python list
38,555,385
<p>My program returns a list of tuples, which represent the edges of a graph, in the form of:</p> <pre><code>[(i, (e, 130)), (e, (i, 130)), (g, (a, 65)), (g, (d, 15)), (a, (g, 65))] </code></pre> <p>So, (i, (e, 130)) means that 'i' is connected to 'e' and is 130 units away.</p> <p>Similarly, (e, (i, 130)) means that...
6
2016-07-24T18:30:45Z
38,555,529
<p>The simplest solution to write would be simply to iterator and check equality of all of them:</p> <pre><code>def edge_equal(edge_tuple1, edge_tuple2): return edge_tuple1[0] == edge_tuple2[1][0] and edge_tuple2[0] == edge_t\ uple1[1][0] new = [] for i in range(len(graph)): found_equal = False for e...
2
2016-07-24T18:44:36Z
[ "python" ]
Removing duplicate edges from graph in Python list
38,555,385
<p>My program returns a list of tuples, which represent the edges of a graph, in the form of:</p> <pre><code>[(i, (e, 130)), (e, (i, 130)), (g, (a, 65)), (g, (d, 15)), (a, (g, 65))] </code></pre> <p>So, (i, (e, 130)) means that 'i' is connected to 'e' and is 130 units away.</p> <p>Similarly, (e, (i, 130)) means that...
6
2016-07-24T18:30:45Z
38,555,565
<pre><code>edges = [(i, (e, 130)), (e, (i, 130)), (g, (a, 65)), (g, (d, 15)), (a, (g, 65))] for each in edges: try: edges.remove((each[1][0], (each[0], each[1][1]))) except ValueError: pass </code></pre> <p>reverse the vectors and remove them as you traverse</p>
2
2016-07-24T18:48:34Z
[ "python" ]
In DRF(django-rest-framework), AttributeError 'str' object has no attribute '~~' How to solve it?
38,555,457
<p>I'm using DRF and be front of AttributeError 'str' object has no attribute '~~'.</p> <p><strong>my error page and code</strong></p> <pre><code>Environment: Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Django Version: 1.9.7 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', '...
1
2016-07-24T18:37:35Z
38,555,797
<p>This has nothing to do with your serializer, or where you put it. The error traceback is telling you that the error happens in the view.</p> <p>So, in your post_list view, you build up a list (also called <code>post_list</code>) which is populated by a list of strings. Then you try and put it through the PostSerial...
0
2016-07-24T19:14:47Z
[ "python", "django", "django-rest-framework" ]
Euclidean Algorithm (subtraction) in python
38,555,486
<p>In "Great Mathematical problems -- Vision of infinity", page 18 Ian Stewart referred Euclid's proposition 2, Book VII of Element which is a very elementary method of finding Greatest common divisor. I quote "It works by repeatedly subtracting the smaller number from the larger one, then applying a similar process to...
-5
2016-07-24T18:39:35Z
38,571,393
<p>A typical fast solution to the gcd algorithm would be some iterative version like this one:</p> <pre><code>def gcd(x, y): while y != 0: (x, y) = (y, x % y) return x </code></pre> <p>In fact, in python you'd just use directly the gcd function provided by fractions module.</p> <p>And if you wanted ...
0
2016-07-25T15:10:11Z
[ "python", "algorithm", "subtraction", "greatest-common-divisor" ]
How to read lines from file starting from arbitrary newline in Python
38,555,592
<p>I have a file formatted in a way that lines are separated with a new line, like the following</p> <pre><code>1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 </code></pre> <p>I would like to read the lines separately starting, for example, from the second one and save them in an array. I think I can manage the last part, but I ...
1
2016-07-24T18:51:06Z
38,555,654
<p>As files are iterable in python you could call <a href="https://docs.python.org/2/library/stdtypes.html#iterator.next" rel="nofollow"><code>next</code></a> on it to skip the first line, for example:</p> <pre><code>with open('data.txt', 'r') as data: next(data) for line in data: print line.split() </...
2
2016-07-24T18:58:17Z
[ "python", "file", "newline" ]
How to read lines from file starting from arbitrary newline in Python
38,555,592
<p>I have a file formatted in a way that lines are separated with a new line, like the following</p> <pre><code>1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 </code></pre> <p>I would like to read the lines separately starting, for example, from the second one and save them in an array. I think I can manage the last part, but I ...
1
2016-07-24T18:51:06Z
38,555,691
<p>If you know a-priori the line you want to start reading from, just use <code>f.read().splitlines()</code> to get a list of all the lines and then extract the required list suffix using slices as shown below.</p> <pre><code>n = 1 with open('filename.txt') as f: lines = f.read().splitlines()[n:] print(lines) </...
0
2016-07-24T19:02:32Z
[ "python", "file", "newline" ]
How to read lines from file starting from arbitrary newline in Python
38,555,592
<p>I have a file formatted in a way that lines are separated with a new line, like the following</p> <pre><code>1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 </code></pre> <p>I would like to read the lines separately starting, for example, from the second one and save them in an array. I think I can manage the last part, but I ...
1
2016-07-24T18:51:06Z
38,555,699
<pre><code>lines = open('test.txt', 'r').readlines() # n is your desired line for lineno in range(n-1, len(lines)): print list(lines[lineno].strip()) </code></pre>
1
2016-07-24T19:03:22Z
[ "python", "file", "newline" ]
How to read lines from file starting from arbitrary newline in Python
38,555,592
<p>I have a file formatted in a way that lines are separated with a new line, like the following</p> <pre><code>1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 </code></pre> <p>I would like to read the lines separately starting, for example, from the second one and save them in an array. I think I can manage the last part, but I ...
1
2016-07-24T18:51:06Z
38,555,760
<p>You cannot jump directly to a specific line. You have to read the first n lines:</p> <pre><code>n = 1 with open('data.txt', 'r') as data: for idx, _ in enumerate(data): if idx == n: break for line in data: print line.split() </code></pre>
0
2016-07-24T19:10:19Z
[ "python", "file", "newline" ]
How to read lines from file starting from arbitrary newline in Python
38,555,592
<p>I have a file formatted in a way that lines are separated with a new line, like the following</p> <pre><code>1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 </code></pre> <p>I would like to read the lines separately starting, for example, from the second one and save them in an array. I think I can manage the last part, but I ...
1
2016-07-24T18:51:06Z
38,555,765
<p>Well, you could do something like this:</p> <pre><code>n1, n2 = 0, 2 with open('filename.txt') as f: print '\n'.join(f.read().split('\n')[n1:n2+1]) </code></pre> <p>This would produce (as per the contents in the file you've posted) the output like this:</p> <pre><code>1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 </cod...
1
2016-07-24T19:11:11Z
[ "python", "file", "newline" ]
How to read lines from file starting from arbitrary newline in Python
38,555,592
<p>I have a file formatted in a way that lines are separated with a new line, like the following</p> <pre><code>1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 </code></pre> <p>I would like to read the lines separately starting, for example, from the second one and save them in an array. I think I can manage the last part, but I ...
1
2016-07-24T18:51:06Z
38,555,767
<p>You can use <code>itertool.islice</code> for this, eg:</p> <pre><code>from itertools import islice with open('filename') as fin: wanted = islice(fin, 1, None) # change 1 to lines to skip data = [line.split() for line in wanted] </code></pre>
2
2016-07-24T19:11:35Z
[ "python", "file", "newline" ]
pypyodbc: OPENJSON incorrect syntax near keyword "WITH"
38,555,706
<p>I'm trying to use OPENJSON in a Python script to import some basic JSON into a SQL database. I initially tried with a more complex JSON file, but simplified it for the sake of this post. Here's what I have:</p> <pre><code>sql_statement = "declare @json nvarchar(max) = '{\"name\":\"James\"}'; SELECT * FROM OPENJSON(...
1
2016-07-24T19:04:10Z
38,654,974
<p>The problem could be that your database is running in an older compatibility level, where OPEN JSON is not available.</p> <p>To find the compatibility level of your database, run following SQL statement:</p> <pre><code>SELECT compatibility_level FROM sys.databases WHERE name = 'your_db_name'; </code></pre> <p>If...
3
2016-07-29T09:15:21Z
[ "python", "sql", "sql-server", "json", "pypyodbc" ]
How to center vertically and horizontally a heading text using flask-bootstrap
38,555,814
<p>How can I bring a heading text in the middle of a page? I'm using flask-bootstrap and I would like to customize it with my own CSS style.</p> <p>Here's my sample code:</p> <p><strong>HTML</strong></p> <pre><code>{% extends "bootstrap/base.html" %} {% block head %} &lt;meta charset="utf-8"&gt; &lt;meta http-equiv...
0
2016-07-24T19:17:11Z
38,555,834
<p>In order to use <code>display: table-cell;</code> in this way, the parent element must be set to <code>display: table;</code>. After this it should work.</p> <pre><code>.header { display: table; } </code></pre>
0
2016-07-24T19:19:07Z
[ "python", "html", "css", "twitter-bootstrap" ]
How to center vertically and horizontally a heading text using flask-bootstrap
38,555,814
<p>How can I bring a heading text in the middle of a page? I'm using flask-bootstrap and I would like to customize it with my own CSS style.</p> <p>Here's my sample code:</p> <p><strong>HTML</strong></p> <pre><code>{% extends "bootstrap/base.html" %} {% block head %} &lt;meta charset="utf-8"&gt; &lt;meta http-equiv...
0
2016-07-24T19:17:11Z
38,555,894
<p>I think this will help you.</p> <pre><code>.text-vertical-center{ height: 100px; width: 100px; background-color: #036; left: 0; margin: auto; position: absolute; top: 0; right: 0; bottom: 0; } &lt;div class="text-vertical-center"&gt; &lt;h1&gt;Welcome to my Site&lt;/h1&gt; &lt;h3&gt;My portfolio&l...
0
2016-07-24T19:26:12Z
[ "python", "html", "css", "twitter-bootstrap" ]
How to center vertically and horizontally a heading text using flask-bootstrap
38,555,814
<p>How can I bring a heading text in the middle of a page? I'm using flask-bootstrap and I would like to customize it with my own CSS style.</p> <p>Here's my sample code:</p> <p><strong>HTML</strong></p> <pre><code>{% extends "bootstrap/base.html" %} {% block head %} &lt;meta charset="utf-8"&gt; &lt;meta http-equiv...
0
2016-07-24T19:17:11Z
38,556,244
<p>If you're trying to place the content (both vertically and horizontally) center of the page you can use <code>position: absolute</code> with <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform" rel="nofollow">2D Transforms</a>.</p> <p>*You may want to use a media query for smaller viewports but it i...
0
2016-07-24T20:04:55Z
[ "python", "html", "css", "twitter-bootstrap" ]
convert json retrived from url
38,555,872
<p>I am partially able to work with json saved as file:</p> <pre><code>#! /usr/bin/python3 import json from pprint import pprint json_file='a.json' json_data=open(json_file) data = json.load(json_data) json_data.close() print(data[10]) </code></pre> <p>But I am trying to achieve the same from data directly from we...
1
2016-07-24T19:23:42Z
38,556,264
<p>It's actually telling you the answer: you're getting back a byte array, where in Python 3 a string is different because of dealing with unicode. In Python 2.7, it would work. You should be able to fix it by converting your bytes explicitly to a string with </p> <pre><code>jsonget=str(urlopen("http://api.crossref.o...
-1
2016-07-24T20:06:27Z
[ "python", "json", "python-3.x" ]
groupby DataFrame with new column representing the group
38,555,880
<p>I have a DataFrame with a timestamp column</p> <pre><code>d1=DataFrame({'a':[datetime(2015,1,1,20,2,1),datetime(2015,1,1,20,14,58), datetime(2015,1,1,20,17,5),datetime(2015,1,1,20,31,5), datetime(2015,1,1,20,34,28),datetime(2015,1,1,20,37,51),datetime(2015,1,1,20,41,19), datetime(2015,1,1,20,49,4),datetime(2015,1,1...
0
2016-07-24T19:24:32Z
38,556,106
<p>Use <code>.transform()</code> on your <code>groupby</code> object with an <code>itertools.count</code> iterator:</p> <pre><code>from datetime import datetime from itertools import count import pandas as pd d1 = pd.DataFrame({'a': [datetime(2015,1,1,20,2,1), datetime(2015,1,1,20,14,58), dat...
1
2016-07-24T19:50:48Z
[ "python", "pandas" ]
Find duplicates in mulitple columns and drop rows - Pandas
38,555,922
<p>If the name appears in any subsequent row, I want to drop that row. Mainly i'm not sure how to get the index of that found duplicate and then use that index number to drop it from df.</p> <pre><code>import pandas as pd data = {'interviewer': ['Jason', 'Molly', 'Jermaine', 'Jake', 'Amy'], 'candidate': ['Bob...
1
2016-07-24T19:29:06Z
38,555,985
<p>(At the time when this answer was written, there was some discrepancy between the verbal description and the code example.)</p> <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> to check if an item appears in a different colum...
1
2016-07-24T19:36:27Z
[ "python", "pandas", "rows" ]
Find duplicates in mulitple columns and drop rows - Pandas
38,555,922
<p>If the name appears in any subsequent row, I want to drop that row. Mainly i'm not sure how to get the index of that found duplicate and then use that index number to drop it from df.</p> <pre><code>import pandas as pd data = {'interviewer': ['Jason', 'Molly', 'Jermaine', 'Jake', 'Amy'], 'candidate': ['Bob...
1
2016-07-24T19:29:06Z
38,559,361
<p>I made a function for what I want to do. Using <code>df.index</code> makes it safe to use for any numerical index.</p> <pre><code>def drop_dup_rows(df): names = [] for i, c, ind in zip(df.interviewer, df.candidate, df.index.tolist()): if any(x in names for x in [i, c]): df.drop(ind, inpl...
0
2016-07-25T03:39:28Z
[ "python", "pandas", "rows" ]
How to config file name of logger in each class in scrapy?
38,555,996
<p>I have used scrapy for several months.Several weeks ago,I started to use file to record log information.I wrote <code>log-to-file</code> function as this: </p> <pre><code>def logging_to_file(file_name): import logging from scrapy.utils.log import configure_logging filename = '%s-log.txt' % file_name import os ...
1
2016-07-24T19:37:49Z
38,556,095
<p>I'm not sure if I understand what your question is but in general you don't have to create any functions or anything to configure your logger.</p> <p>What you should do create a logger and assign it a <code>FileHandler</code> and then just use your created logger to log your info.</p> <pre><code>import logging log...
1
2016-07-24T19:49:39Z
[ "python", "logging", "scrapy" ]
In Tensorflow, what is the difference between a Variable and a Tensor?
38,556,078
<p>The Tensorflow documentation states that a <code>Variable</code> can be used any place a <code>Tensor</code> can be used, and they seem to be fairly interchangeable. For example, if <code>v</code> is a <code>Variable</code>, then <code>x = 1.0 + v</code> becomes a <code>Tensor</code>.</p> <p>What is the difference ...
0
2016-07-24T19:47:39Z
38,556,752
<p>It's true that a Variable can be used any place a Tensor can, but the key differences between the two are that a Variable maintains its state across multiple calls to run() and a variable's value can be updated by backpropagation (it can also be saved, restored etc as per the documentation). </p> <p>These differenc...
2
2016-07-24T21:02:48Z
[ "python", "tensorflow" ]