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 |
|---|---|---|---|---|---|---|---|---|---|
Passing a C++ pointer between C and Python | 38,825,958 | <p>I have a python extension module written in C++, which contains multiple functions. One of these generates an instance of a custom structure, which I then want to use with other functions of my module in Python as follows</p>
<pre><code>import MyModule
var = MyModule.genFunc()
MyModule.readFunc(var)
</code></pre>
... | 0 | 2016-08-08T09:45:55Z | 38,885,475 | <p>Like stated in a comment to your question, you'll run into an issue when reading data from the local variable <code>MyStruct var</code>. For this you can use the third destructor to <code>PyCapsule_New</code>.</p>
<p>But that's not the reason for your problem just now. You're using <code>PyCapsule_GetPointer(args, ... | 1 | 2016-08-11T00:20:24Z | [
"python",
"c++",
"c",
"python-c-api"
] |
Tastypie decimal and datetime filters not working | 38,826,031 | <p>The following <strong>lte</strong> and <strong>gte</strong> filter queries returns 0 objects:</p>
<pre><code>curl http://localhost/river/river/?runoff__lte=100.0&runoff__gte=150.0
curl http://localhost/river/river/?runoff__lte=100&runoff__gte=150
http://localhost/river/river/?dt_timestamp__lte=2015-01-01T03... | 0 | 2016-08-08T09:48:51Z | 38,837,149 | <p>I guess You need to select rivers where <code>runoff</code> are between 100 and 150 or <code>dt_timestamp</code> between 2015-01-01T03:00 and 2015-01-07T18:00. In this case try:</p>
<pre><code>http://localhost/river/river/?runoff__gte=100.0&runoff__lte=150.0
http://localhost/river/river/?runoff__gte=100&run... | 0 | 2016-08-08T19:32:48Z | [
"python",
"django",
"postgresql",
"tastypie"
] |
Python27 - Convert tuple time to datetime object | 38,826,071 | <p>I'm trying to get a timestamp from an email like this:</p>
<pre><code>Received: by 10.64.149.4 with SMTP id tw4csp1211013ieb;
Thu, 4 Aug 2016 07:02:01 -0700 (PDT)
</code></pre>
<p>First of all, I parse the timestamp with:</p>
<pre><code>d = email.utils.parsedate('Thu, 4 Aug 2016 07:02:01 -0700 (PDT)')
Result... | -1 | 2016-08-08T09:51:30Z | 38,826,256 | <p>Check out <a href="https://docs.python.org/2/library/calendar.html#calendar.timegm" rel="nofollow"><code>calendar.timegm</code></a> or <a href="https://docs.python.org/3/library/time.html#time.mktime" rel="nofollow"><code>time.mktime</code></a> for converting a struct_time tuple to a float. You can then use <a href=... | 1 | 2016-08-08T10:00:26Z | [
"python",
"datetime"
] |
Python27 - Convert tuple time to datetime object | 38,826,071 | <p>I'm trying to get a timestamp from an email like this:</p>
<pre><code>Received: by 10.64.149.4 with SMTP id tw4csp1211013ieb;
Thu, 4 Aug 2016 07:02:01 -0700 (PDT)
</code></pre>
<p>First of all, I parse the timestamp with:</p>
<pre><code>d = email.utils.parsedate('Thu, 4 Aug 2016 07:02:01 -0700 (PDT)')
Result... | -1 | 2016-08-08T09:51:30Z | 38,826,356 | <p>Last two items of the tuple are strange, they don't look like timezone data. But if you don't need timezone aware <code>datetime</code> object, you can do something like this <code>datetime(*d[:-2])</code></p>
| 1 | 2016-08-08T10:04:07Z | [
"python",
"datetime"
] |
Python27 - Convert tuple time to datetime object | 38,826,071 | <p>I'm trying to get a timestamp from an email like this:</p>
<pre><code>Received: by 10.64.149.4 with SMTP id tw4csp1211013ieb;
Thu, 4 Aug 2016 07:02:01 -0700 (PDT)
</code></pre>
<p>First of all, I parse the timestamp with:</p>
<pre><code>d = email.utils.parsedate('Thu, 4 Aug 2016 07:02:01 -0700 (PDT)')
Result... | -1 | 2016-08-08T09:51:30Z | 38,826,655 | <p><code>email.utils.parsedate</code> <a href="https://docs.python.org/2/library/email.util.html#email.utils.parsedate" rel="nofollow">returns a 9 tuple similar to the structure <code>struct_time</code> but with the index 6,7 and 8 unusable</a></p>
<p><a href="https://docs.python.org/2/library/time.html#time.struct_ti... | 1 | 2016-08-08T10:18:06Z | [
"python",
"datetime"
] |
Django : 'WSGIRequest' object has no attribute 'user'? - AuthenticationMiddleware & SessionAuthenticationMiddleware are in sequence | 38,826,118 | <p>Getting the following error while try to access the django admin panel.</p>
<pre><code>Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: 1.9.8
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'... | 3 | 2016-08-08T09:53:35Z | 38,994,304 | <p>change the name <code>MIDDLEWARE</code> to <code>MIDDLEWARE_CLASSES</code>.</p>
| 4 | 2016-08-17T10:38:23Z | [
"python",
"django",
"wsgi"
] |
How do I have the index of an item in a python list which exactly matches a given regular expression pattern? | 38,826,135 | <p>Suppose I have a list of string items like the following:</p>
<pre><code>lst = ['apple', 'mango', 'MIME']
p = r"MIME" # regex pattern
</code></pre>
<p>Now, I want to have the index of the item which exactly matches the pattern <code>p</code>. Clearly, the answer is <code>2</code>. How do I do it?</p>
| -2 | 2016-08-08T09:54:23Z | 38,826,305 | <p>Here is you code re module is for regular expressions</p>
<pre><code>import re
lst = ['apple', 'mango', 'MIME']
p = r"MIME" # regex pattern
for i in range(0,len(lst)):
if re.compile(p).match(lst[i]):
print i
</code></pre>
| 0 | 2016-08-08T10:02:09Z | [
"python",
"regex",
"python-3.x"
] |
How do I have the index of an item in a python list which exactly matches a given regular expression pattern? | 38,826,135 | <p>Suppose I have a list of string items like the following:</p>
<pre><code>lst = ['apple', 'mango', 'MIME']
p = r"MIME" # regex pattern
</code></pre>
<p>Now, I want to have the index of the item which exactly matches the pattern <code>p</code>. Clearly, the answer is <code>2</code>. How do I do it?</p>
| -2 | 2016-08-08T09:54:23Z | 38,826,724 | <pre><code>import re
r = re.compile(p)
try:
print(next(i for i in range(0, len(lst)) if r.match(lst[i])))
except StopIteration:
print('Not found')
</code></pre>
| 0 | 2016-08-08T10:21:50Z | [
"python",
"regex",
"python-3.x"
] |
Python-Download video from youtube and convert it to mp3 | 38,826,243 | <p>This code downloads the video and convert it to mp3 file. However, the mp3 audio will become 2 times longer than normal video. How can I solve this problem?</p>
<pre class="lang-python prettyprint-override"><code>import pafy
import os
import moviepy.editor as mp
print "[+] Welcome to Youtube downloader."
download... | 0 | 2016-08-08T09:59:39Z | 38,826,731 | <p>It's the value "clip.size" that is twice bigger than the real one, or it's the real lenght of the file ?</p>
| 0 | 2016-08-08T10:22:12Z | [
"python"
] |
Including new app causing AttributeError: 'str' object has no attribute '_meta' in Python/Django app | 38,826,246 | <p>Using Python 2.7 and Django 1.9.9 I'm getting the following error when I try in include an app I am developing within my INSTALLED_APS</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/var/www/cltc/env/local/lib/python2.... | 0 | 2016-08-08T09:59:51Z | 38,826,333 | <p>You have a typo in your declaration of the <code>through</code> attribute of Subscription.category: "SubscritptionCategory" rather than "SubscriptionCategory". Because of that, Django can't find the model you're referencing.</p>
<p>Note however that since you don't define any extra fields on that through model, the... | 1 | 2016-08-08T10:03:04Z | [
"python",
"django",
"python-2.7"
] |
How to use python-ldap to modify configuration DIT of openldap? | 38,826,302 | <p>For example, I can use the following command to change the RootDN password:</p>
<pre><code>sudo ldapmodify -H ldapi:// -Y EXTERNAL -f newpasswd.ldif
</code></pre>
<p>The contend of newpasswd.ldif is:</p>
<pre><code>dn: olcDatabase={1}mdb,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: {SSHA}/Z6e+b4L6uc... | 0 | 2016-08-08T10:02:03Z | 38,910,813 | <p>I find the solution, here is my code.</p>
<pre><code>def ldap_modify_root():
conn = ldap.initialize("ldapi://")
conn.sasl_external_bind_s()
old = {'olcRootPW': 'xxx'}
new = {'olcRootPW': '{SSHA}/Z6e+b4L6ucglrlI4KsNaX142WDCH6de'}
ldif = modlist.modifyModlist(old, new)
dn = "olcDatabase={1}mdb... | 0 | 2016-08-12T05:50:18Z | [
"python",
"openldap",
"python-ldap"
] |
Python could not open port | 38,826,334 | <p>I want to communicate with my serial port in python. I installed pyserial for linux:</p>
<pre><code>import thread
import serial
PORT = '/dev/rfcomm0'
BAUDRATE = 921600
TIMEOUT = 1
port = serial.Serial(port=PORT, baudrate=BAUDRATE, timeout=TIMEOUT)
port.open()
...
port.close()
</code></pre>
<p>It gives the follow... | 0 | 2016-08-08T10:03:05Z | 38,842,193 | <p>/dev/rfcomm0 seems a BlueZ registered virtual device port.
Can you list this device on your system? and did your Bluetooth starts well?</p>
| 0 | 2016-08-09T04:38:27Z | [
"python",
"linux",
"python-2.7",
"bluetooth"
] |
How to access request parameters from SET value of on_delete in django model | 38,826,392 | <p>I have about 10 models each of which use User as a Foreign Key. When the user is deleted, I want to set the values in each of these tables to the one who deletes the user. The users are being deleted through django admin area by authorized staff.</p>
<p>So, I guess I have to call a function and use SET of on_delet... | 2 | 2016-08-08T10:06:02Z | 38,826,751 | <p>First of all, <code>on_delete.SET</code> designed that so it will call callable without any parameters, check it's <a href="https://docs.djangoproject.com/en/dev/_modules/django/db/models/deletion/#SET" rel="nofollow">source code</a>.</p>
<p>The actual solution to your problem can be achieved in many different ways... | 2 | 2016-08-08T10:23:30Z | [
"python",
"django",
"django-models",
"django-rest-framework"
] |
How to access request parameters from SET value of on_delete in django model | 38,826,392 | <p>I have about 10 models each of which use User as a Foreign Key. When the user is deleted, I want to set the values in each of these tables to the one who deletes the user. The users are being deleted through django admin area by authorized staff.</p>
<p>So, I guess I have to call a function and use SET of on_delet... | 2 | 2016-08-08T10:06:02Z | 38,826,998 | <p>Since a staff member is deleting other users and effectively taking ownership of the objects that belongs to the deleted user the only effective solution is to override the <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.delete_model" rel="nofollow">delete_model</a> ... | 2 | 2016-08-08T10:35:08Z | [
"python",
"django",
"django-models",
"django-rest-framework"
] |
Create set and lists with the positions in the set efficently | 38,826,426 | <p>I need create a set of the IDs of some messages, and the positions in the original list. The code is used to sort the messages an later handle them according to ID. </p>
<p>The following works, is readable, but slow. </p>
<pre><code>import numpy as np
IDs=np.array([354,45,45,34,354])#example, the actual array is ... | 0 | 2016-08-08T10:08:04Z | 38,826,574 | <p>Try to use <code>defaultdict</code> and <code>enumerate</code>:</p>
<pre><code>from collections import defaultdict
Dict = defaultdict(list)
for i,id in enumerate(IDs):
Dict[id].append(i)
</code></pre>
<p>(using <code>try</code> and <code>except</code> is a bad idea <a href="http://stackoverflow.com/a/81084... | 1 | 2016-08-08T10:14:30Z | [
"python",
"dictionary"
] |
Create set and lists with the positions in the set efficently | 38,826,426 | <p>I need create a set of the IDs of some messages, and the positions in the original list. The code is used to sort the messages an later handle them according to ID. </p>
<p>The following works, is readable, but slow. </p>
<pre><code>import numpy as np
IDs=np.array([354,45,45,34,354])#example, the actual array is ... | 0 | 2016-08-08T10:08:04Z | 38,843,179 | <p>The fastest code I came up with, is this. It does much more math, is not as readable, and I am not proud, but it is a lot quicker (even with large arrays):</p>
<pre><code> Sorted_positions_of_IDs=np.argsort(IDs,kind='mergesort')
SortedIDs=IDs[Sorted_positions_of_IDs]
Position=0
Position_last=-1
... | 0 | 2016-08-09T06:04:23Z | [
"python",
"dictionary"
] |
How to convert certain categorical values from a DataFrame to numerical(int) in python? | 38,826,468 | <p>I have a dataframe with multiple columns and categorical data in it which I want to assign a numerical (int) value in order to proceed with the data clean-up I need to do.</p>
<p>e.g. I want the cells in the column OldValue & NewValue containing "1st Call" to have a value of 2, "2nd Call" to have a value of 3, ... | -1 | 2016-08-08T10:09:49Z | 38,826,810 | <p>You may use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow">replace</a> and passing a dictinary which maps each category on a numerical value and then add the new column to your DataFrame:</p>
<pre><code>df['OldValueInt'] = df['OldValue'].replace( {'1st C... | 0 | 2016-08-08T10:26:33Z | [
"python",
"dataframe",
"converter"
] |
Use of Dictonary in python | 38,826,477 | <p>I am doing a Coursera python exercise and having trouble writing my code.</p>
<p>The question is as following:</p>
<p>Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines... | -3 | 2016-08-08T10:10:13Z | 38,826,798 | <p>Here is the code you need, you're not storing the words2 output in the list, and as mentioned in the comments you're recursing the file in a wrong manner too. </p>
<p>Hope this will help you.</p>
<pre><code>name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
name="mbox-short.txt"
handle=o... | 0 | 2016-08-08T10:25:49Z | [
"python",
"python-2.7",
"python-3.x",
"dictionary"
] |
Python Xarray add DataArray to Dataset | 38,826,505 | <p>Very simple question but I can't find the answer online. I have a <code>Dataset</code> and I just want to add a named <code>DataArray</code> to it. Something like <code>dataset.add({"new_array": new_data_array})</code>. I know about <code>merge</code> and <code>update</code> and <code>concatenate</code>, but my unde... | 0 | 2016-08-08T10:11:17Z | 38,826,718 | <p>OK I found one way to do it but I don't know if this is the canonical way or the best way, so please criticise and advise. It doesn't feel like a good way of doing it.</p>
<pre><code>dataset = xarray.merge([dataset, new_data_array.rename("new_array")])
</code></pre>
| 0 | 2016-08-08T10:21:40Z | [
"python",
"python-xarray"
] |
Python Xarray add DataArray to Dataset | 38,826,505 | <p>Very simple question but I can't find the answer online. I have a <code>Dataset</code> and I just want to add a named <code>DataArray</code> to it. Something like <code>dataset.add({"new_array": new_data_array})</code>. I know about <code>merge</code> and <code>update</code> and <code>concatenate</code>, but my unde... | 0 | 2016-08-08T10:11:17Z | 38,833,440 | <p>You need to make sure that the dimensions of your new DataArray are the same as in your dataset. Then the following should work:</p>
<pre><code>dataset['new_array_name'] = new_array
</code></pre>
<p>Here is a complete example to try it out:</p>
<pre><code># Create some dimensions
x = np.linspace(-10,10,10)
y = np... | 2 | 2016-08-08T15:42:40Z | [
"python",
"python-xarray"
] |
Python Xarray add DataArray to Dataset | 38,826,505 | <p>Very simple question but I can't find the answer online. I have a <code>Dataset</code> and I just want to add a named <code>DataArray</code> to it. Something like <code>dataset.add({"new_array": new_data_array})</code>. I know about <code>merge</code> and <code>update</code> and <code>concatenate</code>, but my unde... | 0 | 2016-08-08T10:11:17Z | 39,049,786 | <p>Thanks to your detailed report, this issue has now been fixed in the latest release of xarray (v0.8.2).</p>
<p>We fixed the behavior in two ways:</p>
<ol>
<li><p>Alignment operations between xarray objects now succeed even with non-unique indexes, as long as the non-unique indexes take on identical values on all o... | 2 | 2016-08-20T02:05:15Z | [
"python",
"python-xarray"
] |
Check for letter after a substring | 38,826,710 | <p>I'm trying to find a way to check for a letter after a sub-string. I have searched for it both on the internet and google. So if the sub-string is: <code>sub</code>, and the text is: <code>substrings are cool</code>, it should return <code>True</code> and if the text is: <code>sub dafdgnjgf</code> it should return <... | -1 | 2016-08-08T10:21:14Z | 38,827,072 | <p>If you're looking for <em>any</em> valid letter after a given sub-string, you can first find the position of that sub-string inside the string with <code>str.find</code>, then check if the index after the sub-string matches <code>ascii_letters</code> from <code>string</code>:</p>
<pre><code>from string import ascii... | 3 | 2016-08-08T10:38:45Z | [
"python",
"string",
"python-3.x"
] |
Check for letter after a substring | 38,826,710 | <p>I'm trying to find a way to check for a letter after a sub-string. I have searched for it both on the internet and google. So if the sub-string is: <code>sub</code>, and the text is: <code>substrings are cool</code>, it should return <code>True</code> and if the text is: <code>sub dafdgnjgf</code> it should return <... | -1 | 2016-08-08T10:21:14Z | 38,827,436 | <p>You could use a <a href="https://docs.python.org/3/library/re.html" rel="nofollow">regular expression</a> with the substring as a lookbehind, matching a character:</p>
<pre><code>>>> p = re.compile(r"(?<=sub)([a-zA-Z])")
>>> p.search("substrings are cool")
<_sre.SRE_Match at 0x7f3a50dbc300&g... | 1 | 2016-08-08T10:57:42Z | [
"python",
"string",
"python-3.x"
] |
parameters constraint in numpy lstsq | 38,826,726 | <p>I'm fitting a set of data with <code>numpy.lstsq()</code>:</p>
<pre><code>numpy.linalg.lstsq(a,b)[0]
</code></pre>
<p>returns something like:</p>
<pre><code>array([ -0.02179386, 0.08898451, -0.17298247, 0.89314904])
</code></pre>
<p>Note the fitting solution is a mix of positive and negative float.</p>
<p>Un... | 2 | 2016-08-08T10:21:59Z | 38,828,588 | <p><em>Non-negative least squares</em> is implemented in <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.nnls.html" rel="nofollow"><code>scipy.optimize.nnls</code></a>.</p>
<pre><code>from scipy.optimize import nnls
solution = nnls(a, b)[0]
</code></pre>
| 1 | 2016-08-08T11:55:34Z | [
"python",
"numpy"
] |
How to refer to types in Python? | 38,826,791 | <p>I know how to refer to some types, i.e. <code>str</code> for <code>type('')</code>, <code>int</code> for <code>type(1)</code> etc. But what about other types, such as <code>type(lambda: None)</code>?</p>
<p>I know to refer to it as <code>type(f) == type(lambda: None)</code> for comparison, but, is there any other w... | -2 | 2016-08-08T10:25:24Z | 38,826,916 | <p>If you want to test if a certain value is <em>a lambda</em>:</p>
<pre><code>import types
foo = lambda: None
print(isinstance(foo, types.LambdaType))
</code></pre>
<p>See <a href="https://docs.python.org/3/library/types.html" rel="nofollow">https://docs.python.org/3/library/types.html</a>.</p>
<p>You usually use ... | 2 | 2016-08-08T10:31:30Z | [
"python",
"types"
] |
How to refer to types in Python? | 38,826,791 | <p>I know how to refer to some types, i.e. <code>str</code> for <code>type('')</code>, <code>int</code> for <code>type(1)</code> etc. But what about other types, such as <code>type(lambda: None)</code>?</p>
<p>I know to refer to it as <code>type(f) == type(lambda: None)</code> for comparison, but, is there any other w... | -2 | 2016-08-08T10:25:24Z | 38,826,919 | <p>To get the type of various builtin types in Python 2, you can use the <code>types</code> module.</p>
<pre><code>import types
l = lambda: 0
function_type = types.FunctionType
if isinstance(l, function_type):
do_stuff()
</code></pre>
| 1 | 2016-08-08T10:31:38Z | [
"python",
"types"
] |
How to refer to types in Python? | 38,826,791 | <p>I know how to refer to some types, i.e. <code>str</code> for <code>type('')</code>, <code>int</code> for <code>type(1)</code> etc. But what about other types, such as <code>type(lambda: None)</code>?</p>
<p>I know to refer to it as <code>type(f) == type(lambda: None)</code> for comparison, but, is there any other w... | -2 | 2016-08-08T10:25:24Z | 38,827,555 | <p>Checking if something is a function is different to checking if it is a callable.
Most likely you want to check if the object is callable (can I use this object like a function?). </p>
<p>A function is one of several types of callable. They are:</p>
<ol>
<li>Pure python functions</li>
<li>Methods</li>
<li>Classes ... | 1 | 2016-08-08T11:02:51Z | [
"python",
"types"
] |
how to get a folder name and file name in python | 38,827,110 | <p>I have a python program named <code>myscript.py</code> which would give me the list of files and folders in the path provided.</p>
<pre><code>import os
import sys
def get_files_in_directory(path):
for root, dirs, files in os.walk(path):
print(root)
print(dirs)
print(files)
path=sys.argv... | 0 | 2016-08-08T10:40:36Z | 38,827,188 | <p>You could try using the <code>glob</code> module instead:</p>
<pre><code>import glob
glob.glob('D:\Python\Test\D1\*\*\*.bat')
</code></pre>
<p>Or, to just get the filenames</p>
<pre><code>import os
import glob
[os.path.basename(x) for x in glob.glob('D:\Python\Test\D1\*\*\*.bat')]
</code></pre>
| 1 | 2016-08-08T10:45:41Z | [
"python",
"python-3.x",
"path"
] |
how to get a folder name and file name in python | 38,827,110 | <p>I have a python program named <code>myscript.py</code> which would give me the list of files and folders in the path provided.</p>
<pre><code>import os
import sys
def get_files_in_directory(path):
for root, dirs, files in os.walk(path):
print(root)
print(dirs)
print(files)
path=sys.argv... | 0 | 2016-08-08T10:40:36Z | 38,829,770 | <p>To get what you want, you could do the following:</p>
<pre><code>def get_files_in_directory(path):
# Get the root dir (in your case: test)
rootDir = path.split('\\')[-1]
# Walk through all subfolder/files
for root, subfolder, fileList in os.walk(path):
for file in fileList:
# Sk... | 0 | 2016-08-08T12:53:54Z | [
"python",
"python-3.x",
"path"
] |
Pandas dataframe generate column with different row info, but no apply function | 38,827,141 | <p>maybe question name is not accurate (sorry for that because I don't find any accurate word to describe my question...), let me make an example:</p>
<p>The following dataframe is income with "week_id" and "user_id":</p>
<pre><code>week_id user income
1 1 100
1 2 50
2 1 200
2 2... | 1 | 2016-08-08T10:42:34Z | 38,827,173 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.shift.html" rel="nofollow"><code>DataFrameGroupBy.shift</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a>... | 0 | 2016-08-08T10:45:10Z | [
"python",
"pandas"
] |
How to use TensorFlow reader and queue to read two file at same time? | 38,827,264 | <p>My training set contains two kinds of file: training image with file name like "1.png" and label file with name like "1.label.txt".</p>
<p>I found some usage of Queue and Reader in tutorials like this:
</p>
<pre><code>filename_queue = tf.train.string_input_producer(filenames)
result.key, value = reader.read(filena... | 0 | 2016-08-08T10:50:14Z | 38,870,337 | <p><em>I have figured out the solution to my problem. I would like post answer here instead of delete my question, hoping this will help people who is new to TensorFlow.</em></p>
<p>The answer contains two parts:</p>
<h1>Part 1: How to read files pair by pair using TensorFlow's queue</h1>
<p>The solution is simple:<... | 0 | 2016-08-10T10:08:58Z | [
"python",
"tensorflow"
] |
Why does pandas.Dataframe.drop() returns None? | 38,827,316 | <p>Here in my code I read the data from CSV:</p>
<pre><code>data = pandas.read_csv('dataset/job_functions.csv', names=["job","category"] ,skiprows=1).dropna().reindex()
num_jobs = data["job"].size
</code></pre>
<p>Then I want to drop the rows which 'category' label does not equal to <code>i</code>:</p>
<pre><code>da... | 0 | 2016-08-08T10:52:39Z | 38,827,860 | <p>It looks like need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>import pandas as pd
data = pd.DataFrame({'category':['a','b', 'c']})
print (data)
category
0 a
1 b
2 c
i = 'a'
print (data... | 0 | 2016-08-08T11:17:46Z | [
"python",
"pandas",
"dataframe"
] |
Python ctypes.BigEndianStructure can't store a value | 38,827,440 | <p>I am in trouble with ctypes.BigEndianStructure. I can't get the value that I set to one the fields. My code is like this.</p>
<pre><code>import ctypes
class MyStructure(ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = [
('fx', ctypes.c_uint, 7),
('fy', ctypes.c_ubyte, 1)
]
x = MyStruct... | 2 | 2016-08-08T10:57:53Z | 38,827,971 | <p>I don't know why what your doing doesn't work and it is certainly strange behavior. I think this alternative code works.</p>
<pre><code>import ctypes
class MyStructure(ctypes.BigEndianStructure):
_pack_ = 1
def __init__(self):
self.fx=ctypes.c_uint(7)
self.fy = ctypes.c_ubyte(1)
x = MyStruc... | -1 | 2016-08-08T11:23:17Z | [
"python",
"structure",
"ctypes"
] |
How to fetch resultant of a POST request in a web-scrapper? | 38,827,476 | <p>I am trying to scrape out data from <a href="http://ngo.india.gov.in/sector_ngolist_ngo.php?psid=&records=" rel="nofollow">this website.</a> </p>
<p>There is a table in which there are different organisations listed and the name each organisation is a link to a webpage with more information about the organisati... | 0 | 2016-08-08T10:59:34Z | 38,829,861 | <p>First, the javascript will not be executed <em>server side</em> but always client side. Here, you should simply use the debugging facilities or a browser (Firefox function F12 is enough) to see what happens when you click on one of the links. You immediately see that the javascript code only prepares and send a POST... | 0 | 2016-08-08T12:58:22Z | [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup"
] |
Detecting colored circle and it's center using OpenCV | 38,827,505 | <p>I am trying to detect BLUE colored CIRCLE and it's CENTER. Then draw a circle on the detected circle and a very small circle on it's center. But I get a few errors. (I am using OpenCV 3.1.0, Python 2.7 Anaconda 64 bits, PyCharm as an IDE) (Please help me using python codes)
I run the following code:</p>
<pre><code>... | 1 | 2016-08-08T11:00:47Z | 38,831,028 | <p>Change <code>frame, _ = cap.read()</code> to <code>ret,frame = cap.read()</code></p>
<pre><code>import cv2
import numpy as np
cap = cv2.VideoCapture(0)
if cap.isOpened():
while(True):
ret,frame= cap.read()
# blurring the frame that's captured
frame_gau_blur = cv2.GaussianBlur(frame, (3, 3), 0)
# co... | 0 | 2016-08-08T13:52:10Z | [
"python",
"python-2.7",
"opencv",
"computer-vision",
"opencv3.1"
] |
Detecting colored circle and it's center using OpenCV | 38,827,505 | <p>I am trying to detect BLUE colored CIRCLE and it's CENTER. Then draw a circle on the detected circle and a very small circle on it's center. But I get a few errors. (I am using OpenCV 3.1.0, Python 2.7 Anaconda 64 bits, PyCharm as an IDE) (Please help me using python codes)
I run the following code:</p>
<pre><code>... | 1 | 2016-08-08T11:00:47Z | 38,873,062 | <p>I have solved the my problem and after looking up the meanings of the errors online (the one's that I got), I was able to find the solutions for them and hence I was able to solve them. If you run the following code given below you should be able to detect blue circles pretty well. Thanks a lot to the people who tri... | 1 | 2016-08-10T12:09:10Z | [
"python",
"python-2.7",
"opencv",
"computer-vision",
"opencv3.1"
] |
How to limit memory usage ofPython _ pandas | 38,827,526 | <p>Currently am using a panda operation to merge two csv file It take around 4.6 gb RAM i want to limit the RAM usage by 2 gb like java -Xmax and -Xmin</p>
<p>is their any way to do so</p>
<p>Thanks in advance</p>
| -2 | 2016-08-08T11:01:35Z | 38,827,634 | <p>Use <a href="https://docs.python.org/2/library/resource.html#resource.setrlimit" rel="nofollow"><code>setrlimit</code></a>:</p>
<pre><code>import resource
rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
print 'Soft limit starts as :', soft
resource.setrlimit(rsrc, (1024, hard)) #limit to one ki... | 2 | 2016-08-08T11:06:47Z | [
"python",
"pandas"
] |
Get list_display in django admin to display the 'many' end of a many-to-one relationship | 38,827,608 | <p>I would like to display all pet owners (Clients) using list_display and for each owner a comma-separate list of all of their pets (Patients).</p>
<p>The foreign key is in the Patient table, such that an owner can have many pets, but a pet can only have one owner.</p>
<p>I've got the following to work but would lik... | 0 | 2016-08-08T11:05:09Z | 38,827,864 | <p>if it works :+1: !!</p>
<p>few notes however: it will execute one query for each Client, so if you display 100 clients on the admin, django will execute 100 queries</p>
<p>You could maybe improve it by changing the main queryset (<a href="https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admi... | 2 | 2016-08-08T11:17:56Z | [
"python",
"django",
"python-3.x",
"django-admin"
] |
Get list_display in django admin to display the 'many' end of a many-to-one relationship | 38,827,608 | <p>I would like to display all pet owners (Clients) using list_display and for each owner a comma-separate list of all of their pets (Patients).</p>
<p>The foreign key is in the Patient table, such that an owner can have many pets, but a pet can only have one owner.</p>
<p>I've got the following to work but would lik... | 0 | 2016-08-08T11:05:09Z | 38,828,289 | <pre><code>def patients(self,obj):
p = obj.patients.all()
return list(p)
</code></pre>
<p>this is assuming that in your ForeignKey you set <code>related_name='patients'</code></p>
<p>EDIT: fixed mistake
EDIT2: changed reverse_name to related_name and added '.all()'</p>
| 0 | 2016-08-08T11:39:37Z | [
"python",
"django",
"python-3.x",
"django-admin"
] |
Get list_display in django admin to display the 'many' end of a many-to-one relationship | 38,827,608 | <p>I would like to display all pet owners (Clients) using list_display and for each owner a comma-separate list of all of their pets (Patients).</p>
<p>The foreign key is in the Patient table, such that an owner can have many pets, but a pet can only have one owner.</p>
<p>I've got the following to work but would lik... | 0 | 2016-08-08T11:05:09Z | 38,917,120 | <p>This now works:</p>
<pre><code>class ClientAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'mobile', 'get_patients')
def get_queryset(self, obj):
qs = super(ClientAdmin, self).get_queryset(obj)
return qs.prefetch_related('patient_fk')
def get_patients(self, obj):
... | 0 | 2016-08-12T11:41:27Z | [
"python",
"django",
"python-3.x",
"django-admin"
] |
How to read only number from a specific line using python script | 38,827,657 | <p>How to read only number from a specific line using python script for example </p>
<p>"1009 run test jobs" here i should read only number "1009" instead of "1009 run test jobs"</p>
| -1 | 2016-08-08T11:07:43Z | 38,827,760 | <p>a simple regexp should do:</p>
<pre><code>import re
match = re.match(r"(\d+)", "1009 run test jobs")
if match:
number = match.group()
</code></pre>
<p><a href="https://docs.python.org/3/library/re.html" rel="nofollow">https://docs.python.org/3/library/re.html</a></p>
| 0 | 2016-08-08T11:12:29Z | [
"python"
] |
How to read only number from a specific line using python script | 38,827,657 | <p>How to read only number from a specific line using python script for example </p>
<p>"1009 run test jobs" here i should read only number "1009" instead of "1009 run test jobs"</p>
| -1 | 2016-08-08T11:07:43Z | 38,827,778 | <p>Use regular expression:</p>
<pre><code>>>> import re
>>> x = "1009 run test jobs"
>>> re.sub("[^0-9]","",x)
>>> re.sub("\D","",x) #better way
</code></pre>
| 1 | 2016-08-08T11:13:41Z | [
"python"
] |
How to read only number from a specific line using python script | 38,827,657 | <p>How to read only number from a specific line using python script for example </p>
<p>"1009 run test jobs" here i should read only number "1009" instead of "1009 run test jobs"</p>
| -1 | 2016-08-08T11:07:43Z | 38,827,794 | <p>Or this if your number always comes first <code>int(line.split()[0])</code></p>
| 0 | 2016-08-08T11:14:20Z | [
"python"
] |
How to read only number from a specific line using python script | 38,827,657 | <p>How to read only number from a specific line using python script for example </p>
<p>"1009 run test jobs" here i should read only number "1009" instead of "1009 run test jobs"</p>
| -1 | 2016-08-08T11:07:43Z | 38,827,849 | <p>Or a simple check if its numbers in a string.</p>
<p><code>[int(s) for s in str.split() if s.isdigit()]</code></p>
<p>Where str is your string of text.</p>
| 0 | 2016-08-08T11:17:00Z | [
"python"
] |
How to read only number from a specific line using python script | 38,827,657 | <p>How to read only number from a specific line using python script for example </p>
<p>"1009 run test jobs" here i should read only number "1009" instead of "1009 run test jobs"</p>
| -1 | 2016-08-08T11:07:43Z | 38,827,880 | <p>Pretty sure there is a "more pythonic" way, but this works for me:</p>
<pre><code>s='teststri3k2k3s21k'
outs=''
for i in s:
try:
numbr = int(i)
outs+=i
except:
pass
print(outs)
</code></pre>
<p>If the number is always at the beginning of your string, you might consider something lik... | 0 | 2016-08-08T11:18:41Z | [
"python"
] |
How to read only number from a specific line using python script | 38,827,657 | <p>How to read only number from a specific line using python script for example </p>
<p>"1009 run test jobs" here i should read only number "1009" instead of "1009 run test jobs"</p>
| -1 | 2016-08-08T11:07:43Z | 38,828,188 | <p>You can do it with regular expression. That's very easy:</p>
<pre><code>import re
regularExpression = "[^\d-]*(-?[0-9]+).*"
line = "some text -123 some text"
m = re.search(regularExpression, line)
if m:
print(m.groups()[0])
</code></pre>
<p>This regular expression extracts the first number in a text. It consid... | 0 | 2016-08-08T11:34:23Z | [
"python"
] |
accessing python dictionary from bash script | 38,827,679 | <p>I am invoking the bash script from python script.</p>
<p>I want the bash script to add an element to dictionary "d" in the python script</p>
<h2><code>abc3.sh</code>:</h2>
<pre><code>#!/bin/bash
rank=1
echo "plugin"
function reg()
{
if [ "$1" == "what" ]; then
python -c 'from framework import data;d... | 0 | 2016-08-08T11:09:00Z | 38,828,116 | <p>If I understand correctly, you have a python script that runs a shell script, that in turn runs a new python script. And you'd want the second Python script to update a dictionnary in the first script. That will not work like that. </p>
<p>When you run your first python script, it will create a new python process, ... | 2 | 2016-08-08T11:30:44Z | [
"python",
"bash"
] |
accessing python dictionary from bash script | 38,827,679 | <p>I am invoking the bash script from python script.</p>
<p>I want the bash script to add an element to dictionary "d" in the python script</p>
<h2><code>abc3.sh</code>:</h2>
<pre><code>#!/bin/bash
rank=1
echo "plugin"
function reg()
{
if [ "$1" == "what" ]; then
python -c 'from framework import data;d... | 0 | 2016-08-08T11:09:00Z | 38,829,773 | <p>Let's suppose that you have a shell plugin that echoes the value:</p>
<pre><code>echo $1 12
</code></pre>
<p>The mockup python script looks like (I'm on windows/MSYS2 BTW, hence the strange paths for a Linux user):</p>
<pre><code>import subprocess
p = subprocess.Popen(args=[r'C:\msys64\usr\bin\sh.exe',"-c","C:/u... | 0 | 2016-08-08T12:54:08Z | [
"python",
"bash"
] |
How to update a dataframe in Pandas Python | 38,827,835 | <p>I have the following two dataframes in pandas:</p>
<pre><code>DF1:
AuthorID1 AuthorID2 Co-Authored
A1 A2 0
A1 A3 0
A1 A4 0
A2 A3 0
DF2:
AuthorID1 AuthorID2 Co-Authored
A1 A2 5
A2 A3 6
A6 A7 9
</code>... | 1 | 2016-08-08T11:16:36Z | 38,827,938 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.update.html" rel="nofollow"><code>update</code></a>:</p>
<pre><code>df1.update(df2)
print (df1)
AuthorID1 AuthorID2 Co-Authored
0 A1 A2 5.0
1 A2 A3 6.0
2 A1 A4 ... | 1 | 2016-08-08T11:21:55Z | [
"python",
"pandas",
"dataframe"
] |
Manipulating Azure storage containers in a Djano project | 38,827,843 | <p>In a Django project, I'm uploading video files to an Azure storage via the following snippet:</p>
<pre><code>content_str = content.read()
blob_service.put_blob(
'videos',
name,
content_str,
x_ms_blob_type='BlockBlob',
x_ms_blob_content_type=content_type,
... | 0 | 2016-08-08T11:16:49Z | 38,827,950 | <blockquote>
<p>How do I upload the video files without specifying a container, i.e.
de facto creating a unique container for every file I upload?</p>
</blockquote>
<p>Each blob (a video file in your case) must belong to a container. So what you could do is create a container using <code>blob_service.create_contai... | 0 | 2016-08-08T11:22:28Z | [
"python",
"azure",
"windows-azure-storage",
"azure-storage-blobs"
] |
kivy: __init__() is missing x required positional arguments | 38,827,858 | <p>I have the class Movie as follows:</p>
<pre><code>class Movie(Widget):
def __init__(self, title, image, time, description, trailer, fsk, threeD, **kwargs):
super(Movie, self).__init__(title, image, time, description, trailer, fsk, threeD, **kwargs)
title = StringProperty()
image = String... | 0 | 2016-08-08T11:17:45Z | 38,911,620 | <p>I've found out that the kv-lang-file was the reason for this object initialization error. So I don't know how to fix it but I think that is an other question as this is about why <code>__init__</code> is being called</p>
| -1 | 2016-08-12T06:49:39Z | [
"python",
"python-3.x",
"kivy"
] |
Finding the input dependencies of a functions outputs | 38,827,921 | <p>I've been working on a python program with pycparser which is supposed to generate a JSON-file with dependencies of a given function and its outputs.
For an example function:</p>
<pre><code>int Test(int testInput)
{
int b = testInput;
return b;
}
</code></pre>
<p>Here I would expect <strong>b</strong> to b... | 0 | 2016-08-08T11:20:43Z | 38,828,618 | <p>You need data flow analysis of your code, and then you want to follow the data flow backwards from a result to its sources, up to some stopping point (in your case, you stopped at a function parameter but you probably also want to stop at any global variable).</p>
<p>This is called <a href="http://en.wikipedia.org/... | 1 | 2016-08-08T11:57:11Z | [
"python",
"c",
"static-analysis",
"control-flow-graph",
"pycparser"
] |
Python Terminal unexpected character after line continuation character | 38,827,949 | <p>I have a file isqrt.py, containing following code:</p>
<pre><code> from cmath import sqrt
x = -1
y = sqrt(x)
print(y)
</code></pre>
<p>I am getting following error in my Mac Terminal:</p>
<pre><code>File "isqrt.py", line 1
{\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf210
... | -1 | 2016-08-08T11:22:28Z | 38,828,040 | <p>Might be a bad idea to start with non-defined expressions, since the square-root of a negative number is not defined (at least when using real numbers).</p>
<p>What happens if you calculate the square-root of a positive number?</p>
| 0 | 2016-08-08T11:27:10Z | [
"python"
] |
Python Terminal unexpected character after line continuation character | 38,827,949 | <p>I have a file isqrt.py, containing following code:</p>
<pre><code> from cmath import sqrt
x = -1
y = sqrt(x)
print(y)
</code></pre>
<p>I am getting following error in my Mac Terminal:</p>
<pre><code>File "isqrt.py", line 1
{\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf210
... | -1 | 2016-08-08T11:22:28Z | 38,828,091 | <p>Your error is showing you that the file you're running is not what you think it is; it's got a whole load of control characters. Seems like you've saved a file as RTF rather than plain text. Ideally, you should use a proper text editor to write Python code.</p>
| 4 | 2016-08-08T11:29:27Z | [
"python"
] |
Django MissingFileError: Path is a directory | 38,827,960 | <p>I'm trying to deploy my project static files on S3 AWS but when i collectstatic on my terminal, i got this error. I heard that it looks like you i'm trying to include a static asset in my template, but i have specified a directory instead of a file... and i do not understand this :/</p>
<pre><code>Traceback (most r... | -1 | 2016-08-08T11:22:49Z | 38,828,847 | <p>If you use only <code>django-storages</code> you'll need to specify </p>
<pre><code>DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
</code></pre>
<p>instead <code>STATICFILES_STORAGE</code></p>
| 0 | 2016-08-08T12:09:15Z | [
"python",
"django",
"amazon-web-services",
"amazon-s3"
] |
Django MissingFileError: Path is a directory | 38,827,960 | <p>I'm trying to deploy my project static files on S3 AWS but when i collectstatic on my terminal, i got this error. I heard that it looks like you i'm trying to include a static asset in my template, but i have specified a directory instead of a file... and i do not understand this :/</p>
<pre><code>Traceback (most r... | -1 | 2016-08-08T11:22:49Z | 38,832,242 | <p>That error is from WhiteNoise, but you don't need to use WhiteNoise if you're serving your static files from S3. You should remove the WhiteNoise references from your <code>wsgi.py</code> file.</p>
| 1 | 2016-08-08T14:46:12Z | [
"python",
"django",
"amazon-web-services",
"amazon-s3"
] |
Passing variable into MySQL using Python 2.7 | 38,827,994 | <p>I've been trying to insert a string value from a variable in Python 2.7 into a MySQL statement.
I can't seem to get it to work, could someone point me in the right direction?</p>
<pre><code>import MySQLdb
country_name = raw_input("Which country would you like?\n")
dbh = MySQLdb.connect(host="localhost",
... | 0 | 2016-08-08T11:24:16Z | 38,842,518 | <p>Try this </p>
<pre><code>cursor.execute("SELECT name, population FROM world where name = %s", [country_name])
</code></pre>
| 1 | 2016-08-09T05:10:41Z | [
"python",
"mysql",
"python-2.7"
] |
Python grammar end "return outside function" | 38,828,017 | <p>I've noticed that Python grammar allows return statement appear outside function, but I really don't understand, why? I believe that one can specify grammar so, that this wouldn't be allowed.</p>
<p>This is a piece of Python grammar which allows this:</p>
<pre><code>single_input: NEWLINE | simple_stmt | compound_s... | 2 | 2016-08-08T11:25:37Z | 38,828,722 | <p>First, the interrupter builds the AST tree. Then, When it generates code for basic blocks by visiting the AST tree, It verifies that the return statement is inside a function.</p>
<pre><code>compiler_visit_stmt(struct compiler *c, stmt_ty s)
...
switch (s->kind) {
...
case Return_kind:
... | 4 | 2016-08-08T12:03:07Z | [
"python",
"parsing",
"ebnf"
] |
An efficient way to save parsed XML content to Django Model | 38,828,108 | <p>This is my first question so I will do my best to conform to the question guidelines. I'm also learning how to code so please ELI5.</p>
<p>I'm working on a django project that parses XML to django models. Specifically Podcast XMLs. </p>
<p>I currently have this code in my model:</p>
<pre><code> from django.db ... | 0 | 2016-08-08T11:30:24Z | 38,828,170 | <p>If you don't want it run every time, don't put it in models.py. The only thing that belongs there are the model definitions themselves.</p>
<p>Stuff that happens in response to a user action on the site goes in a view. Or, if you want this to be done from the admin site, it should go in the admin.py file.</p>
| 0 | 2016-08-08T11:33:26Z | [
"python",
"xml",
"django",
"django-models",
"xml-parsing"
] |
Spark cartesian product | 38,828,139 | <p>I have to compare coordinates in order to get the distance. Therefor i load the data with sc.textFile() and make a cartesian product. There are about 2.000.000 lines in the textfile thus 2.000.000 x 2.000.000 to be compared coordinates.</p>
<p>I tested the code with about 2.000 coordinates and it worked fine within... | 0 | 2016-08-08T11:31:48Z | 38,831,748 | <p>You used <code>data.collect()</code> in your code which basically calls all data into one machine. Depending on the memory on that machine, 2,000,000 lines of data might not fit very well.</p>
<p>Also, I tried to reduce the number of computations to be done by doing joins instead of using <code>cartesian</code>. (P... | 1 | 2016-08-08T14:23:02Z | [
"python",
"apache-spark",
"cartesian-product"
] |
How to find polygon vertices from edge detection images? | 38,828,143 | <p><strong>1. The problem</strong></p>
<p>Given the images of a house roof, I am trying to find the contours of the roofs. I have labelled data available (as polygon vertices) which I interpolate and create the truth image which is shown below
<a href="http://i.stack.imgur.com/OhNKI.png" rel="nofollow"><img src="http... | 0 | 2016-08-08T11:31:58Z | 38,834,390 | <p>I think <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/feature_detection.html#houghlinesp" rel="nofollow">HoughLinesP</a> will help you in your goal. It will find line segments and output them in a vector <code>[x1,y1,x2,y2]</code> where (x,y) pairs represent the start and endpoints of line segments.</p>
<... | 1 | 2016-08-08T16:36:47Z | [
"python",
"numpy",
"image-processing",
"signal-processing",
"skimage"
] |
How to select a group of minimum values out of a numpy array? | 38,828,180 | <p><code>fitVec = np.zeros((100, 2))</code> #Initializing the fitVec, where first column` will be the indices and second column will contain the values</p>
<p>After Initialization, fitVec gets assigned some values by running a function.
Final fitVec values:</p>
<pre><code>fitVec [[ 2.00000000e+01 2.42733444e+10]
... | 0 | 2016-08-08T11:33:57Z | 39,816,949 | <p>First off, I'd separate indices and values; no need to store them both as <code>float</code>. After that, <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow"><code>numpy.argsort</code></a> is your friend:</p>
<pre><code>import numpy
idx = numpy.arange(20, 38, dtype=int)... | 1 | 2016-10-02T12:22:13Z | [
"python",
"numpy"
] |
Select multiple sections of rows by index in pandas | 38,828,331 | <p>I have large DataFrame with GPS path and some attributes. A few sections of the path are those which I need to analyse. I would like to subset only those sections to a new DataFrame. I can subset one section at the time but the idea is to have them all and to have an original index.</p>
<p>The problem is similar to... | 1 | 2016-08-08T11:42:05Z | 38,828,421 | <p>One possible solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p>
<pre><code>cdf = pd.concat([df.loc[11:13], df.loc[17:20]])
print (cdf)
A B
11 1 b
12 2 c
13 3 d
17 7 h
18 8 i
19 9 j
</code></pre>
<p>Another so... | 3 | 2016-08-08T11:46:59Z | [
"python",
"pandas",
"slice"
] |
Select multiple sections of rows by index in pandas | 38,828,331 | <p>I have large DataFrame with GPS path and some attributes. A few sections of the path are those which I need to analyse. I would like to subset only those sections to a new DataFrame. I can subset one section at the time but the idea is to have them all and to have an original index.</p>
<p>The problem is similar to... | 1 | 2016-08-08T11:42:05Z | 38,828,498 | <p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="nofollow"><code>np.r_</code></a> to concatenate the slices:</p>
<pre><code>In [16]: df.loc[np.r_[11:13, 17:20]]
Out[16]:
A B
11 1 b
12 2 c
17 7 h
18 8 i
19 9 j
</code></pre>
<p>Note, however, that
<code>... | 3 | 2016-08-08T11:51:11Z | [
"python",
"pandas",
"slice"
] |
Django says that table doesn't exist while it does | 38,828,394 | <p>My ultimate goal is to deploy Django application on new server and all I have is raw image of disk of the old server. I have everything set up on the new server: uwsgi, python, mysql, django etc. But let's get to my problem: when I run </p>
<pre><code>uwsgi --http :8001 --module propotolki.wsgi
</code></pre>
<p>It... | 0 | 2016-08-08T11:45:36Z | 38,828,450 | <p>How did your table names end up with a '.' in them? It's a special character.</p>
<pre><code>| propotolki.django_content_type |
| propotolki.middleware_redirecthandler |
</code></pre>
<p>Try:</p>
<pre><code>ALTER TABLE `propotolki.middleware_redirecthandler` RENAME TO middleware_redirecthandler
</code></pr... | 1 | 2016-08-08T11:48:33Z | [
"python",
"mysql",
"django",
"python-2.7",
"uwsgi"
] |
random module's randrange not working in pygame | 38,828,460 | <p>I am trying to make a game in pygame and want to add apples at random places but the random module is not working. I tried looking online but the guy there was able to use this without any problem
<strong>My code and The output is down below</strong> </p>
<pre><code>impoort pygame
imporrt random
pygame.init()
dis... | -5 | 2016-08-08T11:49:11Z | 38,828,617 | <ol>
<li><p>Next time write your code and errors directly in your question body, not as a screenshot.</p></li>
<li><p>You must have assigned <code>random</code> to a tuple somewhere between <code>import random</code> to the lines you posted.</p></li>
</ol>
| 1 | 2016-08-08T11:57:08Z | [
"python",
"random",
"pygame"
] |
Python threading interrupt sleep | 38,828,578 | <p>Is there a way in python to interrupt a thread when it's sleeping?
(As we can do in java)</p>
<p>I am looking for something like that.</p>
<pre><code> import threading
from time import sleep
def f():
print('started')
try:
sleep(100)
print('finished')
except SleepInterruptedException:
... | 0 | 2016-08-08T11:55:11Z | 38,828,735 | <p>How about using condition objects: <a href="https://docs.python.org/2/library/threading.html#condition-objects" rel="nofollow">https://docs.python.org/2/library/threading.html#condition-objects</a></p>
<p>Instead of sleep() you use wait(<em>timeout</em>). To "interrupt" you call notify().</p>
| 0 | 2016-08-08T12:03:55Z | [
"python",
"multithreading",
"thread-sleep"
] |
Calculating the stock price volatility from a 3-columns csv | 38,828,622 | <p>I am looking for a way to make the following code work:</p>
<pre><code>import pandas
path = 'data_prices.csv'
data = pandas.read_csv(path, sep=';')
data = data.sort_values(by=['TICKER', 'DATE'], ascending=[True, False])
data.columns
</code></pre>
<p>I have a 2 dimensional array with three columns, the data looks... | -1 | 2016-08-08T11:57:34Z | 38,832,992 | <p>Apologies, it's not fully clear on the sort of output you're hoping for so I've assumed you want to enter a ticker and a period (x) and see the current volatility number. Below I have also made use of numpy, in case you don't have that library.</p>
<p>Essentially I've created a DataFrame of all the original data an... | 0 | 2016-08-08T15:21:09Z | [
"python",
"pandas",
"stocks",
"yield-return",
"volatility"
] |
Modifying data in a column Python | 38,828,675 | <p>Hi guys i have a column like this,</p>
<pre><code> Start
Start = 11122001
Start = 12012014
Start = 23122001
</code></pre>
<p>And i want to remove the "Start =" and the date format into </p>
<pre><code> Start
11/12/2001
12/01/2014
23/12/2001
</code></pre>
<p>How do I do this properly?</p>
| 0 | 2016-08-08T12:00:43Z | 38,828,715 | <p>It depends on what you are trying to do.</p>
<p>If you want to remove <code>Start =</code> from each line:</p>
<pre><code>lines = [ format_date(re.sub("^Start =", '', line)) for line in lines ]
</code></pre>
<p>(presuming you have your text line by line in a list). </p>
<p>To format date you need to implement th... | 4 | 2016-08-08T12:02:33Z | [
"python",
"string"
] |
succeed in script but fail in rc.local | 38,828,731 | <p>I write mail.py(use webpy) to send me the ip address of each machine. </p>
<pre><code>#!/usr/bin/env python
#coding=utf-8
import web
def send_mail(send_to, subject, body, cc=None, bcc=None):
try:
web.config.smtp_server = 'xxxxx'
web.config.smtp_port = 25
web.config.smtp_u... | 0 | 2016-08-08T12:03:40Z | 38,830,057 | <p>This might happen because <code>PATH</code> is different when <code>rc.local</code> runs. Specifically, <code>web.sendmail</code> might expect to find <code>sendmail</code> in the path, but it's not there yet. See docs <a href="http://webpy.org/cookbook/sendmail" rel="nofollow">here</a>.</p>
<p>The paths might be s... | 1 | 2016-08-08T13:08:00Z | [
"python",
"bash",
"ubuntu",
"rc"
] |
python global variable between modules | 38,828,738 | <p>I have two modules and I'm trying to modify a global variable in the first module from the second module.</p>
<p><code>app.py</code>:</p>
<pre><code>import time
glob=0;
def setval(val):
global glob
glob = val
print "glob = "+glob
def bau():
while(1):
if(glob):
print"glob is set"
... | 0 | 2016-08-08T12:04:10Z | 38,828,822 | <blockquote>
<p>I not able to understand why in start.py the full content of app.py is
included and not only the function that I want.</p>
</blockquote>
<p>You misunderstand how import works. What it does it actually runs the script you are importing and <em>then</em> binds to things defined inside. If you wish to... | 4 | 2016-08-08T12:08:09Z | [
"python"
] |
python global variable between modules | 38,828,738 | <p>I have two modules and I'm trying to modify a global variable in the first module from the second module.</p>
<p><code>app.py</code>:</p>
<pre><code>import time
glob=0;
def setval(val):
global glob
glob = val
print "glob = "+glob
def bau():
while(1):
if(glob):
print"glob is set"
... | 0 | 2016-08-08T12:04:10Z | 38,829,109 | <p>As suggested by <a href="http://stackoverflow.com/users/645551/freakish">freakish</a>, you can use that approach.</p>
<p>Or if you want to keep it in this format that it's called by different scripts , I suggest you use enviroment variables.</p>
<p>start.py</p>
<pre><code>import os
os.environ['glob_var'] = 'any_v... | 0 | 2016-08-08T12:21:50Z | [
"python"
] |
How to use Tensorflow and Sci-Kit Learn together in one environmen in PyCharm ? | 38,828,829 | <p>I am using Ubuntu 16.04 . I tried to install Tensorflow using Anaconda 2 . But it installed a Environment inside ubuntu . So i had to create a virtual environment and then use Tensorflow . Now how can i use both Tensorflow and Sci-kit learn together in a single environment . </p>
| 1 | 2016-08-08T12:08:33Z | 39,021,770 | <p>Anaconda <code>defaults</code> doesn't provide tensorflow yet, but <code>conda-forge</code> do, conda <code>install -c conda-forge tensorflow</code> should see you right, though (for others reading!) the installed tensorflow will not work on CentOS < 7 (or other Linux Distros of a similar vintage).</p>
| 1 | 2016-08-18T15:11:58Z | [
"python",
"pycharm",
"tensorflow",
"anaconda",
"ubuntu-16.04"
] |
How to use Tensorflow and Sci-Kit Learn together in one environmen in PyCharm ? | 38,828,829 | <p>I am using Ubuntu 16.04 . I tried to install Tensorflow using Anaconda 2 . But it installed a Environment inside ubuntu . So i had to create a virtual environment and then use Tensorflow . Now how can i use both Tensorflow and Sci-kit learn together in a single environment . </p>
| 1 | 2016-08-08T12:08:33Z | 39,022,103 | <p>there are many options to install, but for example if you use #pip method, you can install #tensorflow using:
sudo apt-get install python-pip python-dev python-virtualenv</p>
<p>then complete the process following the official instructions: <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setu... | 0 | 2016-08-18T15:28:22Z | [
"python",
"pycharm",
"tensorflow",
"anaconda",
"ubuntu-16.04"
] |
"QThread: Destroyed while thread is still running" when run from the Windows cmd or IDLE but not from PyCharm? | 38,829,023 | <p>This is a simplified version of the program implementing PyQt multi-threading with QObject.moveToThread. Basically, I query a webpage on a separate thread and extract the HMTL content.</p>
<p>I get this problem where running the code from IDLE or the Windows command line hangs python. The Windows cmd shows "QThread... | 1 | 2016-08-08T12:17:09Z | 38,832,029 | <p>I figured it out:</p>
<p>Both http_client and temp_thread have to be attributes or the HtmlGetter class. I think it's because otherwise python discards them when exiting the function. This is the working code:</p>
<pre><code>import requests
import sys
from PyQt4 import QtGui, uic
from PyQt4.QtCore import QObject, ... | 1 | 2016-08-08T14:36:15Z | [
"python",
"multithreading",
"pyqt",
"hang",
"destroy"
] |
Retain original format of datetime64 when converting to list | 38,829,075 | <pre><code>>>>df = pd.DataFrame(index=pd.date_range(DT.datetime(2016,8,1), DT.datetime(2016,8,9)), columns=['a','b'] )
>>>df.index
DatetimeIndex(['2016-08-01', '2016-08-02', '2016-08-03', '2016-08-04',
'2016-08-05', '2016-08-06', '2016-08-07', '2016-08-08',
'2016-08-09'],
... | 0 | 2016-08-08T12:20:11Z | 38,830,047 | <p>You can retain the original format while converting them to list by using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.date.html#pandas.DatetimeIndex.date" rel="nofollow"><code>.date</code></a> of <code>pandas.DatetimeIndex.date</code> which returns the date part of the Timesta... | 2 | 2016-08-08T13:07:35Z | [
"python",
"pandas",
"python-datetime"
] |
The truth value of a Series is ambiguous | 38,829,124 | <pre><code>df['class'] = np.where(((df['heart rate'] > 50) & (df['heart rate'] < 101 )) & ((df['systolic blood pressure'] > 140 & df['systolic blood pressure'] < 160)) &
((df['dyastolic blood pressure'] > 90 & ['dyastolic blood pressure'] < 100 )) & ((df['temperature'] >... | 0 | 2016-08-08T12:22:29Z | 38,829,324 | <p>Maybe this will solve your (our) problem.</p>
<pre><code>import random
import pandas as pd
import numpy as np
heart_rate = [random.randrange(45, 125) for _ in range(500)]
blood_pressure_systolic = [random.randrange(140, 230) for _ in range(500)]
blood_pressure_dyastolic = [random.randrange(90, 140) for _ in range(5... | 0 | 2016-08-08T12:32:17Z | [
"python",
"conditional",
"logical-operators"
] |
Scikit-learn SVM: Reshaping X leads to incompatible shapes | 38,829,135 | <p>I try to use scikit-learn SVM to predict whether a stock from S&P500 beats the index or not.
I have the 'sample' file from which I extract the features X and the labels (beats the index or doesn't beat it) Y.</p>
<p>When I tried it the first time (without reshaping X) I got the the following depreciation error:... | 0 | 2016-08-08T12:22:51Z | 38,829,560 | <p>You should not be reshaping <code>X</code> to <code>(-1, 1)</code>. In fact the error is in your call to the <code>predict</code> method.</p>
<p>Change</p>
<pre><code>clf.predict(X[-x])[0]
</code></pre>
<p>to</p>
<pre><code>clf.predict(X[-x].reshape((-1, 9)))[0]
</code></pre>
| 1 | 2016-08-08T12:42:56Z | [
"python",
"error-handling",
"scikit-learn",
"svm"
] |
Error NoReverseMatch | 38,829,138 | <p>I keep running in to a <code>NoReverseMatch</code> error on Django 1.10, while earlier versions have no problems with it.</p>
<p>rendered template:</p>
<pre><code>{% extends "loginBase.html" %}
{% block content %}
<h1>Login:</h1>
<form class="form-horizontal" role="form" method="post" action="{%... | 0 | 2016-08-08T12:23:05Z | 38,829,349 | <p>In Django 1.10, <a href="https://docs.djangoproject.com/en/1.10/releases/1.10/#features-removed-in-1-10" rel="nofollow">you can no longer reverse URLs using the Python dotted path</a>, e.g. '<code>django.contrib.auth.views.login</code>'.</p>
<p>You already have <code>name='login'</code> in your URL pattern,</p>
<p... | 3 | 2016-08-08T12:33:32Z | [
"python",
"django",
"django-1.10"
] |
Boolearn logic in Python CGI script | 38,829,146 | <p>Does anyone know how to set a html check box to true or false with python. I am using a Python file to parse an XML file to a list. From this list I want to check a checkbox if the text in XML tag is 1 or I want it to remain unchecked if the the text in the XML tag is 0.</p>
<p>Thsi is being done as a cgi file, don... | -1 | 2016-08-08T12:23:33Z | 38,850,770 | <p>I was shown a solution by someone who was using php to do something similiar. The answer that worked for me in the end was simple enough. I changed the setting in the XML file to 1 or 0 for true or false and then did this:</p>
<pre><code>if config_settings.settings[5] == '1':
print'''<html><label clas... | 0 | 2016-08-09T12:28:08Z | [
"python",
"html",
"xml",
"list"
] |
Dask error: Length of values does not match length of index | 38,829,387 | <p>I have read csv file using <a href="http://dask.pydata.org/en/latest/" rel="nofollow">dask</a> this way:</p>
<pre><code>import dask.dataframe as dd
train = dd.read_csv('act_train.csv')
</code></pre>
<p>Then I would like to apply simple logic per row , that works pretty fine in pandas:</p>
<pre><code>columns = li... | 0 | 2016-08-08T12:34:49Z | 38,830,548 | <p>If x doesn't contain space character than x.split(' ') will return a list containing single element x. </p>
<p>So, when u are trying to access the second element of x.split(' ') by calling
x.split(' ')[1]. It will give the error :</p>
<p>"Length of values does not match length of index", as there is no element at... | 0 | 2016-08-08T13:30:30Z | [
"python",
"csv",
"dataframe",
"runtime-error",
"dask"
] |
How to compare two matrices (numpy ndarrays) element by element and get the min-value of each comparison | 38,829,428 | <p>So i want to make a comparison between two matrices (size: 98000 x 64). The comparison should be done element by element and i want to the min value of each comparison stored in a third matrix with the same dimensions. I also want the comparison being done without the use of loops! </p>
<p>Here's a small example:</... | 1 | 2016-08-08T12:37:10Z | 38,829,754 | <p>Numpy has a minimum feature, as below:</p>
<pre><code>c = np.minimum(a,b)
</code></pre>
| 4 | 2016-08-08T12:53:03Z | [
"python",
"numpy"
] |
Process variables from one method to another inside one class | 38,829,632 | <p>Guys, I think how to process variables from one method into another inside one class. For example : </p>
<pre><code>class Newclas:
def getPortalSources(self,portal):
self.connection_source=self.config.get("portal_"+portal,'Sources')
self.portal=portal
def getConnection(self,source):... | -2 | 2016-08-08T12:46:44Z | 38,829,961 | <p>What I suggest is that you use constructor, or global variables.</p>
<p>I will give an example for constructor here:</p>
<pre><code>class Newclas:
def __init__(self,portal='default_portal',source='default_source'):
self.portal = portal
self.source = source
def getPortalSources(self,porta... | 0 | 2016-08-08T13:03:48Z | [
"python"
] |
tensorflow.train.import_meta_graph does not work? | 38,829,641 | <p>I try to simply save and restore a graph, but the simplest example does not work as expected (this is done using version 0.9.0 or 0.10.0 on Linux 64 without CUDA using python 2.7 or 3.5.2)</p>
<p>First I save the graph like this:</p>
<pre><code>import tensorflow as tf
v1 = tf.placeholder('float32')
v2 = tf.placeh... | 1 | 2016-08-08T12:47:09Z | 38,834,095 | <p>To reuse a <code>MetaGraphDef</code>, you will need to record the names of interesting tensors in your original graph. For example, in the first program, set an explicit <code>name</code> argument in the definition of <code>v1</code>, <code>v2</code> and <code>v4</code>:</p>
<pre><code>v1 = tf.placeholder(tf.float3... | 3 | 2016-08-08T16:18:58Z | [
"python",
"tensorflow"
] |
Summing Booleans in a Dataframe | 38,829,702 | <p>I have a non-indexed Pandas dataframe where each row consists of numeric and boolean values with some NaNs. An example row in my dataframe might look like this (with variables above): </p>
<pre><code>X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12
24.4 True 5.1 False 22.4 55 33.4 True 18.04 False NaN... | 1 | 2016-08-08T12:50:23Z | 38,829,815 | <p>Select boolean columns and then sum:</p>
<pre><code>df.select_dtypes(include=['bool']).sum(axis=1)
</code></pre>
<p>If you have NaNs, first fill with False's:</p>
<pre><code>df.fillna(False).select_dtypes(include=['bool']).sum(axis=1)
</code></pre>
<hr>
<p>Consider this DataFrame:</p>
<pre><code>df
Out:
... | 4 | 2016-08-08T12:55:59Z | [
"python",
"pandas",
"dataframe"
] |
Django how to send the email after save the object,but send email function don't delay return HttpResponse | 38,829,705 | <p>I want to send an email after saving the data into a database,but I don't want to wait after completed send email return the <code>HTTP</code> response ,I want to return the <code>HTTP</code> response direct ,then send the email by Django self. </p>
<pre><code>def received(request):
login=get_login(request)
... | 0 | 2016-08-08T12:50:31Z | 38,829,870 | <h2>Use a local SMTP server.</h2>
<p>Will result in the mail being queued (even if it's not delivered) almost instantly, so you are able to send your http response without being held up by the delays in sending the email.</p>
<h2>Use a Task Queue</h2>
<p>In it's simplest form, you can just chuck in the email message... | 2 | 2016-08-08T12:58:58Z | [
"python",
"django",
"email"
] |
Django how to send the email after save the object,but send email function don't delay return HttpResponse | 38,829,705 | <p>I want to send an email after saving the data into a database,but I don't want to wait after completed send email return the <code>HTTP</code> response ,I want to return the <code>HTTP</code> response direct ,then send the email by Django self. </p>
<pre><code>def received(request):
login=get_login(request)
... | 0 | 2016-08-08T12:50:31Z | 38,829,945 | <p>Simplest solution is to run is asynchronously:</p>
<pre><code>import threading
def run_async(func, args):
threading.Thread(target=func, args=args).start()
</code></pre>
<p>and then:</p>
<pre><code>run_async([function], ([args]))
</code></pre>
| 1 | 2016-08-08T13:02:36Z | [
"python",
"django",
"email"
] |
Matplotlib; open plots minimized? | 38,829,797 | <p>So I've got a code that is going to make a couple plots, for which I want/have the window maximized in size. However, I'd ideally also want these windows to be minimized when they get created (mostly because it would make testing things a lot easier!) Is there any way to achieve this? I'm currently using Python 2.7 ... | 0 | 2016-08-08T12:55:19Z | 38,830,288 | <p>Try this after relevant plots:</p>
<pre><code>mng = plt.get_current_fig_manager()
mng.window.showMaximized()
mng.window.showMinimized()
</code></pre>
| 0 | 2016-08-08T13:18:55Z | [
"python",
"linux",
"matplotlib",
"plot"
] |
Use struct in python to deserialize a byte array coming from serial | 38,829,921 | <p>I have a class with all sorts of data in it, like:</p>
<pre><code>class UARTMessage:
Identification1 = int(0) #byte 0
Timestamp1 = int(0) #bytes [1:5]
Voltage1 = int(0) #bytes [6:7]
Current1 = int(0) #bytes [8:9]
Signal1= int(0) #bytes [10:11]
Identification2 = int(0) #byte 12
Timestamp2... | 1 | 2016-08-08T13:01:19Z | 38,833,966 | <p>First of all, we need to declare format of incoming bytes according to this list: <a href="https://docs.python.org/3/library/struct.html?highlight=struct#format-characters" rel="nofollow">https://docs.python.org/3/library/struct.html?highlight=struct#format-characters</a>. </p>
<pre><code>import struct
import sys
... | 1 | 2016-08-08T16:11:44Z | [
"python",
"serialization"
] |
Selecting many rows in Qt table | 38,829,929 | <p>I am trying to create a <code>QTableView</code> in Qt which is efficient for large tables. I've managed to make the display of data efficient by defining my own abstract table model:</p>
<pre class="lang-py prettyprint-override"><code>from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
class DataTableMo... | 0 | 2016-08-08T13:01:37Z | 38,831,656 | <p>The simplest way would be to reimplement the selection model. The view queries the selection model for the selection status of each index. Alas, the <code>QItemSelectionModel</code> has a major shortcoming: you can't reimplement its <code>isSelected</code> method.</p>
<p>The best you can do is to create a fresh sel... | 0 | 2016-08-08T14:18:36Z | [
"python",
"performance",
"qt",
"pyqt"
] |
Selecting many rows in Qt table | 38,829,929 | <p>I am trying to create a <code>QTableView</code> in Qt which is efficient for large tables. I've managed to make the display of data efficient by defining my own abstract table model:</p>
<pre class="lang-py prettyprint-override"><code>from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
class DataTableMo... | 0 | 2016-08-08T13:01:37Z | 38,831,667 | <p>You should use the second overloaded version of <code>select</code>, the one that accepts a <a href="http://doc.qt.io/qt-4.8/qitemselection.html" rel="nofollow"><code>QItemSelection</code></a> instead of a single index.</p>
<p>The <code>QItemSelection</code> is able to select <em>ranges</em> of rows by providing th... | 1 | 2016-08-08T14:19:05Z | [
"python",
"performance",
"qt",
"pyqt"
] |
Selecting many rows in Qt table | 38,829,929 | <p>I am trying to create a <code>QTableView</code> in Qt which is efficient for large tables. I've managed to make the display of data efficient by defining my own abstract table model:</p>
<pre class="lang-py prettyprint-override"><code>from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
class DataTableMo... | 0 | 2016-08-08T13:01:37Z | 38,877,904 | <p>If you want to display some selected rows only as opposite to
display everything and select some rows, then QSortFilterProxyModel could help:</p>
<pre><code>from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
import numpy as np
class FilterProxy(QtGui.QSortFilterProxyModel):
afilter = set(np.where(n... | 0 | 2016-08-10T15:36:21Z | [
"python",
"performance",
"qt",
"pyqt"
] |
Dealing with NSRect in python | 38,829,970 | <p>I have a function:</p>
<pre><code>def getMediaBox(doc, pageNum):
page = CGPDFDocumentGetPage(doc, pageNum)
return CGPDFPageGetBoxRect(page, kCGPDFMediaBox)
</code></pre>
<p>which returns:</p>
<pre><code><NSRect origin=<NSPoint x=0.0 y=0.0> size=<NSSize width=499.0 height=709.0>>
</code><... | 0 | 2016-08-08T13:04:11Z | 38,873,499 | <p>You can query the NSRect object with the following lines:</p>
<pre><code>x = CGRectGetWidth(mediaBox)
y = CGRectGetHeight(mediaBox)
</code></pre>
| 0 | 2016-08-10T12:30:43Z | [
"python",
"osx",
"core-graphics"
] |
Groupby an numpy.array based on groupby of a pandas.DataFrame with the same length | 38,830,134 | <p>I have a numpy.array <code>arr</code> and a pandas.DataFrame <code>df</code>.</p>
<p><code>arr</code> and <code>df</code> have the same shape <code>(x,y)</code>. </p>
<p>I need to group by one column of <code>df</code> and apply the transformation of the impacted rows on <code>arr</code> which have the same shape.... | 2 | 2016-08-08T13:11:50Z | 38,830,253 | <p>It looks like need first create <code>DataFrame</code> from <code>arr</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by column <code>A</code> and aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generate... | 2 | 2016-08-08T13:17:03Z | [
"python",
"arrays",
"pandas",
"numpy",
"dataframe"
] |
Rearrange position of words in string conditionally | 38,830,165 | <p>I've spent the last few months developing a program that my company is using to clean and geocode addresses on a large scale (~5,000/day). It is functioning adequately well, however, there are certain address formats that I see daily that are causing issues for me.</p>
<p>Addresses with a format such as this <code>... | 0 | 2016-08-08T13:12:54Z | 38,830,304 | <p>Make the string <code>address[location]</code> into a list by wrapping it in brackets, then concatenate the other pieces.</p>
<pre><code>address = [address[location]] + address[:location] + address[location+1:]
</code></pre>
<p>An example:</p>
<pre><code>address = ['park', 'avenue', '1']
location = 2
address = [a... | 1 | 2016-08-08T13:19:26Z | [
"python"
] |
Rearrange position of words in string conditionally | 38,830,165 | <p>I've spent the last few months developing a program that my company is using to clean and geocode addresses on a large scale (~5,000/day). It is functioning adequately well, however, there are certain address formats that I see daily that are causing issues for me.</p>
<p>Addresses with a format such as this <code>... | 0 | 2016-08-08T13:12:54Z | 38,831,062 | <p>Here's a modified version of your code. It uses simple list slicing to rearrange the parts of the address list.</p>
<p>Rather than using a <code>for</code> loop to search for a matching road type it uses set operations.</p>
<p>This code isn't perfect: it won't catch "numbers" like 12a, and it won't handle weird st... | 1 | 2016-08-08T13:54:04Z | [
"python"
] |
sympy.geometry Point class is working slow | 38,830,236 | <p>I have a code which reads unstructured mesh. I wrote wrappers around geometric entities of <code>sympy.geometry</code> such as:</p>
<pre><code>class Point:
def __init__(self, x, y, parent_mesh):
self.shape = sympy.geometry.Point(x,y)
self.parent_mesh = parent_mesh
self.parent_cell = list... | 1 | 2016-08-08T13:16:13Z | 38,830,325 | <p>Take a look at the <a href="http://docs.sympy.org/latest/modules/geometry/points.html#module-sympy.geometry.point" rel="nofollow"><code>Point</code> class documentation</a>, specifically, in one of the first examples:</p>
<blockquote>
<p>Floats are automatically converted to Rational unless the evaluate flag is <... | 3 | 2016-08-08T13:20:20Z | [
"python",
"python-3.x",
"sympy"
] |
How to fill matplotlib bars with a gradient? | 38,830,250 | <p>I would be very interested in filling matplotlib/seaborn bars of a barplot with different gradients exactly like done here (not with matplotlib as far as I understood):
<a href="http://i.stack.imgur.com/fOGrG.png" rel="nofollow"><img src="http://i.stack.imgur.com/fOGrG.png" alt="enter image description here"></a></... | -1 | 2016-08-08T13:16:55Z | 38,833,551 | <p>I am using seaborn <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.barplot.html" rel="nofollow">barplot</a> with the <code>palette</code> option. Imagine you have a simple dataframe like:</p>
<pre><code>df = pd.DataFrame({'a':[1,2,3,4,5], 'b':[10,5,2,4,5]})
</code></pre>
<p>using seaborn:... | 1 | 2016-08-08T15:48:56Z | [
"python",
"matplotlib",
"bar-chart",
"gradient",
"seaborn"
] |
Removing \xa0 from string in a list | 38,830,308 | <p>I have a list with a bunch of words:</p>
<pre><code>lista = ['Jeux Olympiques De Rio\xa02016', 'Sahara Ray', 'Michael Phelps', 'Amber Alert']
</code></pre>
<p>I tried to replace the <code>'\xa0'</code>:</p>
<pre><code>for element in listor:
element = element.replace('\xa0',' ')
</code></pre>
<p>But it didn't... | 1 | 2016-08-08T13:19:36Z | 38,830,388 | <pre><code>for index, element in enumerate(listor):
listor[index] = element.replace('\xa0',' ')
</code></pre>
<p>Now you're replacing the string within the list rather than trying to change the string itself. Previously, you were assigning a new string to the same variable name, which doesn't change the previous s... | 2 | 2016-08-08T13:23:21Z | [
"python",
"string",
"python-3.x"
] |
Removing \xa0 from string in a list | 38,830,308 | <p>I have a list with a bunch of words:</p>
<pre><code>lista = ['Jeux Olympiques De Rio\xa02016', 'Sahara Ray', 'Michael Phelps', 'Amber Alert']
</code></pre>
<p>I tried to replace the <code>'\xa0'</code>:</p>
<pre><code>for element in listor:
element = element.replace('\xa0',' ')
</code></pre>
<p>But it didn't... | 1 | 2016-08-08T13:19:36Z | 38,830,447 | <p>Just use a list comprehension to replace the ending if a string contains <code>'\xa0'</code>:</p>
<pre><code>res = [elem if '\xa0' not in elem else elem.replace('\xa0', '') for elem in lista]
</code></pre>
<p>Your current approach merely re-assigns a name (<code>element</code>) over and over without actually modif... | 2 | 2016-08-08T13:25:28Z | [
"python",
"string",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.