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 |
|---|---|---|---|---|---|---|---|---|---|
Wrong result in list comprehension codition | 37,663,906 | <p>I am getting wrong result in my list comprehension if condition . I tried everything any hints what could be wrong.</p>
<pre><code>po_list = [n for n in Material.objects.all()
if (((F('n.total_inventory') + F('n.total_po') - F('n.total_so'))) < F('n.min_quantity'))]
</code></pre>
<p>Currently it will alwa... | -1 | 2016-06-06T17:55:49Z | 37,664,148 | <p>Don't use the <code>F</code> objects and use the <code>n</code> variable:</p>
<pre><code>po_list = [n for n in Material.objects.all()
if (n.total_inventory + n.total_po - n.total_so) < n.min_quantity]
</code></pre>
| 1 | 2016-06-06T18:12:26Z | [
"python",
"django"
] |
Selecting columns with condition on Pandas DataFrame | 37,663,931 | <p>I have a dataframe looking like this.</p>
<pre><code> col1 col2
0 something1 something1
1 something2 something3
2 something1 something1
3 something2 something3
4 something1 something2
</code></pre>
<p>I'm trying to filter all rows that have <code>something1</code> either on <code>col1</code>... | 1 | 2016-06-06T17:57:39Z | 37,663,969 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow"><code>all</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>print ((df == 'somethin... | 1 | 2016-06-06T17:59:44Z | [
"python",
"pandas",
"dataframe",
"condition"
] |
CAN module python 3 | 37,664,104 | <p>I have recently purchased a <a href="http://skpang.co.uk/blog/archives/1220" rel="nofollow">PICAN</a> 2 board that uses the CAN module,</p>
<pre><code>import CAN
bus = CAN.interface.Bus(channel='can0', bustype='socketcan_native')
msg = CAN.Message(arbitration_id=0x13C, data=[0,25,1,3,1,4,1]
bus.send(msg)
</code></p... | 2 | 2016-06-06T18:09:20Z | 37,714,120 | <p>As rfkortekaas said - the module is called <code>can</code>. I suspect you have called one of your python files <code>CAN.py</code> which is why you get the error you're seeing. </p>
<p>Have you downloaded and installed the <a href="https://bitbucket.org/hardbyte/python-can" rel="nofollow">python-can</a> package?</... | 0 | 2016-06-08T22:42:11Z | [
"python",
"can"
] |
Python: defaultdict(dict) how to create nested dictionary? | 37,664,113 | <p>I need to grab strings from all files in a directory and record them somehow, so I tried to use defaultdict to create this, but I'm having difficulty figuring out how to progressively add to each layer of the dictionary. Essentially, what the dictionary should look like is this:</p>
<blockquote>
<p>Filename</p>
... | 0 | 2016-06-06T18:10:41Z | 37,664,634 | <p>A dictionary is something that has a key and a value, any time you put something into a dictionary that has the same key, it will replace that value. For instance:</p>
<pre><code>dictionary = {}
# Insert value1 at index key1
dictionary["key1"] = "value1"
# Overwrite the value at index key1 to value2
dictionary["ke... | 1 | 2016-06-06T18:39:54Z | [
"python",
"dictionary",
"nested",
"defaultdict"
] |
pandas get counts based on previous column | 37,664,274 | <p>I would like to add column to a pandas dataframe where the value is an incrementing value starting with a value from another column. For instance say I have the following dataframe.</p>
<pre><code>df = pd.DataFrame([['a', 1], ['a', 1], ['b', 5], ['c', 10], ['c', 10], ['c', 10]], columns=['x', 'y'])
df
x y
0 ... | 1 | 2016-06-06T18:19:56Z | 37,664,483 | <p>try: </p>
<pre><code>df['z'] = df.y + df.groupby('y').apply(lambda df: pd.Series(range(len(df)))).values
</code></pre>
| 3 | 2016-06-06T18:31:15Z | [
"python",
"pandas"
] |
pandas get counts based on previous column | 37,664,274 | <p>I would like to add column to a pandas dataframe where the value is an incrementing value starting with a value from another column. For instance say I have the following dataframe.</p>
<pre><code>df = pd.DataFrame([['a', 1], ['a', 1], ['b', 5], ['c', 10], ['c', 10], ['c', 10]], columns=['x', 'y'])
df
x y
0 ... | 1 | 2016-06-06T18:19:56Z | 37,664,748 | <p>While not a pandas related answer, to get out of the nested lists, and flatten it out, you can use a simple list comprehension from what you currently have as z.</p>
<pre><code>>>>z = [[1, 2], [5], [10, 11, 12]]
>>>z_flat = [num for sublist in z for num in sublist])
>>>z_flat
[1, 2, 5, 10... | 1 | 2016-06-06T18:46:25Z | [
"python",
"pandas"
] |
pandas get counts based on previous column | 37,664,274 | <p>I would like to add column to a pandas dataframe where the value is an incrementing value starting with a value from another column. For instance say I have the following dataframe.</p>
<pre><code>df = pd.DataFrame([['a', 1], ['a', 1], ['b', 5], ['c', 10], ['c', 10], ['c', 10]], columns=['x', 'y'])
df
x y
0 ... | 1 | 2016-06-06T18:19:56Z | 37,665,006 | <p>Here is a way uglier method compared to @piRSquared's:</p>
<pre><code>def func(group):
x = group['y'].head(1).values
l = []
for i in range(len(group)):
l.append(x+i)
return pd.Series(l, name='z')
x = df.groupby('x').apply(func).reset_index().drop('level_1', axis=1)
x['z'] = x['z'].apply(lam... | 1 | 2016-06-06T19:03:00Z | [
"python",
"pandas"
] |
Annotating vertical lines below the x-axis with pyplot | 37,664,304 | <p>With matplotlib, I am trying to annotate vertical lines that I have drawn on a plot of sequential data. With the line</p>
<pre><code>plt.annotate('%.2f' % 2.34, xy=(0,0), xytext=(0,-20), xycoords='axes fraction', textcoords='offset points',color='r')
</code></pre>
<p>I am able to get text to show up below my plot.... | 1 | 2016-06-06T18:21:12Z | 37,665,857 | <p>It's difficult to say what is the exact problem without a workable example. In any case as solution to your problem I would advise you to duplicate your axis (in the same figure) and just use the second one to control the accessory stuff. </p>
<p>Here is a working solution:</p>
<pre><code>import numpy as np
import... | 0 | 2016-06-06T19:58:14Z | [
"python",
"matplotlib",
"plot",
"annotations"
] |
Downloading multiple files using Selenium click()? | 37,664,334 | <p>Using Firefox/Python/Selenium-- I am able to use <code>click()</code> on a file link on a webpage to download it, and the file downloads to my Downloads folder as expected.</p>
<p>However, when I add more lines to <code>click()</code> on more than 1 link, the script no longer runs as expected. Instead of the files ... | 0 | 2016-06-06T18:22:43Z | 37,664,671 | <p>A way to download such multiple files if <strong><em>opened in different tabs</em></strong> could be to follow these algorithmic steps in your own coding language : </p>
<pre><code>for( all such links) :
click() the pdf link
findElement the download element
click() the download link
close the tab
swi... | 0 | 2016-06-06T18:41:51Z | [
"python",
"selenium",
"firefox",
"selenium-webdriver"
] |
Downloading multiple files using Selenium click()? | 37,664,334 | <p>Using Firefox/Python/Selenium-- I am able to use <code>click()</code> on a file link on a webpage to download it, and the file downloads to my Downloads folder as expected.</p>
<p>However, when I add more lines to <code>click()</code> on more than 1 link, the script no longer runs as expected. Instead of the files ... | 0 | 2016-06-06T18:22:43Z | 37,669,583 | <p>I added the following code for launching Firefox and now the download behavior works as expected when clicking on each file:</p>
<pre><code> profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting',... | 1 | 2016-06-07T02:27:54Z | [
"python",
"selenium",
"firefox",
"selenium-webdriver"
] |
Storing a single list of references to elements in several other lists in python | 37,664,446 | <p>I have several lists, let's say they look like:</p>
<pre><code>a = [0, 1, 2]
b = [3, 4, 5, 6]
</code></pre>
<p>And I want to have a list or similarly iterable data structure which stores all the elements in both a and b:</p>
<pre><code>c = [0, 1, 2, 3, 4, 5, 6]
</code></pre>
<p>changing any of these elements cha... | 3 | 2016-06-06T18:29:22Z | 37,665,269 | <p>Perhaps something like this:</p>
<pre><code>class IndirectList():
def __init__(self, *args):
self.array = list()
for subarray in range(len(args)):
for element in range(len(args[subarray])):
self.array.append((args[subarray], element))
def __len__(self):
... | 3 | 2016-06-06T19:20:04Z | [
"python"
] |
Spark-pyspark: saved data has undesired quotation marks | 37,664,468 | <p>I am using the following code to export my data frame to csv:</p>
<pre><code>data.write.format('com.databricks.spark.csv').options(delimiter="\t", codec="org.apache.hadoop.io.compress.GzipCodec").save('s3a://myBucket/myPath')
</code></pre>
<p>Note that I use <code>delimiter="\t"</code>, as I don't want to add addi... | 1 | 2016-06-06T18:30:38Z | 37,725,033 | <p>You don't use all the options provided by the CSV writer. It has <code>quoteMode</code> parameter which takes one of the four values (descriptions from the <code>org.apache.commons.csv</code> <a href="https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/QuoteMode.html_" rel="nofollow">documen... | 0 | 2016-06-09T11:43:52Z | [
"python",
"csv",
"apache-spark",
"pyspark"
] |
How can I connect a serial device to a Raspberry Pi without a USB to serial adapter? | 37,664,487 | <p>I am trying to connect a serial device (specifically, an aerosol particle counter) to the Pi. Currently, I have a USB to serial adapter connecting the Pi and the device. When I run this program to read data from the serial device: </p>
<pre><code>import time
import serial
ser = serial.Serial('/dev/ttyUSB0')
print ... | 1 | 2016-06-06T18:31:37Z | 37,707,569 | <p>One thing that can be problematic is the fact that the PIs serial pins work with 3v3 logic not 5v. If your sensor is sending data in 5v logic it can mess with the PI.</p>
<p>Another thing you should check if you have enabled a linux terminal session on ttyAMA0. This is an option you can set in <code>/boot/cmdline.t... | 0 | 2016-06-08T16:04:42Z | [
"python",
"serial-port",
"raspberry-pi",
"usb",
"pyserial"
] |
Python's PyQtGraph: Is it possible to have a gradient-filled plot? | 37,664,521 | <p>Is it possible to generate a plot that looks like this using PyQtGraph?I know how to create a filled plot, but I can't find any examples of applying a gradient to the filled region. </p>
<p><a href="http://i.stack.imgur.com/5hRSu.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/5hRSu.jpg" alt="Gradient filled... | 0 | 2016-06-06T18:33:12Z | 37,672,212 | <p>Look into brush and setfilllevel on the <a href="http://www.pyqtgraph.org/documentation/graphicsItems/plotcurveitem.html" rel="nofollow">PlotCurveItem</a>. You can set the brush with a gradient from PyQt.</p>
<pre><code>from PyQt4 import QtCore, QtGui
import pyqtgraph as pg
import numpy as np
win = pg.GraphicsWind... | 2 | 2016-06-07T06:42:05Z | [
"python",
"pyqtgraph"
] |
How can I shuffle two object lists that I merged in my python Django app | 37,664,544 | <p>I am trying to merge to object lists and then shuffle them but it's not working. If I use </p>
<pre><code>random.shuffle(list_1)
</code></pre>
<p>it will shuffle that one list but if I do</p>
<pre><code>first = list_1()
second = list_2()
merged = first + second
ran = random.shuffle(merged)
context = {
"ran"... | 0 | 2016-06-06T18:34:58Z | 37,664,631 | <p>random.shuffle shuffles the list in place, it doesn't return the shuffled list.</p>
<p>You can do</p>
<pre><code> random.shuffle(merged)
</code></pre>
<p>and the list 'merged' will be shuffled, you can directly use it.</p>
| 2 | 2016-06-06T18:39:47Z | [
"python",
"django",
"random-sample"
] |
How can I shuffle two object lists that I merged in my python Django app | 37,664,544 | <p>I am trying to merge to object lists and then shuffle them but it's not working. If I use </p>
<pre><code>random.shuffle(list_1)
</code></pre>
<p>it will shuffle that one list but if I do</p>
<pre><code>first = list_1()
second = list_2()
merged = first + second
ran = random.shuffle(merged)
context = {
"ran"... | 0 | 2016-06-06T18:34:58Z | 37,664,657 | <p><code>random.shuffle()</code> has no return value. Check the docs <a href="https://docs.python.org/2/library/random.html#random.shuffle" rel="nofollow">here</a></p>
<p>What you can do instead is use the directly shuffled list:</p>
<pre><code>first = list_1()
second = list_2()
merged = first + second
random.shuffle... | 4 | 2016-06-06T18:41:02Z | [
"python",
"django",
"random-sample"
] |
How to run exe file in php | 37,664,561 | <p>I'm working on classification algorithm in python and it related with php code, to get the right result I should run my python exe then go to the php code.</p>
<p>I want to execute the python by itself with php code. I tried this:</p>
<pre><code><?php
// outputs the username that owns the running php/httpd proc... | -1 | 2016-06-06T18:36:05Z | 37,664,801 | <pre><code><?php
exec("C:\\Users\\posh\\AppData\\Local\\Programs\\Python\\Python35\\python.exe YOUR_PYTHONSCRIPT.py <arguments if any>", $output, $ret_code);
// directly writing python may not work in that case
// give path to python.exe
exec("python YOUR_PYTHONSCRIPT.py <arguments if any>", $output, $r... | 0 | 2016-06-06T18:49:30Z | [
"php",
"python",
"exe"
] |
Python MemoryError when not really out of memory? | 37,664,829 | <p>I am trying to perform mean scaling on a bunch of images (>40k). When I read in the images, of size (3,256,256), into an np array, memory usage is at %40 (out of 60 GB, checked using htop). However, when I run arr.std(), the program crashes and gives a MemoryError, even though usage is still at %40. </p>
<p>Any t... | 1 | 2016-06-06T18:51:26Z | 37,665,352 | <p>Are you completly sure that each cell of your arrays takes only 1 Byte, because maybe by default it allocates 8 Bytes for cell.</p>
<p>I created small array 3 x 3 and it occupies 72 bytes.</p>
<p><code>import numpy as np
a = np.array(np.mat('1, 2, 3; 4, 5, 6; 7, 8, 9'))
print(a.nbytes) # Use this .nbytes instead o... | 1 | 2016-06-06T19:24:56Z | [
"python",
"image",
"numpy",
"memory"
] |
get the values of dictionary out of list python | 37,664,850 | <p>I am using the googlemaps library to measure distance between two points. Here is its output. Does anyone know how to assign the distance (<code>'text': '1,271km'</code>) to variable?</p>
<pre><code>dic = {'rows': [{'elements': [{'distance': {'value': 1271380,
'text': '1,... | 0 | 2016-06-06T18:52:53Z | 37,664,933 | <pre><code>In [1]: distance = dic['rows'][0]['elements'][0]['distance']['text']
In [2]: distance
Out[1]: '1,271 km'
In [3]: duration = dic['rows'][0]['elements'][0]['duration']['text']
In [4]: duration
Out[2]: '12 hours 3 mins'
</code></pre>
<p>Use like this. But this is particularly for this <code>dict</code></p>
| 0 | 2016-06-06T18:58:21Z | [
"python",
"python-2.7",
"python-3.x"
] |
get the values of dictionary out of list python | 37,664,850 | <p>I am using the googlemaps library to measure distance between two points. Here is its output. Does anyone know how to assign the distance (<code>'text': '1,271km'</code>) to variable?</p>
<pre><code>dic = {'rows': [{'elements': [{'distance': {'value': 1271380,
'text': '1,... | 0 | 2016-06-06T18:52:53Z | 37,664,936 | <p>I assume that you posted only 1 row and 1 element, but your data might have more than this.</p>
<p>This is how you can iterate and extract the distance value, for example:</p>
<pre><code>>>> for row in dic['rows']:
... for element in row['elements']:
... text = element['distance']['text']
...
>&... | 1 | 2016-06-06T18:58:37Z | [
"python",
"python-2.7",
"python-3.x"
] |
How can I delete one field with same name in mongodb 3.2? | 37,664,910 | <pre><code>{ "_id" : { "$oid" : "50906d7fa3c412bb040eb57b" }, "student_id" : 1, "type" : "exam", "score" : 74.20010837299897 }
{ "_id" : { "$oid" : "50906d7fa3c412bb040eb57c" }, "student_id" : 1, "type" : "quiz", "score" : 96.76851542258362 }
{ "_id" : { "$oid" : "50906d7fa3c412bb040eb57d" }, "student_id" : 1, "type" :... | 0 | 2016-06-06T18:56:38Z | 37,665,095 | <p>Use <a href="https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/" rel="nofollow"><code>findAndModify</code></a>:</p>
<pre><code>db.students.findAndModify({
query: {"student_id" : 1, "type" : "homework"},
sort: {"score": 1},
remove: true
})
</code></pre>
<p>In MongoDB 3.2 yo... | 3 | 2016-06-06T19:08:12Z | [
"python",
"json",
"mongodb"
] |
How to pass an object from callback to errback (twisted)? | 37,664,931 | <p>I have a callback chain with an errback at the end. If any of the callbacks fail, I need to pass an object to be used on errBack.</p>
<p><strong>How can I pass an object from callback to the errback?</strong></p>
<p>The following code exemplifies what I want to do: </p>
<pre><code>from twisted.internet.defer impo... | 0 | 2016-06-06T18:58:00Z | 37,665,193 | <p>In this case you can just raise an exception, containing all info you need</p>
<p>For example:</p>
<pre><code>from twisted.internet import defer
class MyCustomException(Exception):
def __init__(self, msg, code):
self.code = code
self.message = msg
def callback(result):
print result
ra... | 1 | 2016-06-06T19:14:38Z | [
"python",
"twisted",
"deferred"
] |
How to input both wind speed and direction data and pcolormesh plot it in python, with both on the same plot? | 37,664,950 | <p>I have some wind speed and direction data that I need to plot into python. I got the data from a data file and did some calculations to get the wind speed and data, and here is what I got:</p>
<pre><code>wind_speed = np.sqrt(u**2+ v**2)
wind_speed
wind_dir_trig_to = (np.arctan2((u/wind_speed), (v/wind_speed)))
wind... | 1 | 2016-06-06T18:59:45Z | 37,665,033 | <p>How about:</p>
<pre><code>import matplotlib.pyplot as pl
pl.pcolormesh(wind_dir_cardinal)
</code></pre>
| 2 | 2016-06-06T19:04:18Z | [
"python",
"numpy",
"matplotlib"
] |
Using Selenium to By-pass SSL Certification In Internet Explorer (Python) | 37,664,978 | <p>I have done some searching on this issue and have not found any working solutions. Essentially, I am trying to write a script that utilizes Selenium to open a particular site and enter user login information. However, Internet Explorer returns a certificate warning as shown:</p>
<p><img src="http://i.stack.imgur.co... | 0 | 2016-06-06T19:01:36Z | 38,483,803 | <p>SSL error page in IE isn't Shadow DOM, you can navigate on the page and just click on "Continue".
Try 'find_element' :</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = webdriver.DesiredCapabilities().INTERNETEXPLORER
caps['acceptSsl... | 0 | 2016-07-20T14:17:26Z | [
"python",
"internet-explorer",
"selenium",
"ssl",
"certificate"
] |
python multiprocessing module, shared multidimensional array | 37,665,002 | <p>I have a code which given two parameters, (k, m) will return a 4d numpy array, my requirement is that I need to calculate this array for possible values of (k,m) with k,m < N and add them up. This is slow in serial so I am trying to learn the multiprocessing module in python to do it.
<a href="https://docs.python... | 1 | 2016-06-06T19:02:48Z | 37,666,174 | <p>One approach would be to create <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.memmap.html" rel="nofollow">memory mapped arrays</a> in the parent process, and pass them to the children to fill. Additionally you should probably have a <code>multiprocessing.Event</code> for every mapped arra... | 0 | 2016-06-06T20:18:59Z | [
"python",
"multiprocessing",
"shared-memory",
"multiprocessing-manager"
] |
Iterate through a for loop using multiple cores in Python | 37,665,089 | <p>I have the following code that is currently running like normal Python code:</p>
<pre><code>def remove_missing_rows(app_list):
print("########### Missing row removal ###########")
missing_rows = []
''' Remove any row that has missing data in the name, id, or description column'''
for row in app_list:
... | 0 | 2016-06-06T19:07:41Z | 37,665,364 | <p>This is probably not cpu bound. Try the code below.</p>
<p>I've used a <code>set</code> for very fast (hash-based) <code>contains</code> (you use it when you invoke <code>if row not in missing_rows</code>, and it's very slow for a long list).</p>
<p>If this is the csv module you're already holding tuples which are... | 1 | 2016-06-06T19:26:02Z | [
"python",
"multithreading",
"parallel-processing",
"multiprocessing",
"bigdata"
] |
Iterate through a for loop using multiple cores in Python | 37,665,089 | <p>I have the following code that is currently running like normal Python code:</p>
<pre><code>def remove_missing_rows(app_list):
print("########### Missing row removal ###########")
missing_rows = []
''' Remove any row that has missing data in the name, id, or description column'''
for row in app_list:
... | 0 | 2016-06-06T19:07:41Z | 37,665,676 | <p>You can use filter, to not iterate twice:</p>
<pre><code>def remove_missing_rows(app_list):
filter_func = lambda row: all((row[1], row[4], row[5]))
return list(filter(filter_func, app_list))
</code></pre>
<p>But if you are doing data analysis, you probably should have a look into pandas.
There you could... | 1 | 2016-06-06T19:47:02Z | [
"python",
"multithreading",
"parallel-processing",
"multiprocessing",
"bigdata"
] |
Python; popen do not pass std* | 37,665,109 | <p>I have a chain of three processes: Process A calls B to spawn C, then B dies. We can call B a "bridge" between two systems A and C. </p>
<p>I want to make sure that C DOES NOT inherit any file descriptors that A opens in order to prevent zombying, which I am currently observing (sometimes A calls B to kill C, and a... | 0 | 2016-06-06T19:09:02Z | 37,665,406 | <p>The <code>os</code> module provides a nice function, <a href="https://docs.python.org/3/library/os.html#os.closerange" rel="nofollow"><code>os.closerange()</code></a>, that will do this for you in one call:</p>
<pre><code>os.closerange(0, 3)
</code></pre>
<p>If you're hunting after phantom open files, I would go a... | 1 | 2016-06-06T19:28:38Z | [
"python",
"process"
] |
Python; popen do not pass std* | 37,665,109 | <p>I have a chain of three processes: Process A calls B to spawn C, then B dies. We can call B a "bridge" between two systems A and C. </p>
<p>I want to make sure that C DOES NOT inherit any file descriptors that A opens in order to prevent zombying, which I am currently observing (sometimes A calls B to kill C, and a... | 0 | 2016-06-06T19:09:02Z | 37,665,871 | <p>When you are starting process C from B, and you don't want it to inherit any file handles, use the following arguments in <code>subprocess.Popen</code>;</p>
<ol>
<li><code>close_fds=True</code></li>
<li>Set <code>stdin</code>, <code>stdout</code> and <code>stderr</code> to <code>subprocess.PIPE</code> or <code>subp... | 3 | 2016-06-06T19:59:05Z | [
"python",
"process"
] |
Accessing variable from another class | 37,665,152 | <p>I'm trying to use a variable from one class in another, but I get the error, "run() missing 1 required positional argument: 'MyWindowClass'"</p>
<pre><code>class TaskThread(QtCore.QThread):
updateProgressSignal = QtCore.pyqtSignal(int)
def run(self, MyWindowClass):
for i in range(101):
se... | 0 | 2016-06-06T19:12:09Z | 37,665,229 | <p>This should work:</p>
<pre><code>class MyWindowClass(QtGui.QDialog):
pbTimeUpdate = .2
class TaskThread(QtCore.QThread):
updateProgressSignal = QtCore.pyqtSignal(int)
def run(self):
for i in range(101):
self.updateProgressSignal.emit(i)
print(MyWindowClass.pbTimeUpdate)
... | 1 | 2016-06-06T19:16:47Z | [
"python",
"python-3.x",
"pyqt4"
] |
kill a user's program if disk usage exceeds 98% in linux | 37,665,181 | <p>I know I can find the amount of space left in my home directory using 'df -h' in linux. But is it possible to write a script/python program which constantly monitors disk usage in my home directory and kills all currently running programs with my user name if my disk usage exceeds 98%. I am using Ubuntu 12.04 server... | 0 | 2016-06-06T19:13:56Z | 37,665,752 | <p>Instead of lurking, adding up space usage over and over (which requires repeated scans of your entire home directory hierarchy) and killing all your processes, you should just set yourself up with a <a href="https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Storage_Administration_Guide/ch... | 3 | 2016-06-06T19:51:35Z | [
"python",
"linux",
"python-2.7",
"ubuntu",
"ubuntu-14.04"
] |
Switching windows in Tkinter | 37,665,190 | <p>I'm trying to create a simple game. I am currently creating a settings page, however when I try to go back to the home screen it doesn't do so. Could you please help me find my bug. Also I'm trying to keep each screen in a function and in my while loop I try to switch to different pages.</p>
<pre><code>import tkint... | 0 | 2016-06-06T19:14:28Z | 37,665,571 | <p>How about you try to not use that while loop ?
I modified your code but its far from perfect:</p>
<pre><code>import tkinter as tk
"""I am going to make a game to use arrow keys to move a character to a flag"""
font, win = "", '' # Define win so you can use 'global' or you cna pass it by argument
world=[ [0,... | 1 | 2016-06-06T19:39:22Z | [
"python",
"tkinter"
] |
Left shift inconsistancy | 37,665,208 | <p>I asked a question yesterday that was beautifully <a href="http://stackoverflow.com/a/37650516/2336654">answered by @jezrael</a></p>
<p>In this he used:</p>
<pre><code>df = pd.DataFrame([[1, 0, 1], [1, 1, 0], [0, 1, 1], [0, 0, 1]])
print (df.T.dot(1 << np.arange(df.shape[0] - 1, -1, -1)))
0 12
1 6
2... | 0 | 2016-06-06T19:15:46Z | 37,665,658 | <p>You have to convert your array of int32 to an array of python objects:</p>
<pre><code>numbers = np.arange(100,dtype=int)
longs = 1 << np.arange(100).astype(object)
</code></pre>
| 4 | 2016-06-06T19:46:08Z | [
"python",
"numpy"
] |
Correctly saved timezone aware datetime object appearing timezone unaware when accessed in Django app | 37,665,280 | <p>In a Django app w/ postgresql backend I maintain, users log in and post comments. Every comment has a timestamp associated to it. </p>
<p>When creating the comment object, I do:</p>
<pre><code>now = datetime.now()
Comment.objects.create(commenter=self.request.user, when=now, text='text')
</code></pre>
<p><code>no... | 0 | 2016-06-06T19:20:41Z | 37,665,470 | <p>Use <a href="https://docs.djangoproject.com/en/1.9/ref/utils/#django.utils.timezone.now" rel="nofollow">timezone.now()</a> instead of datetime.now():</p>
<pre><code>from django.utils import timezone
timezone.now()
</code></pre>
<p>To get now() either with or without timezone globally for the whole app (including P... | 1 | 2016-06-06T19:31:55Z | [
"python",
"django",
"postgresql",
"datetime"
] |
Python: Howto enumerate the virtual superclasses of a class? | 37,665,304 | <p>For any class you can tell the (non-virtual) superclasses via the attribute <code>__mro__</code> and the (non-virtual) subclasses by calling <code>__subclasses__</code>.</p>
<p>For any ABC you can tell all virtual subclasses via the attribute <code>_abc_registry</code>.</p>
<p>Is there a way to tell all virtual su... | 1 | 2016-06-06T19:22:14Z | 37,665,610 | <blockquote>
<p>For any ABC you can tell all virtual subclasses via the attribute '_abc_registry'.</p>
</blockquote>
<p>No you can't. You can only find explicitly registered virtual subclasses that way. Anything handled by <code>__subclasshook__</code> won't show up in your check.</p>
<p>To do what you're trying to... | 1 | 2016-06-06T19:42:36Z | [
"python"
] |
Python: Howto enumerate the virtual superclasses of a class? | 37,665,304 | <p>For any class you can tell the (non-virtual) superclasses via the attribute <code>__mro__</code> and the (non-virtual) subclasses by calling <code>__subclasses__</code>.</p>
<p>For any ABC you can tell all virtual subclasses via the attribute <code>_abc_registry</code>.</p>
<p>Is there a way to tell all virtual su... | 1 | 2016-06-06T19:22:14Z | 37,665,637 | <p>I think you are asking if there is a way to find all classes that would be considered a subclass of a given ABC. Other than iterating through the global and local namespaces and testing them all, the answer is no, there is no way to do this. </p>
<p>By their very nature ABCs do not "know" about their child classes ... | 1 | 2016-06-06T19:44:32Z | [
"python"
] |
Editing netcdf variables and writting out a new netcdf file using python | 37,665,319 | <p>I am working with MITgcm to make some simulations, specifically to work with internal waves models; I got .nc files with my results but some variables are not in exactly the same coordinates. I'll explain myself: I want to work out the components of velocity but, for some numerical reasons that I don't fully underst... | 0 | 2016-06-06T19:23:22Z | 37,677,512 | <p>You create <code>u_out</code> to be a netCDF variable with four dimensions ('time', 'longitude', 'latitude', 'level'), yet you use a 3D slice ([:,:,:]) to assign data to it.</p>
| 1 | 2016-06-07T10:59:52Z | [
"python",
"netcdf"
] |
Pandas: Creating another column with row column multiplication | 37,665,330 | <pre><code>Priority Expected Actual
High 47 30
Medium 22 14
Required 16 5
</code></pre>
<p>I'm trying to create two other columns '<strong>Expected_values</strong>' which will have the values like for the row <strong>High 47*5</stro... | 1 | 2016-06-06T19:23:52Z | 37,665,567 | <p>try:</p>
<pre><code>a = np.array([5, 3, 10])
df['Expected_values'] = df.Expected * a
df['Actual_values'] = df.Actual * a
print df
Priority Expected Actual Expected_values Actual_values
0 High 47 30 235 150
1 Medium 22 14 66 ... | 1 | 2016-06-06T19:39:02Z | [
"python",
"pandas"
] |
Python seaborn, dataframe big, do subplot | 37,665,347 | <p>I have created a dataframe with pandas, further generated a pairplot with seaborn which works fine. The problem is, that the data frame is too big, having 1700 rows and 23 columns. Therefore, the pairplots are too tiny to see anything. (besides, file size is huge, RAM is very busy).</p>
<p>As an example a dataframe... | 0 | 2016-06-06T19:24:25Z | 37,665,413 | <blockquote>
<p>Is there any way to tell seaborn to divide the plot into several pieces? </p>
</blockquote>
<p>not directly, as far as I know.</p>
<blockquote>
<p>Maybe do subplots (5*5) with matplotlib? Thus, the data is visible?</p>
</blockquote>
<p>That sounds like a feasible plan, especially since you probab... | 0 | 2016-06-06T19:29:06Z | [
"python",
"dataframe",
"seaborn"
] |
Python seaborn, dataframe big, do subplot | 37,665,347 | <p>I have created a dataframe with pandas, further generated a pairplot with seaborn which works fine. The problem is, that the data frame is too big, having 1700 rows and 23 columns. Therefore, the pairplots are too tiny to see anything. (besides, file size is huge, RAM is very busy).</p>
<p>As an example a dataframe... | 0 | 2016-06-06T19:24:25Z | 37,665,589 | <p>The answer is "Yes" you can, and you should use the <code>FacetGrid</code> functionality. You can read about that in <a href="http://stanford.edu/~mwaskom/software/seaborn/tutorial/categorical.html" rel="nofollow">this tutorial.</a> And maybe <a href="http://stackoverflow.com/questions/37648266/seaborn-overlay-line-... | -1 | 2016-06-06T19:40:51Z | [
"python",
"dataframe",
"seaborn"
] |
Why can't I make a connection to a remote mysql database? | 37,665,388 | <p>I was given some credentials, but I appear to be missing something here, as the script errors out when trying to make a connection.</p>
<pre><code>import mysql.connector
def test_sql_query():
db = mysql.connector.connect(host='hostname', database='db', user='dbuser,' password='dbpass', port='000')
cur = db... | 0 | 2016-06-06T19:27:22Z | 37,665,489 | <p>You may need to check if the remote database is allowed to connect remotely.</p>
<p><a href="http://stackoverflow.com/questions/14779104/how-to-allow-remote-connection-to-mysql">How to allow remote connection to mysql</a></p>
| 0 | 2016-06-06T19:33:05Z | [
"python",
"mysql",
"jdbc"
] |
Why can't I make a connection to a remote mysql database? | 37,665,388 | <p>I was given some credentials, but I appear to be missing something here, as the script errors out when trying to make a connection.</p>
<pre><code>import mysql.connector
def test_sql_query():
db = mysql.connector.connect(host='hostname', database='db', user='dbuser,' password='dbpass', port='000')
cur = db... | 0 | 2016-06-06T19:27:22Z | 37,665,522 | <p>this line is missing comma:</p>
<pre><code>db = mysql.connector.connect("host='hostname' database='db' user='dbuser' password='dbpass' port='000'")
</code></pre>
<p>replace to</p>
<pre><code>db = mysql.connector.connect(host='hostname', user='dbuser', passwd='dbpass', db='db')
</code></pre>
| 0 | 2016-06-06T19:35:33Z | [
"python",
"mysql",
"jdbc"
] |
Making an AJAX request to a Django view that may require a redirect? | 37,665,449 | <p><strong>Introduction</strong></p>
<p>I am getting an error when trying to request a particular Django view from AJAX. This view redirects the user if they have not yet authorized the site with Google. I believe that the problem lies in the fact that I am trying to perform the redirect from "within" a view requested... | 0 | 2016-06-06T19:30:26Z | 38,901,197 | <p>I had a similar problem while trying to sync some contacts on google and start the whole process from the client side. Managed to work around it by returning the redirect url (instead of doing a <code>HttpResponseRedirect</code>) and redirecting from jquery.</p>
<p>So, instead of <code>return HttpResponseRedirect('... | 0 | 2016-08-11T16:01:21Z | [
"javascript",
"python",
"ajax",
"django",
"redirect"
] |
Python Pandas compare two dataframes to assign country to phone number | 37,665,457 | <p>I have two dataframes that I read in via csv. Dataframe one consists of a phone number and some additional data. The second dataframe contains country codes and country names.</p>
<p>I want to take the phone number from the first dataset and compare it to the country codes of the second. Country codes can between o... | 2 | 2016-06-06T19:30:58Z | 37,675,494 | <p>i would do it this way:</p>
<pre><code>cl = pd.read_csv('country_list.csv', sep=';', dtype={'country_code':str})
ll = pd.read_csv('phones.csv', skipinitialspace=True, dtype={'phonenumber':str})
lookup = cl['country_code']
lookup.index = cl['country_code']
ll['country_code'] = (
ll['phonenumber']
.apply(la... | 2 | 2016-06-07T09:28:42Z | [
"python",
"pandas",
"dataframe",
"startswith"
] |
Access json content of http post request with Klein in python | 37,665,554 | <p>I have a simple http client in python that send the http post request like this:</p>
<pre><code>import json
import urllib2
from collections import defaultdict as dd
data = dd(str)
req = urllib2.Request('http://myendpoint/test')
data["Input"] = "Hello World!"
response = urllib2.urlopen(req, json.dumps(data))
</code>... | 1 | 2016-06-06T19:37:48Z | 37,665,773 | <p>Asaik Klein doesn't give you direct access to the json data, however you can use this code to access it:</p>
<pre><code>import json
@app.route('/test', methods = ['POST'])
@inlineCallbacks
def test(request):
output = dd()
data = json.loads(request.content.read()) # <=== This will work
</code></pre>
| 2 | 2016-06-06T19:52:38Z | [
"python",
"klein-mvc"
] |
Reflect Python list change in string attribute | 37,665,739 | <p>I'm searching an elegant (an efficient) way to implement the following:</p>
<p>I have a class storing a list of values as a <strong>string</strong> (with a separator, eg.: " - "). I use a property (getter and setter) to convert this string into a Python <code>list</code>.</p>
<pre><code>class C(object):
def __... | 1 | 2016-06-06T19:51:09Z | 37,665,853 | <p>I would approach this by overloading certain operators you want to support, for example the <a href="https://docs.python.org/3/reference/datamodel.html#object.__iadd__" rel="nofollow">+= operator by defining <code>__iadd__</code></a>. You would then be able to do something like:</p>
<pre><code>class C(object):
... | 1 | 2016-06-06T19:58:03Z | [
"python",
"properties",
"python-descriptors"
] |
Reflect Python list change in string attribute | 37,665,739 | <p>I'm searching an elegant (an efficient) way to implement the following:</p>
<p>I have a class storing a list of values as a <strong>string</strong> (with a separator, eg.: " - "). I use a property (getter and setter) to convert this string into a Python <code>list</code>.</p>
<pre><code>class C(object):
def __... | 1 | 2016-06-06T19:51:09Z | 37,666,586 | <p>Maybe I'm oversimplifying your problem because you've oversimplified your first example, but I'm going to agree with some of the commenters and propose that you change around the way you store this. <strong>Store the list, produce the string on demand.</strong></p>
<pre><code>In [1]: class C(object):
...: de... | 1 | 2016-06-06T20:44:17Z | [
"python",
"properties",
"python-descriptors"
] |
A loop for adding list element without high memory performance? | 37,665,760 | <p>Everybody,</p>
<pre><code>a =[0, 0, 2, 4, 6]
x=5
</code></pre>
<p>This a list (<code>a</code>) and a fix value (<code>x</code>). </p>
<p>I need a loop codes which must add with x every element of list and add this value with previous list elements in every loop ( loop must continue as x value). Other words resul... | -4 | 2016-06-06T19:51:59Z | 37,665,885 | <p>You need to change the values in <code>a</code>, not just add to the numbers you get out of <code>a</code> (because you'll keep getting the same ones out). Also, you need to print out the original values.</p>
| 0 | 2016-06-06T20:00:27Z | [
"python",
"list",
"loops",
"while-loop"
] |
A loop for adding list element without high memory performance? | 37,665,760 | <p>Everybody,</p>
<pre><code>a =[0, 0, 2, 4, 6]
x=5
</code></pre>
<p>This a list (<code>a</code>) and a fix value (<code>x</code>). </p>
<p>I need a loop codes which must add with x every element of list and add this value with previous list elements in every loop ( loop must continue as x value). Other words resul... | -4 | 2016-06-06T19:51:59Z | 37,665,935 | <pre><code>def process(x, memo):
return [n+x if n else n for n in memo]
res = a
memo = a
for _ in range(x - 1):
memo = process(x, memo)
res.extend(memo)
</code></pre>
| 0 | 2016-06-06T20:03:39Z | [
"python",
"list",
"loops",
"while-loop"
] |
A loop for adding list element without high memory performance? | 37,665,760 | <p>Everybody,</p>
<pre><code>a =[0, 0, 2, 4, 6]
x=5
</code></pre>
<p>This a list (<code>a</code>) and a fix value (<code>x</code>). </p>
<p>I need a loop codes which must add with x every element of list and add this value with previous list elements in every loop ( loop must continue as x value). Other words resul... | -4 | 2016-06-06T19:51:59Z | 37,665,958 | <p>I think this does mostly what you want (at least, as I understand the question)...</p>
<pre><code>def make_it_so(a, x):
i = 0
counter=0
while counter < x:
for i in a:
if i == 0:
yield 0
else:
yield i + counter * x
counter = counter + 1
# Demo
for item in make_it_so([0, ... | 2 | 2016-06-06T20:05:19Z | [
"python",
"list",
"loops",
"while-loop"
] |
Saving an array inside a column of a matrix in numpy shape error | 37,665,781 | <p>Let's say I do some calculation and I get a matrix of size 3 by 3 each time in a loop. Assume that each time, I want to save such matrix in a column of a bigger matrix, whose number of rows is equal to 9 (total number of elements in the smaller matrix). first I reshape the smaller matrix and then try to save it into... | 2 | 2016-06-06T19:53:16Z | 37,666,465 | <p>try:</p>
<pre><code>import numpy as np
Big = np.zeros((9,3))
Small = np.random.rand(3,3)
Big[:,0]= np.reshape(Small,(9,))
print Big
</code></pre>
<p>or:</p>
<pre><code>import numpy as np
Big = np.zeros((9,3))
Small = np.random.rand(3,3)
Big[:,0]= Small.reshape((9,1))
print Big
</code></pre>
<p>or:</p>
<pre><cod... | 1 | 2016-06-06T20:36:34Z | [
"python",
"arrays",
"numpy"
] |
How to create new closure cell objects? | 37,665,862 | <p>I need to monkey-patch my library to replace an instance of a symbol, and it's getting referenced by some function closures. I need to copy those functions (since I also need access to original unpatched version of the function as well), but <code>__closure__</code> is immutable, and I can't <code>copy.copy</code> i... | 0 | 2016-06-06T19:58:37Z | 37,666,086 | <p>The simple way to make a closure cell would be to make a closure:</p>
<pre><code>def make_cell(val=None):
x = val
def closure():
return x
return closure.__closure__[0]
</code></pre>
<p>If you want to reassign a cell's contents, you'll need to make a <a href="https://docs.python.org/2/c-api/cell... | 1 | 2016-06-06T20:13:36Z | [
"python",
"python-2.7",
"closures",
"monkeypatching"
] |
python IOError [Errno 13] string vs Tk | 37,665,866 | <p>When I use Tk.askopenfiledialogbox and choose the directory I want, then open each file with <code>open(files, "r")</code> it works fine. However, when I hard code the path into a string I get access denied IOError [Errno13]. Here is my code:</p>
<pre><code> data_path = "C:\Data\DataSubDir"
datadir = [x[0] f... | 0 | 2016-06-06T19:58:50Z | 37,665,924 | <p>Either escape your backslashes </p>
<pre><code>data_path = "C:\\Data\\DataSubDir"
</code></pre>
<p>or use a raw string: </p>
<pre><code>data_path = r"C:\Data\DataSubDir"
</code></pre>
<p>With a Tk dialog box the string is in the correct format.</p>
| 2 | 2016-06-06T20:02:34Z | [
"python",
"python-2.7",
"file",
"tkinter",
"tk"
] |
Rethinkdb: returning more than one object from a query | 37,665,870 | <p>I have a table with some rows that look like this:</p>
<pre><code>{
"id": "12345"
"created_date": Fri May 27 2016 22:06:25 GMT+00:00 ,
"image": true
} {
"id": "6789"
"created_date": Mon May 30 2016 07:48:35 GMT+00:00 ,
"video": true
}{
"id": "12345"
"created_date": Fri May 21 2016 22:06:25 GMT+00:... | 2 | 2016-06-06T19:59:01Z | 37,666,014 | <p>You can combine two queries by writing something like <code>r.expr([query1, query2])</code> and it should work.</p>
| 2 | 2016-06-06T20:08:49Z | [
"python",
"nosql",
"rethinkdb",
"rethinkdb-python"
] |
How can I modify Django's login_required decorator on a custom Pinax installation? | 37,665,971 | <p>I would like to have Django's <code>@login_required</code> decorator test whether a particular field on a User has been set to something other than None. (The added field has null = true and a default of None.)</p>
<p>Newly created User objects do indeed have a value of None for the field, but an obvious change to ... | 2 | 2016-06-06T20:06:02Z | 37,668,757 | <p>I see from your code, that you have actually encountered <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.decorators.user_passes_test" rel="nofollow">user_passes_test</a> and this in fact is what you should use instead of modifying the source code of login_required directly.</p... | 2 | 2016-06-07T00:28:10Z | [
"python",
"django",
"pinax"
] |
mysql.connector multiple queries: Error -1: No result set to fetch from | 37,665,993 | <p>In Python 2.7.3, Wins 10, MySQL remote server 5.6.23, MySQL.connector 2.1.3,</p>
<p>If I wanna run these two queries together in Python MySQL.connector:</p>
<pre><code>SELECT * FROM A LIMIT 5;
SELECT DISTINCT COLUM_A FROM B;
</code></pre>
<p>I got the following error message using the code below:</p>
<pre><cod... | 0 | 2016-06-06T20:07:27Z | 38,699,453 | <p>Change the code to-</p>
<pre><code>iterable = cursor.execute(sql1,multi=True)
for item in iterable:
print(item.fetchall())
</code></pre>
<p>Should work.</p>
| 0 | 2016-08-01T12:53:22Z | [
"python",
"mysql",
"mysql-connector"
] |
How to click on a video using Selenium | 37,666,063 | <p>I'm new to coding using python and it's libraries, and also new to stackoverflow so I apologize if I'm not acquainted to some things.</p>
<p>Anyway to the question. I'm trying to write code that automates playing a video from the website that. Here's an example link:</p>
<p><a href="http://www.shush.se/index.php?i... | 0 | 2016-06-06T20:12:16Z | 37,666,649 | <p>Even though you don't know the exact id, you know that it will start with "jw6playerid". The following works for me:</p>
<pre><code>elements = driver.find_elements_by_xpath("//*[contains(@id, 'jw6playerid')]")
elements[0].click()
</code></pre>
| 0 | 2016-06-06T20:47:52Z | [
"python",
"selenium",
"video"
] |
python subplot for loop | 37,666,087 | <p>I'm trying to use a for lop to populate a subplot but I can't do so. here is a summary of my code:
Edit 1:</p>
<pre><code>for idx in range(8):
img = f[img_set[ind[idx]][0]]
patch = img[:,col1+1:col2, row1+1:row2]
if idx < 3:
axarr[0,idx] = plt.imshow(patch)
elif idx <6:
axarr[1,idx-3... | 1 | 2016-06-06T20:13:37Z | 37,666,342 | <p>You forgot to create the sub plots. You can use <code>add_subplot()</code> (<a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.add_subplot" rel="nofollow">http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.add_subplot</a>). For example,</p>
<pre><code>import matplotlib.pyplo... | 1 | 2016-06-06T20:28:26Z | [
"python",
"matplotlib"
] |
Unable to pip2.7 install at Mac | 37,666,137 | <p>I am trying to install 'mrjob' package at Python 2.7. However when I ran 'pip2.7 install mrjob', the following error appears. Does anyone have the solution to this? Note: I have both Python 2.7 and 3.5 install at my mac. </p>
<pre><code>Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-... | 0 | 2016-06-06T20:16:55Z | 37,666,170 | <p>Run it with elevated privileges.</p>
<p><strong>sudo</strong> pip2.7 install mrjob</p>
| 1 | 2016-06-06T20:18:55Z | [
"python",
"python-2.7",
"pip"
] |
Importing caffe results in ImportError: "No module named google.protobuf.internal" (import enum_type_wrapper) | 37,666,241 | <p>I installed Anaconda Python on my machine. When I start the Python Interpreter and type "import caffe" in the Python shell, I get the following error:</p>
<pre><code>ImportError: No module named google.protobuf.internal
</code></pre>
<p>I have the following files:</p>
<pre><code>wire_format_lite_inl.h
wire_forma... | 1 | 2016-06-06T20:22:59Z | 37,868,338 | <p>If you are using Ubuntu, try installing protobuf using</p>
<pre><code>sudo apt-get install protobuf
</code></pre>
<p>It solved the same problem that I faced.</p>
| 1 | 2016-06-16T19:57:15Z | [
"python",
"protocol-buffers",
"caffe",
"google-protobuf"
] |
Importing caffe results in ImportError: "No module named google.protobuf.internal" (import enum_type_wrapper) | 37,666,241 | <p>I installed Anaconda Python on my machine. When I start the Python Interpreter and type "import caffe" in the Python shell, I get the following error:</p>
<pre><code>ImportError: No module named google.protobuf.internal
</code></pre>
<p>I have the following files:</p>
<pre><code>wire_format_lite_inl.h
wire_forma... | 1 | 2016-06-06T20:22:59Z | 37,905,483 | <p>This is probably because you have two python environments in your machine, the one provided by your linux distribution(<code>pip</code>) and the other by the anaconda environment (<code>/home/username/anaconda2/bin/pip</code>).</p>
<h1>Try installing protobuf for both environments to be sure</h1>
<p><code>pip inst... | 6 | 2016-06-19T08:52:30Z | [
"python",
"protocol-buffers",
"caffe",
"google-protobuf"
] |
cassandra-driver: ImportError: No module named queue | 37,666,269 | <p>I'm installing cassandra-driver with pip on OSX 10.11.
Straight out of pip, cassandra-driver gives this error:</p>
<pre><code>traceback (most recent call last): File "syncS3ToCassandra.py", line 19, in <module>
from cassandra.cluster import Cluster File "cassandra/cluster.py", line 48, in init cassandra.c... | 0 | 2016-06-06T20:24:52Z | 37,666,389 | <p>From the source code, you need the package <strong>six</strong> to be installed and it should have a subpackage <strong>moves</strong> which contains a module <strong>queue.py</strong>:</p>
<pre><code>38 from six.moves.queue import Queue, Empty
</code></pre>
<p>Can you try to reinstall six?</p>
<ol>
<li>pip un... | 1 | 2016-06-06T20:31:54Z | [
"python",
"cassandra",
"datastax"
] |
cassandra-driver: ImportError: No module named queue | 37,666,269 | <p>I'm installing cassandra-driver with pip on OSX 10.11.
Straight out of pip, cassandra-driver gives this error:</p>
<pre><code>traceback (most recent call last): File "syncS3ToCassandra.py", line 19, in <module>
from cassandra.cluster import Cluster File "cassandra/cluster.py", line 48, in init cassandra.c... | 0 | 2016-06-06T20:24:52Z | 37,666,491 | <p>Since <strong>cassandra-driver</strong> (version 3.4.1) is only available as <code>.tar.gz</code> package, you have to recompile it from the sources. This is what pip do.</p>
<p>I successfully install it on OSX 10.11.5 (it took at least one minute to compile).</p>
<p>I try this:</p>
<pre><code>$ python
Python 2.7... | 1 | 2016-06-06T20:38:15Z | [
"python",
"cassandra",
"datastax"
] |
cassandra-driver: ImportError: No module named queue | 37,666,269 | <p>I'm installing cassandra-driver with pip on OSX 10.11.
Straight out of pip, cassandra-driver gives this error:</p>
<pre><code>traceback (most recent call last): File "syncS3ToCassandra.py", line 19, in <module>
from cassandra.cluster import Cluster File "cassandra/cluster.py", line 48, in init cassandra.c... | 0 | 2016-06-06T20:24:52Z | 37,667,259 | <p>I solved this issue by updating my ~/.profile with:</p>
<pre><code>export PATH=/usr/local/bin:/usr/local/sbin:$PATH
</code></pre>
<p>and installing python-2.7.11</p>
<pre><code>$ brew install python
</code></pre>
<p>Then restarting my shell.</p>
| 0 | 2016-06-06T21:36:10Z | [
"python",
"cassandra",
"datastax"
] |
cassandra-driver: ImportError: No module named queue | 37,666,269 | <p>I'm installing cassandra-driver with pip on OSX 10.11.
Straight out of pip, cassandra-driver gives this error:</p>
<pre><code>traceback (most recent call last): File "syncS3ToCassandra.py", line 19, in <module>
from cassandra.cluster import Cluster File "cassandra/cluster.py", line 48, in init cassandra.c... | 0 | 2016-06-06T20:24:52Z | 39,929,093 | <p>I also meet this issue on my mbp. And there are some other problems that I can't uninstall six. I use easy_install to update version from 1.4.1 to 1.10.0 to fix it. </p>
<pre><code>$sudo easy_install -U six
</code></pre>
<p>Hope it can help you.</p>
| 1 | 2016-10-08T05:40:07Z | [
"python",
"cassandra",
"datastax"
] |
python multiprocessing IOError: [Errno232] The pipe is being closed | 37,666,289 | <p>The following code will count all 750 joins and will print the results queue, but after it does that it gets stuck in deadlock. If I assign results to multiprocessing.Queue(), the program deadlocks immediately.</p>
<pre><code>def function(job, results):
# do stuff
results_q.put(stuff)
if __name__ == '__ma... | 0 | 2016-06-06T20:25:56Z | 37,685,681 | <p>I think that this problem is caused by creating multiple processes that. This is not necessarily a deadlock, but the algorithm is taking a long time to instantiate methods. I made a test with threads and apparently worked well faster. Look the code:</p>
<pre><code>import multiprocessing
import itertools
import thre... | 1 | 2016-06-07T17:29:35Z | [
"python",
"multiprocessing",
"deadlock"
] |
Using stencil to mask image in kv | 37,666,296 | <p>Been looking through the documentation but can't find out how to properly mask an image in kv. This is my kv code:</p>
<pre><code><MyImage@AsyncImage>:
source: 'http://webserver/120x100.png'
canvas.before:
StencilPush
RoundedRectangle:
size: 120,100
</code></pre>
| 2 | 2016-06-06T20:26:21Z | 37,666,411 | <p>You probably need to to call StencilUse to use the stencil layer. Also remember to unuse and pop:</p>
<pre><code><MyImage@AsyncImage>:
source: 'http://webserver/120x100.png'
canvas.before:
StencilPush
RoundedRectangle:
size: 120,100
StencilUse
canvas.after:
... | 2 | 2016-06-06T20:33:55Z | [
"python",
"kivy",
"kivy-language"
] |
NODEJS SMB2 - convert buffer to date and time | 37,666,301 | <p>I'm using this package for connecting to shared directory(<a href="https://www.npmjs.com/package/@marsaud/smb2" rel="nofollow">npm</a>). Fork from original smb2. </p>
<p>I'm trying to change directory readdir function (now only returns filenames).
So I looked what samba returns I all I can get "parsed" is this:</p... | 1 | 2016-06-06T20:26:26Z | 37,666,706 | <p>You can read the buffer with <a href="https://nodejs.org/api/buffer.html#buffer_buf_readdoublebe_offset_noassert" rel="nofollow">buffer.readDoubleBE()</a>:</p>
<pre><code>// This assumes the name of the object returned by smb2 is 'obj'
var createdAt = new Date(obj.CreationTime.readDoubleBE());
</code></pre>
| 0 | 2016-06-06T20:52:17Z | [
"javascript",
"python",
"node.js",
"buffer",
"smb"
] |
NODEJS SMB2 - convert buffer to date and time | 37,666,301 | <p>I'm using this package for connecting to shared directory(<a href="https://www.npmjs.com/package/@marsaud/smb2" rel="nofollow">npm</a>). Fork from original smb2. </p>
<p>I'm trying to change directory readdir function (now only returns filenames).
So I looked what samba returns I all I can get "parsed" is this:</p... | 1 | 2016-06-06T20:26:26Z | 37,688,947 | <p>So, after long search on microsoft msd and npm. I find that buffer is 64bites length(8bytes). It consist of 2 dwords. The meaning of the unbuffered integer is FILETIME timestamp. </p>
<p>So if I wanted to parse creationTime from that buffer I needed to do this :</p>
<pre><code>buffer = v.LastWriteTime;
var low = b... | 0 | 2016-06-07T20:41:11Z | [
"javascript",
"python",
"node.js",
"buffer",
"smb"
] |
proper way for zipping files in python | 37,666,333 | <p>I'm trying to create a zip file by zipping couple text files from a specific directory. My code looks like the following:</p>
<pre><code>import zipfile,os
project='C:/Users/user1/Documents/work/filesToZip'
dirlist = os.listdir(project)
print dirlist
zip_name = zipfile.ZipFile(os.path.join(project,'jobs.zip'),'w')... | 1 | 2016-06-06T20:28:04Z | 37,666,432 | <p>For python 2.7+ you can use <a href="https://docs.python.org/2/library/shutil.html" rel="nofollow"><code>shutil</code></a> instead:</p>
<pre><code>from shutil import make_archive
make_archive(
'zipfile_name',
'zip', # the archive format - or tar, bztar, gztar
root_dir=None, # root for archive - ... | 1 | 2016-06-06T20:34:49Z | [
"python",
"zip"
] |
proper way for zipping files in python | 37,666,333 | <p>I'm trying to create a zip file by zipping couple text files from a specific directory. My code looks like the following:</p>
<pre><code>import zipfile,os
project='C:/Users/user1/Documents/work/filesToZip'
dirlist = os.listdir(project)
print dirlist
zip_name = zipfile.ZipFile(os.path.join(project,'jobs.zip'),'w')... | 1 | 2016-06-06T20:28:04Z | 37,666,474 | <pre><code>import zipfile,os
project='C:/Users/user1/Documents/work/filesToZip'
original_dir= os.getcwd()
os.chdir(project)
dirlist = os.listdir(".")
print dirlist
zip_name = zipfile.ZipFile('./jobs.zip','w')
for file in dirlist:
zip_name.write('./'+file)
zip_name.close()
os.chdir(original_dir)
</code></pre>
| 1 | 2016-06-06T20:37:04Z | [
"python",
"zip"
] |
proper way for zipping files in python | 37,666,333 | <p>I'm trying to create a zip file by zipping couple text files from a specific directory. My code looks like the following:</p>
<pre><code>import zipfile,os
project='C:/Users/user1/Documents/work/filesToZip'
dirlist = os.listdir(project)
print dirlist
zip_name = zipfile.ZipFile(os.path.join(project,'jobs.zip'),'w')... | 1 | 2016-06-06T20:28:04Z | 37,666,607 | <p><code>ZipFile.write</code> has <a href="https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.write" rel="nofollow">an optional second parameter <code>archname</code></a>
which does exactly what you want.</p>
<pre><code>import zipfile,os
project='C:/Users/user1/Documents/work/filesToZip'
# prevent adding... | 2 | 2016-06-06T20:46:00Z | [
"python",
"zip"
] |
passing a cookie as header using request.COOKIES.get('cfrtoken') not working | 37,666,356 | <p>I have an application which needs cookie information passed headers. When I am passing using </p>
<pre><code> childrequest.add_header('Cookie','cfrtoken=blahblah')
</code></pre>
<p>It's working as expected.</p>
<p>But when I try to get the same cookie information dynamically its failing.</p>
<pre><code>childrequ... | 0 | 2016-06-06T20:29:38Z | 37,668,777 | <p>You're just missing a <code>'</code> in <code>childrequest.add_header('Cookie','cfrtoken= + request.COOKIES.get('cfrtoken'))</code></p>
<p>Should be :</p>
<p><code>childrequest.add_header('Cookie','cfrtoken=' + request.COOKIES.get('cfrtoken'))</code></p>
| 0 | 2016-06-07T00:29:58Z | [
"python",
"django",
"python-3.x",
"cookies"
] |
Obtaining HTML source code with Python cookie | 37,666,410 | <pre><code> import urllib
#my url here stored as url
htmlfile = urllib.urlopen(url)
htmltext = htmlfile.read()
print(htmltext)
</code></pre>
<p>I'm trying to get source code from a url</p>
<p>I get source code but it is from a different page saying two things;
please enable cookies and
this domai... | 1 | 2016-06-06T20:33:43Z | 37,666,602 | <p>You may have to set an url opener</p>
<pre><code>def createOpener(self):
handlers = []
cj = MyCookieJar();
cj.set_policy(cookielib.DefaultCookiePolicy(rfc2965=True))
cjhdr = urllib2.HTTPCookieProcessor(cj)
handlers.append... | 0 | 2016-06-06T20:45:42Z | [
"python",
"html",
"cookies"
] |
applying an operation to multiple columns having multiple columns in the result | 37,666,431 | <p>in sql the query would look like <code>select id, avg(x), avg(y), max(x), max(y) from table group by id</code>
can it be transformed into a single operation on pandas data frame?
I can get each function result like</p>
<pre><code>mydf['center_x'] = mydf.groupby('id')['x'].mean()
mydf['center_y'] = mydf.groupby('i... | 3 | 2016-06-06T20:34:46Z | 37,666,473 | <p>Yes, this is supported, see the documentation <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once" rel="nofollow">here</a>.</p>
<p>To cite from there:</p>
<pre><code>In [56]: grouped = df.groupby('A')
In [57]: grouped['C'].agg([np.sum, np.mean, np.std])
Out[57]:
... | 4 | 2016-06-06T20:37:03Z | [
"python",
"pandas"
] |
Gmail API Quickstart AttributeError in Python | 37,666,552 | <p>I'm trying to learn Gmail API with Python using Mac OSX.</p>
<p>I have a standard problem for this OS: the default installation of the "six" module is loaded before the one that pip installed. <a href="https://developers.google.com/gmail/api/quickstart/python#troubleshooting" rel="nofollow">Google's solution</a>(a... | 1 | 2016-06-06T20:42:25Z | 37,697,397 | <p>From this <a href="https://github.com/google/google-api-python-client/issues/100" rel="nofollow">Python issues thread</a>, it's a given workaround to set the system environment variable PYTHONPATH to point directly to pip's install directory and add:</p>
<pre><code>export PYTHONPATH=/Library/Python/2.7/site-package... | 0 | 2016-06-08T08:39:55Z | [
"python",
"osx",
"gmail-api"
] |
Gmail API Quickstart AttributeError in Python | 37,666,552 | <p>I'm trying to learn Gmail API with Python using Mac OSX.</p>
<p>I have a standard problem for this OS: the default installation of the "six" module is loaded before the one that pip installed. <a href="https://developers.google.com/gmail/api/quickstart/python#troubleshooting" rel="nofollow">Google's solution</a>(a... | 1 | 2016-06-06T20:42:25Z | 37,706,569 | <p>Solution i have found: Reinstall Python 2.7, restart terminal.</p>
| 0 | 2016-06-08T15:16:29Z | [
"python",
"osx",
"gmail-api"
] |
Can a class inherit the properies of a namedtuple? | 37,666,557 | <p>I have a named tuple.</p>
<pre><code>import collections
MyNamedTuple = collections.namedtuple('MyNamedTuple', 'prop1 prop2 foo bar')
</code></pre>
<p>I would like to define a class that can be initialized by these named tuples.</p>
<pre><code>class MyClass():
def __init__(self, t):
self.prop1 = t.pro... | 1 | 2016-06-06T20:42:42Z | 37,666,653 | <p>You've got a couple options... <code>namedtuple</code> returns a class -- You can subclass it directly:</p>
<pre><code>class MyClass(MyNamedTuple):
...
</code></pre>
<p>Of course, this means that <code>MyClass</code> <em>is</em> a <code>tuple</code> which might not be desirable...</p>
<p>You can also use the ... | 2 | 2016-06-06T20:48:10Z | [
"python",
"namedtuple"
] |
What statement in Python has the exactly same function as do statement in SAS | 37,666,561 | <p>What statement in Python has the exactly same function as <strong>do</strong> statement in SAS? Or how can I translate the following SAS code into python language? thanks</p>
<pre><code>do i = 1 to nreach ;
rchld[i,] = incddsrc[i,]+carryf[i,]#node[data[i,jfnode],] ;
</code></pre>
| -1 | 2016-06-06T20:42:59Z | 37,668,323 | <p>Here is a simplified SAS statement with do from their support site:</p>
<pre><code>if years>5 then
do;
months=years*12;
end;
else yrsleft=5-years;
</code></pre>
<p>Here the code nested in do/end will execute only if the var years is greater than 5. If not it executes the else statement.</p>
<p>... | 0 | 2016-06-06T23:29:10Z | [
"python"
] |
Beautifulsoup, urllib2 and requests did not find all HTML tags from 9gag.com | 37,666,562 | <p>I am trying to scrape 9gag comment section to do some sentiment analysis and label the post as positive or negative. The ultimate goal is to train the data of thousands of posts and the predict the sentiment of the post based on Comment count, post upvotes, top ten ten comment upvotes, and the title of the post. </p... | 3 | 2016-06-06T20:43:00Z | 37,666,683 | <p>Their comments are loaded via <a href="https://facebook.github.io/react/index.html" rel="nofollow">reactjs</a>, you'll need something that executes javascript in order to scrape the comments section.</p>
<p>A few to get you started:</p>
<ul>
<li><a href="http://jeanphix.me/Ghost.py/" rel="nofollow">ghost.py</a></l... | 1 | 2016-06-06T20:50:13Z | [
"python",
"web-scraping",
"beautifulsoup",
"urllib2",
"urllib"
] |
Beautifulsoup, urllib2 and requests did not find all HTML tags from 9gag.com | 37,666,562 | <p>I am trying to scrape 9gag comment section to do some sentiment analysis and label the post as positive or negative. The ultimate goal is to train the data of thousands of posts and the predict the sentiment of the post based on Comment count, post upvotes, top ten ten comment upvotes, and the title of the post. </p... | 3 | 2016-06-06T20:43:00Z | 37,667,426 | <p>The data is loaded using React but you can do a little bit of parsing and get all the data you need in <em>json</em> format:</p>
<pre><code>import requests
from urlparse import urljoin
import ast
base = "http://9gag.com/"
# these are the params to get the json.
params = {"appId": "",
"url": "",
... | 2 | 2016-06-06T21:51:50Z | [
"python",
"web-scraping",
"beautifulsoup",
"urllib2",
"urllib"
] |
Using python df.replace with dict does not permanently change values | 37,666,575 | <p>I generated a DataFrame that includes a column called "pred_categories" with numerical values of 0, 1, 2, and 3. See below:</p>
<pre><code> fileids pred_categories
0 /Saf/DA192069.txt 3
1 /Med/DA000038.txt 2
2 /Med/DA000040.txt 2
3 /Saf/DA191905.txt... | 2 | 2016-06-06T20:43:27Z | 37,666,587 | <p>Per default <code>.replace()</code> returns changed DF, but it doesn't change it <em>in place</em>, so you have to do it this way:</p>
<pre><code>df = df.replace({'pred_categories': di})
</code></pre>
<p>or</p>
<pre><code>df.replace({'pred_categories': di}, inplace=True)
</code></pre>
| 3 | 2016-06-06T20:44:20Z | [
"python",
"pandas",
"dataframe"
] |
python panda to calculate rolling means | 37,666,601 | <p>I am trying to calculate the bollinger band of facebook stock. But I found the rm_FB (the calculated rolling mean) are all nan</p>
<p><a href="http://i.stack.imgur.com/KTuID.png" rel="nofollow"><img src="http://i.stack.imgur.com/KTuID.png" alt="BollingerBands"></a></p>
<pre><code>def get_rolling_mean(values, windo... | 1 | 2016-06-06T20:45:26Z | 37,668,191 | <p>I was confused by how you asked. I manufactured the data and created a function I hope helps.</p>
<pre><code>import pandas as pd
import numpy as np
def bollinger_bands(s, k=2, n=20):
"""get_bollinger_bands DataFrame
s is series of values
k is multiple of standard deviations
n is rolling window
... | 1 | 2016-06-06T23:12:03Z | [
"python",
"numpy",
"pandas"
] |
How to detect expired password using Python Fabric? | 37,666,626 | <p>Using the following code, I'm unable to get Fabric to detect an expired password prompt at login. The session doesn't timeout, and the abort_on_prompts parameter doesn't appear to be triggering. How I can configure Fabric to detect this state?</p>
<pre><code>from fabric.api import env, run, execute
from fabric im... | 0 | 2016-06-06T20:46:41Z | 37,701,059 | <p>Fabric include a way to answer prompts questions.</p>
<p>You can use <a href="http://docs.fabfile.org/en/1.9/usage/env.html#prompts" rel="nofollow"><code>prompts</code></a> dictionary on the <a href="http://docs.fabfile.org/en/1.9/api/core/context_managers.html#fabric.context_managers.settings" rel="nofollow"><code... | 0 | 2016-06-08T11:20:54Z | [
"python",
"ssh",
"fabric"
] |
Clicking on a dynamic link with scrapy | 37,666,711 | <p>I have a clickable link on a dynamically created page, that looks like:</p>
<pre><code><a id="ucResultsGrid_X0A" href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ucResultsGrid$X0A", "", false, "", "webProperty.aspx?dbkey=parkercad&amp;stype=id&amp;sdata=X0A&amp;time=2016060... | -1 | 2016-06-06T20:52:43Z | 37,666,838 | <p>I'm not familiar with Scrapy but I can suggest an alternative :-)</p>
<p>Have you looked into an alternative such as <a href="http://casperjs.org/" rel="nofollow">CasperJS</a>? They provide an example for <a href="http://docs.casperjs.org/en/latest/quickstart.html#a-minimal-scraping-script" rel="nofollow">Minimal S... | 1 | 2016-06-06T21:01:42Z | [
"javascript",
"python",
"scrapy"
] |
Pandas replace type issue | 37,666,731 | <p>I have a pandas dataframe with a row that contains data such as:</p>
<pre><code>1 year
1 month
1 week
4 year
3 week
</code></pre>
<p>etc etc</p>
<p>I am trying to replace anything that contains "month" or "week" to 0</p>
<pre><code>train_df.age["weeks" in train_df.age] = 0
</code></pre>
<p>and </p>
<pre><code>... | 1 | 2016-06-06T20:54:14Z | 37,666,756 | <p>Use <code>str.contains</code>:</p>
<pre><code>train_df.loc[train_df['age'].str.contains(r'week|month'), 'age'] = 0
</code></pre>
<p>Here we pass a regex pattern that looks for whether the row contains either 'week' or 'month' and use the boolean mask to selectively update just the rows on interest:</p>
<pre><cod... | 1 | 2016-06-06T20:56:42Z | [
"python",
"pandas"
] |
Python: concurrent file seek | 37,666,760 | <p>I am looking at a way to allow concurrent file object seeking.</p>
<p>As a test case of file seeking going wary:</p>
<pre><code>#!/usr/bin/env python2
import time, random, os
s = 'The quick brown fox jumps over the lazy dog'
# create some file, just for testing
f = open('file.txt', 'w')
f.write(s)
f.close()
# th... | 1 | 2016-06-06T20:56:47Z | 37,666,974 | <p>You cannot - Python I/O builds on C's I/O, and there is only one "current file position" per open file in C. That's inherently shared.</p>
<p>What you can do is perform your seek+read under protection of an interprocess lock.</p>
<p>Like define:</p>
<pre><code>def process_init(lock):
global seek_lock
see... | 0 | 2016-06-06T21:13:22Z | [
"python",
"concurrency"
] |
Adding an x number of new lines to the end of a file Python | 37,666,785 | <p>I have multiple files that I am looping over. If an individual file doesn't have a certain length then I want to mask the lines in that file so that it isn't used but so that the shape remains the same for certain calculations I will need to do in the future. So far this is the code that I have:</p>
<pre><code>patt... | 0 | 2016-06-06T20:58:03Z | 37,667,170 | <p>If you don't really need the list of file names for processing, then this can collapse to:</p>
<pre><code>for filename in glob.iglob(pattern):
with open(filename, 'r+a') as fd:
for num_lines, line in enumerate(fd): pass
# num_lines is now one *less* that the actual line count.
fd.write('... | 0 | 2016-06-06T21:28:45Z | [
"python",
"add",
"mask",
"lines"
] |
How to join() - chapter 8 Automate the Boring Stuff | 37,666,790 | <p>From Automate The Boring Stuff With Python book:
"Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this:</p>
<p>The ADJECTIVE panda walked to the NOUN and then V... | 0 | 2016-06-06T20:58:30Z | 37,666,882 | <p>You have a basic assumption that is preventing you from completing this. Your assignment of <code>mod4</code> is based on previous assignments and their order.</p>
<p>Instead what you should be doing is initializing an <code>output</code> variable to <code>[]</code> and appending the words to it as you loop throug... | 3 | 2016-06-06T21:04:50Z | [
"python"
] |
How to join() - chapter 8 Automate the Boring Stuff | 37,666,790 | <p>From Automate The Boring Stuff With Python book:
"Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this:</p>
<p>The ADJECTIVE panda walked to the NOUN and then V... | 0 | 2016-06-06T20:58:30Z | 37,780,356 | <p>Here's the answer I made. I guess I deserved getting -2 downvotes within 4 minutes of posting the above. :)</p>
<pre><code>import re
madText = open('madText.txt', 'w')
text = 'An ADJECTIVE, a NOUN, a VERB and an ADVERB and a NOUN.'
madText.write(text)
madText.close()
content = re.split('(\W+)', text)
for i in con... | 0 | 2016-06-13T00:14:12Z | [
"python"
] |
Cannot install lxml via pip | 37,666,804 | <p>I want to install lxml via pip, but it just stops, without any error or sth. When I execute </p>
<pre><code>pip install lxml -vvv
</code></pre>
<p>i see, that it stops in the line:</p>
<pre><code>gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -Isrc... | 0 | 2016-06-06T20:59:14Z | 38,827,112 | <p>For all people finding that question with the same problem: Compiling processes are very slow on the Raspberry Pi. It just doesn't have enough power. Just don't do that, it's no fun.</p>
| 0 | 2016-08-08T10:40:43Z | [
"python",
"raspberry-pi",
"lxml"
] |
Python WinReg Path Wildcard | 37,666,821 | <p>I am trying to get some values out of the registry. The problem is, one of the subkeys is "unknown". As an example, this is the key for the networked drive of "Z".<br>
"HKEY_CURRENT_USER/Network/Z" </p>
<p>Here is the current basic code which looks for this specifically. </p>
<pre><code>try:
t = OpenKey(HKEY... | 0 | 2016-06-06T21:00:20Z | 37,666,982 | <p>UNTESTED:</p>
<pre><code>key = OpenKey(HKEY_CURRENT_USER, 'Network', 0, KEY_ALL_ACCESS) # Open the root Network key.
ndrives = QueryInfoKey(key)[0] # Get the number of subkeys inside.
for i in range(ndrives): # For each subkey index...
drive = EnumKey(key, i) # Get the subkey name.
t = OpenKey(HKEY_CURRENR_... | 1 | 2016-06-06T21:13:59Z | [
"python"
] |
Web scraping multiple pages | 37,666,876 | <p>I am scraping a web page with multiple pages. I would very much appreciate your help for my following problem:</p>
<p>I have built a loop around the URL of the web page. However, when looking for the tags in the HTML code only information from page one appears. It seems like the loop is not really flowing through. ... | 0 | 2016-06-06T21:04:22Z | 37,666,925 | <p>Try changing the first two lines in your code to this:</p>
<pre><code>for pagenumber in range(1,50):
url = "http://suchen.mobile.de/fahrzeuge/auto/search.html?zipcodeRadius=100&scopeId=C&ambitCountry=DE&makeModelVariant1.makeId=3500&makeModelVariant1.modelId=115%2C98%2C80%2C99%2C102%2C81%2C100%2... | 0 | 2016-06-06T21:07:55Z | [
"python"
] |
Web scraping multiple pages | 37,666,876 | <p>I am scraping a web page with multiple pages. I would very much appreciate your help for my following problem:</p>
<p>I have built a loop around the URL of the web page. However, when looking for the tags in the HTML code only information from page one appears. It seems like the loop is not really flowing through. ... | 0 | 2016-06-06T21:04:22Z | 37,666,932 | <p>In your forloop you are doing:</p>
<pre><code>url = "* + str(pageNumber)"
</code></pre>
<p>This is literally what the url will be, and isn't concatenating as you think it is.</p>
<pre><code>>>> "a url + str(pageNumber)"
"a url + str(pageNumber)"
</code></pre>
<p>You want:</p>
<pre><code>url = "*" + str... | 1 | 2016-06-06T21:08:15Z | [
"python"
] |
Keras/Tensorflow predict: error in array shape | 37,666,887 | <p>I'm following the <a href="https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py" rel="nofollow">Keras CIFAR10 tutorial here</a>.
The only changes I made were:</p>
<p>[a] added to the end of tutorial file</p>
<pre><code>model.save_weights('./weights.h5', overwrite=True)
</code></pre>
<p>[b] change... | 1 | 2016-06-06T21:05:14Z | 37,667,453 | <p>You have to reshape the input image to have a shape of <code>[?, 3, 32, 32]</code> where <code>?</code> is the batch size. In your case, since you have 1 image the batch size is 1, so you can do:</p>
<pre class="lang-py prettyprint-override"><code>img = np.array(img)
img = img.reshape((1, 3, 32, 32))
</code></pre>
| 0 | 2016-06-06T21:54:36Z | [
"python",
"python-3.x",
"tensorflow",
"reshape",
"keras"
] |
Python Selenium - dynamically generated data not added to DOM | 37,666,923 | <p>I am using python selenium</p>
<p>I am running this simple code</p>
<pre><code>driver = webdriver.PhantomJS()
#Also use driver = webdriver.Chrome()
driver.get("my_url")
driver.find_element_by_xpath("//*[@id='lb_LoadMore_button_text_2']").click()
print [x.text for x in driver.find_elements_by_xpath("//font[@class='... | 2 | 2016-06-06T21:07:38Z | 37,667,195 | <p>You might just need a delay after a click, but let's not just add a <code>time.sleep()</code> call, but <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow">explicitly wait</a> for the product titles to be present via <code>presence_of_all_elements_located()</code>:</p>
<pre><cod... | 2 | 2016-06-06T21:30:35Z | [
"python",
"selenium",
"selenium-webdriver",
"web-scraping"
] |
Is IPC slowing this down? | 37,666,940 | <p>I understand that there is overhead when using the Multiprocessing module, but this seems to be a high amount and the level of IPC should be fairly low from what I can gather.</p>
<p>Say I generate a large-ish list of random numbers between 1-1000 and want to obtain a list of only the prime numbers. This code is on... | 1 | 2016-06-06T21:09:18Z | 37,667,272 | <p>Hmm. How do you measure time? On my computer, the parallel version is much faster than the serial one. </p>
<p>I'm mesuring using <code>time.time()</code> that way: if we assume <code>tt</code> is an alias for <code>time.time()</code>. </p>
<pre><code>serial()
t2 = int(round(tt() * 1000))
print(t2 - t1)
parallel(... | 0 | 2016-06-06T21:37:32Z | [
"python",
"performance",
"multiprocessing"
] |
Change List in Embedded For Loop in Django Template | 37,666,950 | <p>I have the following code in my Django template:</p>
<pre><code>{% for matrix_row in request.session.matrix_rows %}
{% for radio in form.matrix_row_one_column_value %}
<li>{{ radio }}</li>
{% endfor %}
{% endfor %}
</code></pre>
<p>How can I change the list for the inner for loop as the ... | 0 | 2016-06-06T21:10:12Z | 37,667,156 | <p>Why don't you do the work in the view instead of trying to come up with something complicated in the template?</p>
<p>For example, in your Python:</p>
<pre><code>names = ['apple', 'orange', 'carrot']
colors = [ ['red', 'green'], ['orange', 'red'], ['orange', 'yellow'] ]
fruits = zip(names, colors)
</code></pre>
<... | 0 | 2016-06-06T21:28:08Z | [
"python",
"django",
"templates"
] |
Change List in Embedded For Loop in Django Template | 37,666,950 | <p>I have the following code in my Django template:</p>
<pre><code>{% for matrix_row in request.session.matrix_rows %}
{% for radio in form.matrix_row_one_column_value %}
<li>{{ radio }}</li>
{% endfor %}
{% endfor %}
</code></pre>
<p>How can I change the list for the inner for loop as the ... | 0 | 2016-06-06T21:10:12Z | 37,667,883 | <p>If I understand you correctly, what you want to do is something like <code>form[matrix_row]</code></p>
<pre><code>{% for matrix_row in request.session.matrix_rows %}
{% for radio in form[matrix_row] %}
<li>{{ radio }}</li>
...
</code></pre>
<p>That isn't possible in Django templates, so ... | 0 | 2016-06-06T22:36:34Z | [
"python",
"django",
"templates"
] |
Python os.getcwd() always returns cygwin formatted path | 37,666,993 | <p>I've been placed in charge of a build server at work, and I can't for the life of me figure out why os.getcwd() always returns a cygdrive directory. Any clue how to get it back to returning a non-cygdrive path all the time?</p>
| 0 | 2016-06-06T21:14:54Z | 37,667,323 | <p>I've discovered the issue. For some reason there were 3 python installations. The default was supposed to be set to 2.7.2, but for some reason kept running 2.6.5
Python 2.7.2 worked fine when called manually, so I uninstalled 2.6.5.</p>
<p>It also seems, upon further research, that this could also have been solve... | 0 | 2016-06-06T21:42:04Z | [
"python",
"cygwin"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.