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 |
|---|---|---|---|---|---|---|---|---|---|
Pygal Maps World Not Working | 37,679,679 | <p>I am trying to create a simple program so as to display the map of central America with their population using Pygal_maps_world.Here's the code for the same</p>
<pre><code>import pygal_maps_world as pa
wm=pa.World()
wm.title="Map of Central America"
wm.add('North America',{'cd': 84949494949,'mx': 494794164,'us': ... | 0 | 2016-06-07T12:40:47Z | 37,679,825 | <p>In the recent versions of pygal, you start with the first four lines of this code:</p>
<pre><code>from pygal.maps.world import World
wm = World()
wm.force_uri_protocol = 'http'
wm.title="Map of Central America"
wm.add('North America',{'ca': 84949494949,'mx': 494794164,'us': 99794616})
wm.render_to_file('map.svg'... | 0 | 2016-06-07T12:47:08Z | [
"python",
"python-3.x",
"data-visualization",
"pygal"
] |
In Tensorflow, how to assign values in Tensor according to the indices? | 37,679,697 | <p>I want to assign values in a tensor according to the indices.</p>
<p>For example,
According to the pooling values and the corresponding indices output of <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#max_pool_with_argmax" rel="nofollow">tf.nn.max_pool_with_argmax</a>, I want to put these... | 4 | 2016-06-07T12:41:41Z | 37,709,817 | <p>There's a pending PR that should fix this:</p>
<p><a href="https://github.com/tensorflow/tensorflow/issues/1793" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/1793</a></p>
| 0 | 2016-06-08T18:07:16Z | [
"python",
"tensorflow",
"deep-learning"
] |
In Tensorflow, how to assign values in Tensor according to the indices? | 37,679,697 | <p>I want to assign values in a tensor according to the indices.</p>
<p>For example,
According to the pooling values and the corresponding indices output of <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#max_pool_with_argmax" rel="nofollow">tf.nn.max_pool_with_argmax</a>, I want to put these... | 4 | 2016-06-07T12:41:41Z | 37,735,306 | <p>the same question is listed in <a href="https://github.com/tensorflow/tensorflow/issues/2075" rel="nofollow">tf.unravel_index (Was: tf.argmin across all dimensions) #2075</a></p>
| 0 | 2016-06-09T20:11:41Z | [
"python",
"tensorflow",
"deep-learning"
] |
Django: How to filter patients from one department? | 37,679,702 | <p>I'm using django v1.8.</p>
<p>I extended the existing User model.</p>
<p><code>models.py</code></p>
<pre><code>class Institution(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)
class Demographic(models.Model):
patient_id = mode... | 1 | 2016-06-07T12:41:58Z | 37,679,974 | <p>I assume <code>author</code> is a kind of caretaker attached to the patient. Then you can do a <code>filter</code> on the user's department:</p>
<pre><code>department = Institution.objects.get(user=request.user).department
demographic = Demographic.objects.filter(patient_id=id).filter(author__institution__departmen... | 1 | 2016-06-07T12:53:28Z | [
"python",
"django",
"django-models",
"django-views"
] |
Django: How to filter patients from one department? | 37,679,702 | <p>I'm using django v1.8.</p>
<p>I extended the existing User model.</p>
<p><code>models.py</code></p>
<pre><code>class Institution(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)
class Demographic(models.Model):
patient_id = mode... | 1 | 2016-06-07T12:41:58Z | 37,680,399 | <blockquote>
<p>A user belongs to a department when he inserts a patient as author then this patient belongs to that department.</p>
</blockquote>
<p>So let's get the <code>department</code> of a given <code>user</code> first:</p>
<pre><code>user = request.user # the doctor, the nurse etc
department = Institution.o... | 1 | 2016-06-07T13:11:34Z | [
"python",
"django",
"django-models",
"django-views"
] |
selecting row with multi index | 37,679,720 | <p>I have following DB, how i can select a row by retailer_name, visit_number, visit_date ?</p>
<pre><code>category_name Blades & Razors & Foam Diaper
retailer_name store_number visit_date
ABest 1177 ... | -1 | 2016-06-07T12:42:39Z | 37,679,907 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> with <code>slicers</code> - <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="nofollow">docs</a>:</p>
<pre><code>import pandas as pd
... | 2 | 2016-06-07T12:50:33Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
Pandas keep column value if True else False | 37,679,935 | <p>Let's say I have a DataFrame like this:</p>
<pre><code>df = pd.DataFrame({'name':['John Doe', 'Jack Bauer???', 'Chris Smith'],
'flag':['True', 'False', 'True]})[['name', 'flag']]
</code></pre>
<p>As you can see the first and third names are formatted correctly, but the second name has bad text. I want a ne... | 1 | 2016-06-07T12:51:53Z | 37,680,009 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow"><code>mask</code></a>:</p>
<pre><code>df = pd.DataFrame({'name':['John Doe', 'Jack Bauer???', 'Chris Smith'],
'flag':['True', 'False', 'True']})[['name', 'flag']]
print (df)
n... | 1 | 2016-06-07T12:54:53Z | [
"python",
"pandas",
"dataframe"
] |
Boxlayouts in Scrollview | 37,680,070 | <p>I would like to ask your help.</p>
<p>The scrollable structure under the <a href="https://15530009509605697547.googlegroups.com/attach/2b8567ec8ce16/kv.PNG?part=0.1&view=1&vt=ANaJVrHVbK2KjdxSqxXbLZp6pNVtK1O2XkF_Qnn6HYWVDfLDs7Yj_xiNkKjlmrPzOi9_0pKdOCI-0eMzXwldap8iPHM--exI1P3crP3thNcuRGQmMTjxc-s" rel="nofollo... | 0 | 2016-06-07T12:57:24Z | 37,720,218 | <p>If you want to set <code>height</code> or <code>width</code> or anything else with sizing you need to do something first in a widget you want to set it for:</p>
<pre><code>size_hint: None, None
</code></pre>
<p>This will disable setting those properties according to parent's size and some other stuff i.e. number o... | 0 | 2016-06-09T08:07:06Z | [
"python",
"kivy",
"kivy-language"
] |
SalesforceIQ: How to get all contact objects? | 37,680,160 | <p>I'm using SalesforceIQ and am trying to get all contact objects. The API docs indicate how to do this if I have their IDs (just supply an array of IDs when using Contact().fetchByIDs(...)). </p>
<p>They don't indicate how to do it if I don't have IDs.</p>
<p>Any idea how to do this?</p>
<p>Thanks!</p>
| 0 | 2016-06-07T13:01:16Z | 37,720,068 | <p>If you look carefully at the documentation, you see that IDs array is an optional parameter - <a href="https://api.salesforceiq.com/#/python#documentation_contacts_get-all-contacts" rel="nofollow">Get All Contacts</a>. Also don't forget, that Salesforce returns contacts in batches (see <em>limit</em> parameter) and ... | 1 | 2016-06-09T07:59:40Z | [
"python",
"salesforce"
] |
Outer join in python Pandas | 37,680,196 | <p>I have two data sets as following </p>
<pre><code>A B
IDs IDs
1 1
2 2
3 5
4 7
</code></pre>
<p>How in Pandas, Numpy we can apply a join which can give me all the data from B, which is not present in A
Something like Following </p>
<pre><code>B
Ids
5
7
</code></pre>
<p>I k... | 1 | 2016-06-07T13:02:48Z | 37,680,351 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with parameter <code>indicator</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>. Las... | 2 | 2016-06-07T13:08:55Z | [
"python",
"numpy",
"pandas",
"join",
"merge"
] |
Outer join in python Pandas | 37,680,196 | <p>I have two data sets as following </p>
<pre><code>A B
IDs IDs
1 1
2 2
3 5
4 7
</code></pre>
<p>How in Pandas, Numpy we can apply a join which can give me all the data from B, which is not present in A
Something like Following </p>
<pre><code>B
Ids
5
7
</code></pre>
<p>I k... | 1 | 2016-06-07T13:02:48Z | 37,680,495 | <p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.setdiff1d.html" rel="nofollow"><code>NumPy's setdiff1d</code></a>, like so -</p>
<pre><code>np.setdiff1d(B['IDs'],A['IDs'])
</code></pre>
<p>Also, <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.in1d.htm... | 3 | 2016-06-07T13:15:29Z | [
"python",
"numpy",
"pandas",
"join",
"merge"
] |
Outer join in python Pandas | 37,680,196 | <p>I have two data sets as following </p>
<pre><code>A B
IDs IDs
1 1
2 2
3 5
4 7
</code></pre>
<p>How in Pandas, Numpy we can apply a join which can give me all the data from B, which is not present in A
Something like Following </p>
<pre><code>B
Ids
5
7
</code></pre>
<p>I k... | 1 | 2016-06-07T13:02:48Z | 37,680,789 | <p>You could convert the data series to sets and take the difference:</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'A' : [1,2,3,4], 'B' : [1,2,5,7]})
A=set(df['A'])
B=set(df['B'])
C=pd.DataFrame({'C' : list(B-A)}) # Take difference and convert back to DataFrame
</code></pre>
<p>The variable "C" then yiel... | 1 | 2016-06-07T13:28:39Z | [
"python",
"numpy",
"pandas",
"join",
"merge"
] |
Outer join in python Pandas | 37,680,196 | <p>I have two data sets as following </p>
<pre><code>A B
IDs IDs
1 1
2 2
3 5
4 7
</code></pre>
<p>How in Pandas, Numpy we can apply a join which can give me all the data from B, which is not present in A
Something like Following </p>
<pre><code>B
Ids
5
7
</code></pre>
<p>I k... | 1 | 2016-06-07T13:02:48Z | 37,682,009 | <p>You can simply use pandas' <code>.isin()</code> method:</p>
<pre><code>df = pd.DataFrame({'A' : [1,2,3,4], 'B' : [1,2,5,7]})
df[~df['B'].isin(df['A'])]
</code></pre>
<p>If these are separate DataFrames:</p>
<pre><code>a = pd.DataFrame({'IDs' : [1,2,3,4]})
b = pd.DataFrame({'IDs' : [1,2,5,7]})
b[~b['IDs'].isin(a['... | 1 | 2016-06-07T14:23:28Z | [
"python",
"numpy",
"pandas",
"join",
"merge"
] |
matplotlib draw only the image with desired resolution and dpi | 37,680,385 | <p>I've read all of the questions of stackoverflow about this thematic without success.
The code above it's the closest thing that I can get to a image without axes and borders.
I'm not able to control the image resolution, because the dpi when I open the image in gimp it's different from the one that I've chosen .
I'd... | 2 | 2016-06-07T13:10:21Z | 37,680,737 | <p>After your edit:</p>
<pre><code>from stl import mesh
from matplotlib import collections
from matplotlib import pyplot
figure, axes = pyplot.subplots(frameon=False)
pixel_width = 7158 # ADDED
pixel_height = 16392 # ADDED
req_dpi = 72 # ADDED
figure.set_size_inches(pixel_width / float(req_dpi), # MODIFIED
... | 2 | 2016-06-07T13:26:05Z | [
"python",
"matplotlib",
"collections"
] |
Pointer to c_int16 array buffer in Ctypes | 37,680,467 | <p>I'm writing a wrapper for a C dll in Python Ctypes. In the C library I have a function of the kind</p>
<pre><code>int32 Transfer ( ..., PIN_PARAMS_TRANSFERDATA pInData, ... )
</code></pre>
<p>where <code>PIN_PARAMS_TRANSFERDATA</code> is a pointer to this structure:</p>
<pre><code>typedef struct
{
...
... | 0 | 2016-06-07T13:14:14Z | 37,689,473 | <p><code>ctypes.c_void_p</code> is represented as an integer. You could pass it the address of the array:</p>
<pre><code>>>> from ctypes import *
>>> class IN_PARAMS_TRANSFERDATA(Structure):
... _fields_ = [('pDataBuffer', c_void_p)]
...
>>> ArrayType = c_int16 * 2000
>>> in_da... | 1 | 2016-06-07T21:13:39Z | [
"python",
"c",
"pointers",
"dll",
"ctypes"
] |
Pointer to c_int16 array buffer in Ctypes | 37,680,467 | <p>I'm writing a wrapper for a C dll in Python Ctypes. In the C library I have a function of the kind</p>
<pre><code>int32 Transfer ( ..., PIN_PARAMS_TRANSFERDATA pInData, ... )
</code></pre>
<p>where <code>PIN_PARAMS_TRANSFERDATA</code> is a pointer to this structure:</p>
<pre><code>typedef struct
{
...
... | 0 | 2016-06-07T13:14:14Z | 37,695,680 | <p>Another possibility is to use VirtualAlloc, like in the original C code.</p>
<pre><code>p_data_buffer = ctypes.windll.kernel32.VirtualAlloc(c_int(0), c_int(sizeof(c_int16)*2000), c_int(0x00001000), c_int(0x04))
in_data.pDataBuffer = p_data_buffer
</code></pre>
<p>And for getting the data back:</p>
<pre><code>targ... | 0 | 2016-06-08T07:17:14Z | [
"python",
"c",
"pointers",
"dll",
"ctypes"
] |
how to count the number a button is pressed and print the total number pressed on screen | 37,680,470 | <pre><code>from tkinter import *
app = Tk()
app.title("quiz")
app.geometry('300x100+200+100')
b1 = Button(app, text = "correct!", width = 10,
command = play_correct)
b1.pack(side ='left', padx = 10, pady = 10)
b2 = Button(app, text = "wrong!", width = 10,
command = play_wrong)
b2.pack(side ='rig... | 0 | 2016-06-07T13:14:19Z | 37,681,393 | <p>You need to define a callback and bind it to your button</p>
<pre><code>b1 = Button(app, text = "correct!", width = 10,
command = play_correct)
b1.pack(side ='left', padx = 10, pady = 10)
b2 = Button(app, text = "wrong!", width = 10,
command = play_wrong)
b2.pack(side ='right', padx = 10, pa... | 1 | 2016-06-07T13:54:00Z | [
"python",
"button",
"tkinter"
] |
Getting elements from a Pandas DataFrame based on elements from another | 37,680,534 | <p>If I have two pandas DataFrames: </p>
<p><code>y_given_x=</code></p>
<pre><code> y|x probability
0 3 0.11649033348126
1 4 0.02749279374044
2 5 0.02741036003810
3 6 0.34035636232767
4 7 0.16491358255074
</code></pre>
<p>and</p>
<p><code>y=</code></p>
<pre><code> y_value pr... | 1 | 2016-06-07T13:17:18Z | 37,680,613 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>:</p>
<pre><code>print (pd.merge(y,
y_given_x,
left_on='y_value',
right_on='y|x',
suffixes=('','_'))[['y_value','... | 1 | 2016-06-07T13:20:22Z | [
"python",
"pandas",
"dataframe",
"merge",
"match"
] |
Regex in regex python, concatenate string and regex. | 37,680,609 | <p>Is it possible to refer to another regular expression inside a regular expression? When I try the following code: </p>
<pre><code>element = re.compile (r"H|He|Li|Be|B|C|N|O|F|Ne|Na|Mg|Al|Si|P|S|Cl|Ar|K|Ca|Sc|Ti|V|Cr|Mn|Fe
|Co|Ni|Cu|Zn|Ga|Ge|As|Se|Br|Kr|Rb|Sr|Y|Zr|Nb|Mo|Tc|Ru|Rh|Pd|Ag|Cd|In|Sn|Sb|Te|I|Xe|Cs|Ba|La
|C... | 0 | 2016-06-07T13:20:04Z | 37,680,663 | <p><code>element</code> is an already <em>compiled</em> regular expression. Why don't concatenate and then compile:</p>
<pre><code>element = r"H|He|Li|Be|B|C|N|O|F|Ne|Na|Mg|Al|Si|P|S|Cl|Ar|K|Ca|Sc|Ti|V|Cr|Mn|Fe
|Co|Ni|Cu|Zn|Ga|Ge|As|Se|Br|Kr|Rb|Sr|Y|Zr|Nb|Mo|Tc|Ru|Rh|Pd|Ag|Cd|In|Sn|Sb|Te|I|Xe|Cs|Ba|La
|Ce|Pr|Nd|Pm|Sm|... | 1 | 2016-06-07T13:22:37Z | [
"python",
"regex"
] |
Command help (via -h) where `argparse` is range checking input port number | 37,680,645 | <p>I'm using <code>argparse</code> to parse the inputs to my python3 program. I was recently asked to range check some of the numeric inputs, a seemingly good idea. Argparse has a facility to do just that. </p>
<p>The numeric inputs are port numbers, in the usual range 0-65535, so I altered my parse command line to ... | 2 | 2016-06-07T13:21:51Z | 37,681,033 | <p>Just use <code>int</code> as <a href="https://docs.python.org/3/library/argparse.html#type" rel="nofollow">type</a> in <code>add_argument</code>, and manually verify it's in the permitted range. Or, use a type of your own, which has a constructor that does the checking for you, and a <code>__int__</code> method for ... | 2 | 2016-06-07T13:38:14Z | [
"python",
"python-3.x",
"port",
"argparse"
] |
Command help (via -h) where `argparse` is range checking input port number | 37,680,645 | <p>I'm using <code>argparse</code> to parse the inputs to my python3 program. I was recently asked to range check some of the numeric inputs, a seemingly good idea. Argparse has a facility to do just that. </p>
<p>The numeric inputs are port numbers, in the usual range 0-65535, so I altered my parse command line to ... | 2 | 2016-06-07T13:21:51Z | 37,681,330 | <p>Supply an explicit <code>metavar</code> argument instead of letting <code>argparse</code> produce one for you.</p>
<pre><code>cmd_parser.add_argument('-p',
help='Port number to connect to',
dest='cmd_port',
default=1234,
... | 2 | 2016-06-07T13:50:47Z | [
"python",
"python-3.x",
"port",
"argparse"
] |
Command help (via -h) where `argparse` is range checking input port number | 37,680,645 | <p>I'm using <code>argparse</code> to parse the inputs to my python3 program. I was recently asked to range check some of the numeric inputs, a seemingly good idea. Argparse has a facility to do just that. </p>
<p>The numeric inputs are port numbers, in the usual range 0-65535, so I altered my parse command line to ... | 2 | 2016-06-07T13:21:51Z | 37,681,638 | <p>Monkey patch the <code>print_help</code> to get the desired output</p>
<pre><code>def my_help(): print "0-65535 range"
cmd_parser = argparse.ArgumentParser()
cmd_parser.add_argument('-p', help='Port number to connect to', dest='cmd_port', default=1234, type=int, choices=range(0,65536))
cmd_parser.print_help = my_... | 1 | 2016-06-07T14:05:13Z | [
"python",
"python-3.x",
"port",
"argparse"
] |
Command help (via -h) where `argparse` is range checking input port number | 37,680,645 | <p>I'm using <code>argparse</code> to parse the inputs to my python3 program. I was recently asked to range check some of the numeric inputs, a seemingly good idea. Argparse has a facility to do just that. </p>
<p>The numeric inputs are port numbers, in the usual range 0-65535, so I altered my parse command line to ... | 2 | 2016-06-07T13:21:51Z | 37,682,808 | <p>Use custom action...</p>
<pre><code>import argparse
class PortAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if not 0 < values < 2**16:
raise argparse.ArgumentError(self, "port numbers must be between 0 and 2**16")
setattr(namespace... | 2 | 2016-06-07T14:57:18Z | [
"python",
"python-3.x",
"port",
"argparse"
] |
Command help (via -h) where `argparse` is range checking input port number | 37,680,645 | <p>I'm using <code>argparse</code> to parse the inputs to my python3 program. I was recently asked to range check some of the numeric inputs, a seemingly good idea. Argparse has a facility to do just that. </p>
<p>The numeric inputs are port numbers, in the usual range 0-65535, so I altered my parse command line to ... | 2 | 2016-06-07T13:21:51Z | 37,684,240 | <p>There is a Python bug/issue regarding the formatting of large <code>choices</code> lists. Currently <code>choices</code> in the help is formatted with</p>
<pre><code> def _metavar_formatter: ...
choice_strs = [str(choice) for choice in action.choices]
result = '{%s}' % ','.join(choice_strs)
</co... | 0 | 2016-06-07T16:06:17Z | [
"python",
"python-3.x",
"port",
"argparse"
] |
Python os.path.join - INFO - 'list' object has no attribute 'endswith error | 37,680,666 | <p>I am trying to create a function that would listdir into a list, then iterate over the list and remove the last 3 elements. I have used this code before but I am getting an odd error, please see the log below. I have research the error that I am catching with AttributeError and my results have been null. Can anyo... | 0 | 2016-06-07T13:22:44Z | 37,680,723 | <pre><code>print os.path.join(dir_list, dirs)
</code></pre>
<p><code>dir_list</code> is a list, but <code>os.path.join</code>'s arguments need to be individual strings.</p>
<p>It's not clear to me what you're trying to do here. If you just want to display <code>dirs</code>, you don't need <code>join</code> at all. Ju... | 1 | 2016-06-07T13:25:35Z | [
"python"
] |
Does a Try/Except block create a stack of its own? | 37,680,730 | <pre><code>def f(n):
if n>0:
print(1/n)
else:
raise Exception
try:
f(0)
except Exception:
print("Error!")
</code></pre>
<p>When Exception is raised inside f(n), does the interpreter return to the try/except block (which implies the try/except has its own block), or is that error bein... | 0 | 2016-06-07T13:25:46Z | 37,681,034 | <p>Actualy it raises <strong>from the f(n) function</strong> up until it finds a <strong>try/catch</strong> handler <strong>or</strong> the end of the <strong>program stack</strong>. In this last case, the program will stop and raise the error ti the user (through the console).</p>
<p>this will raise the exception up ... | 1 | 2016-06-07T13:38:16Z | [
"python",
"python-3.x"
] |
Does a Try/Except block create a stack of its own? | 37,680,730 | <pre><code>def f(n):
if n>0:
print(1/n)
else:
raise Exception
try:
f(0)
except Exception:
print("Error!")
</code></pre>
<p>When Exception is raised inside f(n), does the interpreter return to the try/except block (which implies the try/except has its own block), or is that error bein... | 0 | 2016-06-07T13:25:46Z | 37,681,181 | <p>In your case, I think this is more pythonic:</p>
<pre><code>def f(n):
try:
print(1/n)
except ZeroDivisionError:
print ("can't divide by zero")
</code></pre>
<p>You never want to raise a blanket exception because you loose the chance to learn what went wrong</p>
| 2 | 2016-06-07T13:44:43Z | [
"python",
"python-3.x"
] |
Python 2.7 Linux \n to Windows \r\n | 37,680,738 | <blockquote>
<p>SOLUTION:
Change ConfigParser.py
Everything with \n should be \r\n, this way linux and windows can read the file with line return.
This fixed it for us.</p>
</blockquote>
<p>I am writing an program in Linux and it communicates with an Windows 10 PC. I get an file from the Windows PC and with P... | 0 | 2016-06-07T13:26:06Z | 37,680,952 | <p>In your call to read the file-like object, you should be passing in the <code>U</code> flag for cross-compatibility. e.g. </p>
<pre><code>import ConfigParser
conf = ConfigParser.ConfigParser()
conf.readfp(open('/tmp/settings.cfg', 'U'))
...
</code></pre>
<p>Per the <a href="https://docs.python.org/2/library/func... | 2 | 2016-06-07T13:35:16Z | [
"python",
"configparser"
] |
Python 2.7 Linux \n to Windows \r\n | 37,680,738 | <blockquote>
<p>SOLUTION:
Change ConfigParser.py
Everything with \n should be \r\n, this way linux and windows can read the file with line return.
This fixed it for us.</p>
</blockquote>
<p>I am writing an program in Linux and it communicates with an Windows 10 PC. I get an file from the Windows PC and with P... | 0 | 2016-06-07T13:26:06Z | 37,683,077 | <p>Maybe not exactly the best way but I works now with the following method: </p>
<p>In /usr/lib/python2.7/ConfigParser.py do the following:</p>
<pre><code>"""Write an .ini-format representation of the configuration state."""
if self._defaults:
fp.write("[%s]\r\n" % DEFAULTSECT)
for (k... | 0 | 2016-06-07T15:08:36Z | [
"python",
"configparser"
] |
How do I use "i and ch in enumerate(Answer)" to see how many of my guess characters are in the right position? | 37,680,932 | <p>Specifically: We are to print out how many of the guess character are exactly right (correct character in the
correct position) and
and how many of the guess characters are correct values but are not in the correct
position.</p>
<p>Here's my code:</p>
<pre><code> key = input("Input your secret key (RYBGWO):")
pri... | -3 | 2016-06-07T13:34:27Z | 37,681,460 | <p>The line </p>
<pre><code>if key[i] == Answer[i] and key[ch] == Answer[ch]:
</code></pre>
<p>does not make all that much sense. Using <code>enumerate</code>, <code>i</code> is the position, that's fine, but <code>ch</code> is the character at that position. <code>key[ch]</code> does not make sense. Did you mean <co... | 0 | 2016-06-07T13:56:46Z | [
"python"
] |
How do I use "i and ch in enumerate(Answer)" to see how many of my guess characters are in the right position? | 37,680,932 | <p>Specifically: We are to print out how many of the guess character are exactly right (correct character in the
correct position) and
and how many of the guess characters are correct values but are not in the correct
position.</p>
<p>Here's my code:</p>
<pre><code> key = input("Input your secret key (RYBGWO):")
pri... | -3 | 2016-06-07T13:34:27Z | 37,682,073 | <p>Down votes are coming because your criteria is not well defined, but I think that you are asking for a basic master-mind type problem. It is easy enough if you define your problem such that the hidden values do not repeat. If your hidden value, as I define it below can have repeating values than the problem gets mor... | 0 | 2016-06-07T14:26:41Z | [
"python"
] |
How can I retrieve data from a QTableWidget? | 37,680,981 | <p>I have a QTableWidget in editable mode in which user puts in integer input , how can I generate a list of data entered in this table so as to perform operations on it , here is my manual code for that: </p>
<pre><code>def dataframe_generation_from_table(self,table):
number_of_rows = table.rowCount()
number... | 0 | 2016-06-07T13:36:18Z | 37,705,744 | <p>I think you're overcomplicating it a little with the updates/joins. The simplest approach is to create the full-size <code>DataFrame</code> first (filled with <code>NaN</code>) and then assign the data to this:</p>
<pre><code>def dataframe_generation_from_table(self,table):
number_of_rows = table.rowCount()
... | 2 | 2016-06-08T14:42:55Z | [
"python",
"pandas",
"pyqt",
"pyqt4",
"qtablewidget"
] |
Simulation and Histogram of Random Hopping in Python | 37,680,982 | <p>I explain you my problem:</p>
<p>Imagine you have a bar, with say s positions. Each position can be counted as position 0, position 1, .. , position s-1.
Now what I want to do is simulate the following : At a certain point in time, a number of particles, say n particles, start in a state of the bar (assume a positi... | 0 | 2016-06-07T13:36:26Z | 37,681,974 | <p>I don't know if i got you right, but
do you want to see this instead of a histogram?</p>
<pre><code>xs = np.arange(len(x))
width = 1/1.5
plt.bar(xs,x,width)
</code></pre>
| 1 | 2016-06-07T14:21:39Z | [
"python",
"python-2.7",
"random",
"histogram",
"simulation"
] |
python setup.py put data files in %APPDATA% directory | 37,680,992 | <p>I would like to copy a default config file to %APPDATA%\foo directory when installing the package.</p>
<pre><code>from setuptools import setup
setup(
name = 'foo',
version = '0.1.0.dev1',
author = 'me',
packages = ['foo'],
data_files=[(r'%APPDATA%\foo', ['foo.config'])]
)
</code></pre>
<p>The ... | 0 | 2016-06-07T13:36:40Z | 37,691,920 | <p>Obvious in hindsight. For some reason I didn't know you could have regular python code in setup.py. Just import os and replace data_files above with:</p>
<pre><code>data_files=[(os.path.join(os.environ['APPDATA'], 'foo'), ['foo.config'])]
</code></pre>
| 0 | 2016-06-08T01:31:22Z | [
"python",
"setup.py"
] |
Syntax error on python 2 which I can't understand why | 37,681,002 | <p>Hi I was trying to shut down raspberry pi via arduino and made a python daemon that shutdowns the raspberry pi. </p>
<p>When I first write code and run it, it perfectly works but when I save it and run the code one more time, it doesn't run because of syntax error. </p>
<p>Here is my python code.
<img src="http:/... | -5 | 2016-06-07T13:37:10Z | 37,681,100 | <p>Remove the <code>>>></code> from your script </p>
| 5 | 2016-06-07T13:41:15Z | [
"python",
"raspberry-pi"
] |
How can I sort excel sheets/tabs in workbook using openpyxl | 37,681,005 | <p>I need to sort the tabs/sheets in a workbook alpha- numerically. I am using <a href="https://openpyxl.readthedocs.io/en/default/" rel="nofollow">openpyxl</a> to manipulate the worksheet.</p>
| 1 | 2016-06-07T13:37:13Z | 37,681,481 | <p>You can try to sort the <code>workbook._sheets</code> list.</p>
<pre><code>workbook._sheets = sorted(workbook._sheets)
</code></pre>
<p>This may result in the active worksheet (referred to by an index) to change silently so the sorting operation should be followed by something like <code>workbook.active = 0</code>... | 0 | 2016-06-07T13:57:53Z | [
"python",
"openpyxl"
] |
Why does numpy say this matrix is singular *sometimes*? | 37,681,020 | <p>Part of my code inverts a matrix (really an ndarray) using numpy.linalg.inv. However, this frequently errors out as follows:</p>
<pre><code>numpy.linalg.linalg.LinAlgError: Singular matrix
</code></pre>
<p>That would be fine if the matrix was actually singular. But that doesn't seem to be the case.</p>
<p>For exa... | 2 | 2016-06-07T13:37:47Z | 37,681,241 | <p>I just compute the determinant:</p>
<pre><code>In [130]: m = np.array([[ 0.76400334, 0.22660491],[ 0.22660491,0.06721147]])
In [131]: np.linalg.det(m)
Out[131]: 2.3302017068132921e-09
# which is in fact for a 2D matrix 0.76400334*0.06721147 - 0.22660491*0.22660491
</code></pre>
<p>Which is already quit close to ... | 1 | 2016-06-07T13:47:07Z | [
"python",
"numpy",
"matrix"
] |
Why does numpy say this matrix is singular *sometimes*? | 37,681,020 | <p>Part of my code inverts a matrix (really an ndarray) using numpy.linalg.inv. However, this frequently errors out as follows:</p>
<pre><code>numpy.linalg.linalg.LinAlgError: Singular matrix
</code></pre>
<p>That would be fine if the matrix was actually singular. But that doesn't seem to be the case.</p>
<p>For exa... | 2 | 2016-06-07T13:37:47Z | 37,690,516 | <p>It's a matter of printing precision. The IEEE 754 doubles, that you're most likely using, have about 16 decimal digits of precision and you need to write out 17 <a href="https://en.wikipedia.org/wiki/IEEE_floating_point#Character_representation" rel="nofollow">to preserve the binary value</a>.</p>
<p>Here's a small... | 1 | 2016-06-07T22:36:32Z | [
"python",
"numpy",
"matrix"
] |
Find below patterns in a text | 37,681,027 | <p>In the broader term, I need to parse SQL procedures and find what tables and columns the <code>proc</code> depends on. To do it, I am trying to search <code>regex</code>.</p>
<p>Example:</p>
<pre><code>from table db..tb
where tb.column2 = "N" AND column 1 in ("ab","cd")
</code></pre>
<p>It should return</p>
<pre... | -1 | 2016-06-07T13:38:04Z | 37,681,512 | <p>My reading of your question is you have a table -- a delimited file -- where you want to check if a particular row has "N" in column 2 and either "ab" or "cd" being found anywhere in the string in column 1. The action you wish to trigger is to print the "N" followed by the value in column 1...</p>
<p>This example ... | 0 | 2016-06-07T13:59:08Z | [
"python",
"sql",
"regex",
"grep",
"sql-parser"
] |
How does HTML pagination work without a link or script? | 37,681,030 | <p>Consider the following link:</p>
<p><a href="https://www.officeworks.com.au/shop/officeworks/c/technology/monitors-digital-signage/27--monitors" rel="nofollow">https://www.officeworks.com.au/shop/officeworks/c/technology/monitors-digital-signage/27--monitors</a></p>
<p>The "View 100 per page" link does not change ... | -1 | 2016-06-07T13:38:12Z | 37,681,276 | <p>One answer is the Ajax and Event system un Javascript.</p>
<p>You can have one HTML item like</p>
<pre><code><button id="but1">Show 100 items</button>
</code></pre>
<p>and add a <strong>"click" event</strong> on it from Javascript (example with <strong>JQuery</strong>)</p>
<pre><code>$("#but1").click... | 0 | 2016-06-07T13:48:50Z | [
"javascript",
"python",
"html"
] |
How does HTML pagination work without a link or script? | 37,681,030 | <p>Consider the following link:</p>
<p><a href="https://www.officeworks.com.au/shop/officeworks/c/technology/monitors-digital-signage/27--monitors" rel="nofollow">https://www.officeworks.com.au/shop/officeworks/c/technology/monitors-digital-signage/27--monitors</a></p>
<p>The "View 100 per page" link does not change ... | -1 | 2016-06-07T13:38:12Z | 37,681,356 | <p>The content is loaded dynamicly, an example of such feature is jQuery Ajax
<a href="http://api.jquery.com/jquery.ajax/" rel="nofollow">http://api.jquery.com/jquery.ajax/</a></p>
<p>There is no need to add a link, or onclick. You can bind event handlers to html tags / classes / IDs ...
<a href="https://api.jquery.co... | 0 | 2016-06-07T13:52:06Z | [
"javascript",
"python",
"html"
] |
Re-arrange table using Python | 37,681,119 | <p>I have some tables presenting daily discharge values of some rivers from 1893 until 2010. Unfortunately, the tables have been organized in a strange way:</p>
<ul>
<li>there is no header,</li>
<li>there is 13 columns. With the first one representing the days and the following ones the month (so column 2 = January; c... | 0 | 2016-06-07T13:42:01Z | 37,681,418 | <p>You're looking for the function <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-melt" rel="nofollow"><code>melt</code></a>. Let's rename the columns first:</p>
<pre><code>df.columns = ['day', 'Jan', 'Feb', ..., 'Dec']
</code></pre>
<p>You can then melt the dataframe:</p>
<pre><cod... | 1 | 2016-06-07T13:55:02Z | [
"python",
"table",
"pandas",
"dataframe"
] |
How to compute the height of a QTreeWidget content? | 37,681,146 | <p>I want a <code>QTreeWidget</code> that has a preferred height that shows all its contents without scrollbar. Use case for this is twofold: 1) trees in a <code>QVBoxLayout</code> taking space proportional to their content and 2) trees in a <code>QScrollArea</code> where there should be only one scrollbar for all tree... | 2 | 2016-06-07T13:43:01Z | 37,724,553 | <p>The trick seems to be to query the header for the width, the tree for individual row heights and add the frameWidth on all sides like this:</p>
<pre><code>class TreeWidget(QtGui.QTreeWidget):
def sizeHint(self):
print("TreeWidget.sizeHint()")
print(" frameWidth = {0}".format(self.frameWidth()))... | 2 | 2016-06-09T11:21:37Z | [
"python",
"qt",
"pyqt",
"qt4",
"pyside"
] |
Complex join between two pandas dataframes | 37,681,147 | <p>I have two large pandas dataframes that I need to join and then fill in missing values:</p>
<p>Dataframe #1 has columns A,B, and C,</p>
<p>and</p>
<p>Dataframe #2 has columns A,B, and C, but with all values from C missing</p>
<p>I am trying to join dataframes #1 and #2 such that where the values in columns A and... | 0 | 2016-06-07T13:43:05Z | 37,681,534 | <p>This an operation for <code>merge</code>:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'A':[1,2,3],'B':[4,5,6],'C':[np.NaN, np.NaN, np.NaN]})
df2 = pd.DataFrame({'A':[1,3],'B':[4,6],'C':[44, 55]})
In [150]: pd.merge(df1.drop(['C'], axis=1), df2, how='left', on=['A','B'])
Out[150]:
A B C
0 1 4 ... | 3 | 2016-06-07T14:00:14Z | [
"python",
"numpy",
"pandas"
] |
performance: python requests extremely slow when using a proxy/VPN | 37,681,160 | <p>I'm running a program which needs to use a VPN/proxy (the websites I query display different results based on geolocation).</p>
<p>I'm currently using TunnelBear on my machine. The request is completed, but it takes > 20 seconds (vs. less than a second without the VPN activated).</p>
<p>Here's what cProfile says:<... | 0 | 2016-06-07T13:43:55Z | 37,991,606 | <p>It greatly depends on the VPN itself. I've had lots of success with Hotspot Shield. It is free (750mb daily) and fast.</p>
| 0 | 2016-06-23T12:26:58Z | [
"python",
"performance",
"proxy",
"python-requests"
] |
Copying zipped file using python | 37,681,199 | <p>I need to copy file from my NAS to my local folder, zip it and then copy it elsewhere. This is my code:</p>
<pre><code>from shutil import copyfile
import zipfile
def make_done_file(user, filename):
copyfile(network_location+filename+'.csv', test_location+filename+'.csv')
zip_file = zipfile.ZipFile(test_loc... | 0 | 2016-06-07T13:45:27Z | 37,682,142 | <p>You probably need to <code>close</code> <code>zip_file</code> before copying it; <code>copyfile</code> is going to open the file separately, and if the data isn't flushed to disk, it's going to copy an incomplete file (especially bad, since you'll likely omit the zip file metadata needed to interpret the contents).<... | 0 | 2016-06-07T14:29:46Z | [
"python",
"python-3.x"
] |
Django not using Python 3 installation | 37,681,265 | <p>I have the following code in my Django app</p>
<pre><code>def get_filename(root):
def wrapper(instance, filename):
return (root + filename)
return wrapper
...
docfile = models.FileField(upload_to=get_filename("/some_dir"))
</code></pre>
<p>Running this with <code>python3 manage.py makemigrations... | -2 | 2016-06-07T13:48:20Z | 37,681,593 | <p>Django is using the <em>default installation</em> of Python on your system. That is likely to be 2.7</p>
<p>If you want to use a specific Python version, you could start Django using that version explicitly</p>
<pre><code>~$ python3 django-admin runserver --settings=myapp.settings
</code></pre>
<p>But what you re... | 3 | 2016-06-07T14:02:47Z | [
"python",
"django",
"python-3.4"
] |
Django not using Python 3 installation | 37,681,265 | <p>I have the following code in my Django app</p>
<pre><code>def get_filename(root):
def wrapper(instance, filename):
return (root + filename)
return wrapper
...
docfile = models.FileField(upload_to=get_filename("/some_dir"))
</code></pre>
<p>Running this with <code>python3 manage.py makemigrations... | -2 | 2016-06-07T13:48:20Z | 37,681,602 | <p>You're better off setting up a python-3.4 <code>virtualenv</code> and running your Django project from the virtual environment. </p>
<p>Find installation guide <a href="https://virtualenv.pypa.io/en/stable/installation.html" rel="nofollow">here</a> and more info <a href="http://stackoverflow.com/questions/23842713/... | 0 | 2016-06-07T14:03:14Z | [
"python",
"django",
"python-3.4"
] |
Django not using Python 3 installation | 37,681,265 | <p>I have the following code in my Django app</p>
<pre><code>def get_filename(root):
def wrapper(instance, filename):
return (root + filename)
return wrapper
...
docfile = models.FileField(upload_to=get_filename("/some_dir"))
</code></pre>
<p>Running this with <code>python3 manage.py makemigrations... | -2 | 2016-06-07T13:48:20Z | 37,682,393 | <p>modify the command you use for python3. for exemple in order to launch django server :
python3 manage.py runserver 0.0.0.0:8000
instead of
python manage.py runserver 0.0.0.0:8000</p>
| 0 | 2016-06-07T14:40:23Z | [
"python",
"django",
"python-3.4"
] |
Error binding parameter 0 - probably unsupported type. SQL/Python | 37,681,325 | <p>genre1, genre2, genre3 has data being retrieved from select fields on my web page. When I select two genres (two fields) it adds the movie perfectly fine. But when I select all three genres (all fields) it gives me an error.</p>
<p>It just doesnt work when theres (genre1,genre2,genre3)
It does work when its (genre1... | 0 | 2016-06-07T13:50:36Z | 37,682,016 | <p>Okay.. So I moved "db.commit()" so that its outside the for loop and it worked.. I do not know why so if anyone would like to explain.. please feel free to!</p>
| 0 | 2016-06-07T14:23:43Z | [
"python",
"sqlite",
"flask"
] |
remove tuples with only one item -- python | 37,681,572 | <p>I have a list of tuples and some of the tuples only have one item in it. How do I remove tuples with only one item from the list? I want to keep tuples with two items in it.</p>
<p>The tuples I have contain a string, and then an integer after it </p>
<pre><code>list = ((['text'],1),(['text'],2),((3,))
</code></pre... | 1 | 2016-06-07T14:02:12Z | 37,681,634 | <p>I may suggest:</p>
<pre><code>filtered_list = [tup for tup in list if len(tup) == 2]
</code></pre>
<p>You can also check if tuple length is higher than one or anything else...</p>
| 5 | 2016-06-07T14:05:00Z | [
"python",
"tuples"
] |
remove tuples with only one item -- python | 37,681,572 | <p>I have a list of tuples and some of the tuples only have one item in it. How do I remove tuples with only one item from the list? I want to keep tuples with two items in it.</p>
<p>The tuples I have contain a string, and then an integer after it </p>
<pre><code>list = ((['text'],1),(['text'],2),((3,))
</code></pre... | 1 | 2016-06-07T14:02:12Z | 37,681,671 | <p>You want to create a list with squared brackets instead of parentheses, otherwise you'd create a tuple.</p>
<p>Also please don't call your variables like built-in names as EdChum suggested.</p>
<p>The solution here is to filter your list:</p>
<pre><code>l=[(1,2),(3,),(4,5)]
filter(lambda x: len(x)!=1, l)
</code><... | 2 | 2016-06-07T14:06:29Z | [
"python",
"tuples"
] |
remove tuples with only one item -- python | 37,681,572 | <p>I have a list of tuples and some of the tuples only have one item in it. How do I remove tuples with only one item from the list? I want to keep tuples with two items in it.</p>
<p>The tuples I have contain a string, and then an integer after it </p>
<pre><code>list = ((['text'],1),(['text'],2),((3,))
</code></pre... | 1 | 2016-06-07T14:02:12Z | 37,681,677 | <p>What about:</p>
<pre><code>new_list = [x for x in old_list if len(x) > 1]
</code></pre>
| 3 | 2016-06-07T14:06:57Z | [
"python",
"tuples"
] |
remove tuples with only one item -- python | 37,681,572 | <p>I have a list of tuples and some of the tuples only have one item in it. How do I remove tuples with only one item from the list? I want to keep tuples with two items in it.</p>
<p>The tuples I have contain a string, and then an integer after it </p>
<pre><code>list = ((['text'],1),(['text'],2),((3,))
</code></pre... | 1 | 2016-06-07T14:02:12Z | 37,681,739 | <p>You could use something like that to rebuild a new tuple with tuple that have a length greater than 1. </p>
<pre><code>new_list = tuple(item for item in your_list if len(item) > 1)
</code></pre>
| 0 | 2016-06-07T14:10:08Z | [
"python",
"tuples"
] |
How to make report by export data into PDF file in django? | 37,681,730 | <p>I want to make report in django to export data as a PDF, excel or csv file. I'm looking forward a library support it in django. How can I do that?</p>
| -1 | 2016-06-07T14:09:45Z | 37,681,913 | <p>I believe you can start from the Django docs: <a href="https://docs.djangoproject.com/en/1.9/howto/outputting-pdf/" rel="nofollow">https://docs.djangoproject.com/en/1.9/howto/outputting-pdf/</a></p>
| 0 | 2016-06-07T14:18:47Z | [
"python",
"django"
] |
How to make report by export data into PDF file in django? | 37,681,730 | <p>I want to make report in django to export data as a PDF, excel or csv file. I'm looking forward a library support it in django. How can I do that?</p>
| -1 | 2016-06-07T14:09:45Z | 37,687,110 | <p>To export as PDF you could use this <a href="http://wkhtmltopdf.org/" rel="nofollow">wkhtmltopdf</a> and this <a href="https://github.com/incuna/django-wkhtmltopdf" rel="nofollow">django-wkhtmltopdf</a> you could create a template with the info and use wkhtmltopdf to export the template as PDF</p>
| 0 | 2016-06-07T18:50:40Z | [
"python",
"django"
] |
Connecting three classes from methods inside of them in python | 37,681,761 | <p>I am using <code>PyQt</code> to create an application with <code>matplotlib</code> and I am trying to connect a method from one class with another method from another class. </p>
<p>Class A is a <code>QMainWindow</code> that instantiate <code>class B</code>, which is a <code>matplotlib</code> figure. So, when I c... | -1 | 2016-06-07T14:11:18Z | 37,684,812 | <p><code>C</code> inherits from <code>B</code> so <code>connect_to_b</code> has access to <code>b</code>.</p>
<pre><code>def connect_to_b(self):
self.b()
</code></pre>
| 1 | 2016-06-07T16:39:42Z | [
"python",
"matplotlib",
"pyqt"
] |
Using object.relatedname_set.all vs object.relatedname.all for ForeignKey in a template | 37,681,762 | <p>I am trying to understand the difference between using <code>relatedname_set.all</code> vs <code>relatedname.all</code>. I have a template that I was unable to get to iterate through objects via a ForeignKey with <code>relatedname_set.all</code>. I just happened to change it to <code>relatedname.all</code> and it wo... | 0 | 2016-06-07T14:11:20Z | 37,682,107 | <p>From the docs for <a href="https://docs.djangoproject.com/en/1.9/topics/db/models/#be-careful-with-related-name" rel="nofollow">be careful with <code>related_name</code></a>,</p>
<blockquote>
<p>If you <strong>donât</strong> specify a related_name attribute for a field in an abstract base class, the <strong>def... | 0 | 2016-06-07T14:28:13Z | [
"python",
"django",
"foreign-keys"
] |
How to get key of a dictionary in a list or tuple? | 37,681,820 | <p>A dict like ,</p>
<pre><code>c = {1:'a', 2:'b', 3:'c'}
</code></pre>
<p>I need to get the keys in list .
I write,</p>
<pre><code>x = [c.key()]
</code></pre>
<p>but that don't work.
how i can do this ?
Can i iterate over key of a dictionary ?
If i write , <code>c.key()</code> that needs to return's the keys of <c... | 0 | 2016-06-07T14:14:03Z | 37,681,877 | <p>In python 3, <code>c.keys()</code> returns a <code>dict_keys</code> object, so to be sure you have a list, you should do:</p>
<pre><code>x = list(c.keys())
</code></pre>
<p><em>Casting</em> is necessary in python 3 because <code>dict_keys</code> objects are not <em>subscriptable</em></p>
<p>In python 2, <code>x =... | 3 | 2016-06-07T14:16:51Z | [
"python",
"python-2.7",
"python-3.x",
"dictionary"
] |
Communicate with multiple slave processes (one multiprocessing.Queue instance per slave) | 37,681,840 | <p>I have devised a way of parallelizing a certain task by distributing the work among several slave processes. So the design I've come up with is this:</p>
<ul>
<li>The master process creates one <code>multiprocessing.Queue</code> instance per slave process it starts.</li>
<li>The master task then creates the slave p... | 0 | 2016-06-07T14:15:04Z | 37,682,694 | <p>It sounds like a task queue </p>
<p><a href="https://en.wikipedia.org/wiki/Thread_pool" rel="nofollow">https://en.wikipedia.org/wiki/Thread_pool</a></p>
<p>but one-directional queues will be much easier to work with.</p>
<p>You want to issue jobs to the appropriate thread using one queue. Finished tasks can be re... | 1 | 2016-06-07T14:53:07Z | [
"python",
"python-multiprocessing"
] |
I can't get my class to work in pygame | 37,681,848 | <pre><code>import pygame, sys, time, os, copy
from pygame.locals import *
forest = pygame.image.load('C:/Python32/PygameImages/forest.png')
rstill = pygame.image.load('C:/Python32/PygameImages/rstill.bmp')
lstill = pygame.image.load('C:/Python32/PygameImages/lstill.bmp')
bstill = pygame.image.load('C:/Python32/Pyga... | 2 | 2016-06-07T14:15:23Z | 37,683,224 | <p>Your timer is being called and reset before it ever reaches 9</p>
<p>to solve this use:</p>
<pre><code>def move(self, walk1, still, walk2, sprite):
timer += clock.tick()
if timer > 9:
timer = 0
if sprite == walk1:
self.sprite = still
elif sprite == still:
... | 0 | 2016-06-07T15:15:39Z | [
"python",
"class",
"pygame"
] |
I can't get my class to work in pygame | 37,681,848 | <pre><code>import pygame, sys, time, os, copy
from pygame.locals import *
forest = pygame.image.load('C:/Python32/PygameImages/forest.png')
rstill = pygame.image.load('C:/Python32/PygameImages/rstill.bmp')
lstill = pygame.image.load('C:/Python32/PygameImages/lstill.bmp')
bstill = pygame.image.load('C:/Python32/Pyga... | 2 | 2016-06-07T14:15:23Z | 37,683,470 | <p>I've yet to isolate your issue other than the fact that your comparison vs the active sprite and a image object doesn't add up to <code>True</code>.</p>
<p>But I wanted to give you a few pointers which are way to long for a comment and needs structure and code highlighting - so here's some general tips when doing g... | 1 | 2016-06-07T15:27:16Z | [
"python",
"class",
"pygame"
] |
Using regex with python to find unique number format | 37,681,868 | <p>I have a very large text file (45000 lines) with ID #'s in the format of 4 or 5 numbers followed by 2 or 3 numbers and then a letter sometimes trailing at the end.</p>
<p>Sample example formats: </p>
<p>XXXX-XX XXXXX-XX ,XXXXX-XXw, XXXXX-XXw, XXXXX-XXww</p>
<p>((Where w is a letter and X is a number))</p>
<p>Mos... | 1 | 2016-06-07T14:16:14Z | 37,682,272 | <p>A simple set which reads your regex should match your clarified comment:</p>
<pre><code>import re
uniq = set()
with open('Sample.txt') as fin:
for line in fin:
ma = re.search(r'(\w{1,4})$', line)
if not ma:
continue
uniq.add(ma.group(1))
print(uniq)
</code></pre>
| 0 | 2016-06-07T14:35:23Z | [
"python",
"regex",
"dictionary",
"format",
"set"
] |
Element-wise seed for random Numpy arrays | 37,681,954 | <p>I'm trying to generate potentially large arrays of float (0.0-1.0), but have each element driven by a seed array, comprised of integers, which represent an id. </p>
<p>For example, I if have these two arrays:</p>
<pre><code>seedArray1 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
seedArray2 = np.array([0, 1, 2, 3, 4,... | 2 | 2016-06-07T14:20:57Z | 37,683,757 | <p>Not really, no. PRNGs are designed to output streams of many numbers from a single seed, and <code>numpy.random</code>'s API is designed around that. You can of course do the loop yourself if you need an arbitrary, repeatable mapping from integers to floats within <code>[0, 1)</code> for some reason. There might be ... | 3 | 2016-06-07T15:40:52Z | [
"python",
"arrays",
"numpy",
"random"
] |
calling serializer in django rest framework | 37,682,058 | <p>I am having some problems with serializer. I'm calling a post method which I want it to call the serializer. Also I want to have the user sent to the serializer. my post method is:</p>
<pre><code>def post(self, request, *args, **kwargs):
serializer = ResourceListSerializer(context={'request': request}, data={})... | 0 | 2016-06-07T14:25:59Z | 37,682,314 | <p>Pass <code>data</code> when instantiating your serializer, not <code>context</code>.</p>
<pre><code>def post(self, request, *args, **kwargs):
serializer = ResourceListSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(creator=request.user)
</code></pre>
<p>You only ... | 3 | 2016-06-07T14:37:13Z | [
"python",
"django",
"post",
"serializer"
] |
Is there a function to return all single letter colors in Matplotlib? | 37,682,109 | <p>I learnt of <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.colors" rel="nofollow">matplotlib.pyplot.colors</a> that the basic built-in colors can be represented as a single letter.</p>
<ul>
<li>b: blue</li>
<li>g: green</li>
<li>r: red</li>
<li>c: cyan</li>
<li>m: magenta</li>
<li>y: yellow</l... | 3 | 2016-06-07T14:28:18Z | 37,682,278 | <p>The built in colors are available via <a href="http://matplotlib.org/api/colors_api.html#matplotlib.colors.ColorConverter.colors" rel="nofollow"><code>matplotlib.colors.ColorConverter.colors</code></a></p>
<pre><code>>>> print(matplotlib.colors.ColorConverter.colors)
{u'b': (0.0, 0.0, 1.0),
u'c': (0.0, 0.... | 4 | 2016-06-07T14:35:39Z | [
"python",
"matplotlib"
] |
Count how many times a substring from list appears in a string | 37,682,127 | <p>I have a string:</p>
<pre><code>seq = '01234567890123456789'
</code></pre>
<p>that I want to first break up into intervals of 4. I found a previous answer </p>
<pre><code>n = 4
[seq[i:i+n] for i in range(0,len(seq,n)]
</code></pre>
<p>which gives me</p>
<pre><code>['0123', '4567', '8901', '2345', '6789']
</... | 0 | 2016-06-07T14:29:11Z | 37,682,271 | <pre><code>generated = ['0123', '4567', '8901', '2345', '6789']
mylist = ['0123', '1111' '2345']
result = [generated.count(element) for element in mylist ]
</code></pre>
<p><code>list.count(e)</code> returns number of occurrences of <code>e</code> in <code>list</code>, so we can execute it for each item in <code>myli... | 0 | 2016-06-07T14:35:23Z | [
"python"
] |
Count how many times a substring from list appears in a string | 37,682,127 | <p>I have a string:</p>
<pre><code>seq = '01234567890123456789'
</code></pre>
<p>that I want to first break up into intervals of 4. I found a previous answer </p>
<pre><code>n = 4
[seq[i:i+n] for i in range(0,len(seq,n)]
</code></pre>
<p>which gives me</p>
<pre><code>['0123', '4567', '8901', '2345', '6789']
</... | 0 | 2016-06-07T14:29:11Z | 37,682,419 | <pre><code>chunked = ['0123', '4567', '8901', '2345', '6789']
mylist = ['0123', '1111', '2345']
my_count = {}
for m in mylist:
for c in chunked:
if m == c:
try:
my_count[m] += 1
except KeyError:
my_count[m] = 1
>>> chunked
['0123', '4567', '8901', '2345... | 0 | 2016-06-07T14:41:42Z | [
"python"
] |
Count how many times a substring from list appears in a string | 37,682,127 | <p>I have a string:</p>
<pre><code>seq = '01234567890123456789'
</code></pre>
<p>that I want to first break up into intervals of 4. I found a previous answer </p>
<pre><code>n = 4
[seq[i:i+n] for i in range(0,len(seq,n)]
</code></pre>
<p>which gives me</p>
<pre><code>['0123', '4567', '8901', '2345', '6789']
</... | 0 | 2016-06-07T14:29:11Z | 37,682,746 | <pre><code>seq = '01234567890123456789'
chunks = ['0123', '4567', '8901', '2345', '6789']
dict = {}
for elt in chunks:
dict[elt] = seq.count(elt)
print(dict)
</code></pre>
| 0 | 2016-06-07T14:55:00Z | [
"python"
] |
Count how many times a substring from list appears in a string | 37,682,127 | <p>I have a string:</p>
<pre><code>seq = '01234567890123456789'
</code></pre>
<p>that I want to first break up into intervals of 4. I found a previous answer </p>
<pre><code>n = 4
[seq[i:i+n] for i in range(0,len(seq,n)]
</code></pre>
<p>which gives me</p>
<pre><code>['0123', '4567', '8901', '2345', '6789']
</... | 0 | 2016-06-07T14:29:11Z | 37,684,065 | <p>Add a tuple containing the chunk and its count in a list, in this case called counts.</p>
<pre><code>In [37]: seq = '01234567890123456789'
In [38]: chunks = ['0123', '4567', '8901', '2345', '6789']
In [39]: mylist = ['0123', '1111' '2345']
In [40]: counts = [(i, mylist.count(i)) for i in chunks]
In [41]: count... | 0 | 2016-06-07T15:56:39Z | [
"python"
] |
How to check if multiple words contain in a CSV column? | 37,682,158 | <p>I found several similar questions online on how to find a word in a specific column in a CSV file however, I didn't find any on checking multiple words.
Here's the problem: </p>
<pre><code>words = âsomethingâ
for row in data:
if words not in row[âcolumn header nameâ]:
writer.writerow[row]
</cod... | 0 | 2016-06-07T14:30:29Z | 37,682,361 | <p>You need the built-in <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>any()</code></a> checking if any of the words in the tuple is present in a row:</p>
<pre><code>words = ("something", "word" , "dada")
for row in data:
# skipping rows containing any of the "words"
if no... | 1 | 2016-06-07T14:38:47Z | [
"python",
"csv"
] |
How to add a header key:value pair when publishing a message with pika | 37,682,184 | <p>I am writing an automated test to test a consumer. So far I did not need to include a header when publishing messages but now I do. And it seems like its lacking documentation.</p>
<p>This is my publisher:</p>
<pre><code>class RMQProducer(object):
def __init__(self, host, exchange, routing_key):
self.... | 1 | 2016-06-07T14:31:24Z | 37,683,061 | <p>cant say where i get this, but i do it like:</p>
<pre><code>props = pika.BasicProperties({'headers': {'key': 'value'}})
channel.basic_publish(exchange=self.exchange,
routing_key=self.routing_key,
body=message, properties = props)
</code></pre>
| 0 | 2016-06-07T15:07:48Z | [
"python",
"rabbitmq",
"amqp",
"pika"
] |
How to add a header key:value pair when publishing a message with pika | 37,682,184 | <p>I am writing an automated test to test a consumer. So far I did not need to include a header when publishing messages but now I do. And it seems like its lacking documentation.</p>
<p>This is my publisher:</p>
<pre><code>class RMQProducer(object):
def __init__(self, host, exchange, routing_key):
self.... | 1 | 2016-06-07T14:31:24Z | 37,698,848 | <p>You would use <a href="http://pika.readthedocs.io/en/0.10.0/modules/spec.html#pika.spec.BasicProperties" rel="nofollow">pika.BasicProperties</a> to add headers.</p>
<pre><code>channel.basic_publish(exchange=self.exchange,
routing_key=self.routing_key,
properties=pika.Basi... | 1 | 2016-06-08T09:42:31Z | [
"python",
"rabbitmq",
"amqp",
"pika"
] |
In Tensorflow, how to unravel the flattened indices obtained by tf.nn.max_pool_with_argmax? | 37,682,201 | <p>I meet a problem: After I use the <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#max_pool_with_argmax" rel="nofollow">tf.nn.max_pool_with_argmax</a>, I obtain the indices i.e.
<code>argmax: A Tensor of type Targmax. 4-D. The flattened indices of the max values chosen for each output.</cod... | 2 | 2016-06-07T14:32:08Z | 39,777,998 | <p>I had the same problem today and I ended up with this solution:</p>
<pre class="lang-py prettyprint-override"><code>def unravel_argmax(argmax, shape):
output_list = []
output_list.append(argmax // (shape[2] * shape[3]))
output_list.append(argmax % (shape[2] * shape[3]) // shape[3])
return tf.pack(ou... | 0 | 2016-09-29T18:56:17Z | [
"python",
"tensorflow",
"deep-learning"
] |
insert element into list, move pre-existing elements | 37,682,208 | <p>I'm trying to create a defined function (without list/string methods):
so far i have code to update at the given location, but I'm struggling to create code that can insert the variable at list location, and move existing elements over. I want the output to be ['a', 'b', 'c', 'd'] instead of ['a', 'b', 'c', 'e'].</p... | 0 | 2016-06-07T14:32:16Z | 37,683,294 | <pre><code>def insert(list1, var, i):
new_list = list1[:i]
new_list.append(var)
new_list.extend(list1[i:])
return new_list
list = ['a', 'b', 'd', 'e']
func = insert(list, 'c', 2)
</code></pre>
<p>take the part of list1 up to i. This is called slicing
tack var onto new_list with append
tack on the res... | 0 | 2016-06-07T15:19:15Z | [
"python",
"list",
"function",
"python-3.x"
] |
insert element into list, move pre-existing elements | 37,682,208 | <p>I'm trying to create a defined function (without list/string methods):
so far i have code to update at the given location, but I'm struggling to create code that can insert the variable at list location, and move existing elements over. I want the output to be ['a', 'b', 'c', 'd'] instead of ['a', 'b', 'c', 'e'].</p... | 0 | 2016-06-07T14:32:16Z | 37,683,827 | <p>In my approach, the method returns the half splitted list with the element you need to add between them.</p>
<pre><code>In [15]: list = ['a', 'b', 'd', 'e']
In [16]: def insert(lst, var, i):
....: return lst[:i] + [var] + lst[i:]
....:
In [17]: insert(list, 'c', 2)
Out[17]: ['a', 'b', 'c', 'd', 'e']
</... | 0 | 2016-06-07T15:44:27Z | [
"python",
"list",
"function",
"python-3.x"
] |
insert element into list, move pre-existing elements | 37,682,208 | <p>I'm trying to create a defined function (without list/string methods):
so far i have code to update at the given location, but I'm struggling to create code that can insert the variable at list location, and move existing elements over. I want the output to be ['a', 'b', 'c', 'd'] instead of ['a', 'b', 'c', 'e'].</p... | 0 | 2016-06-07T14:32:16Z | 37,692,954 | <p>Using slicing, it's fairly easy to do this without use of any <code>list</code> methods at all. If you're using Python 3.5+ with <a href="http://www.python.org/dev/peps/pep-0448/" rel="nofollow">additional unpacking generalizations</a>, it even looks pretty:</p>
<pre><code>def insert(list1, var, i):
# Reassign ... | 0 | 2016-06-08T03:55:24Z | [
"python",
"list",
"function",
"python-3.x"
] |
Mask a 3d array with a 2d mask in numpy | 37,682,284 | <p>I have a 3-dimensional array that I want to mask using a 2-dimensional array that has the same dimensions as the two rightmost of the 3-dimensional array. Is there a way to do this without writing the following loop?</p>
<pre><code>import numpy as np
nx = 2
nt = 4
field3d = np.random.rand(nt, nx, nx)
field2d = np... | 3 | 2016-06-07T14:35:48Z | 37,683,073 | <p>Without the loop you could write it as:</p>
<pre><code>field3d_mask[:,:,:] = field2d[np.newaxis,:,:] > 0.3
</code></pre>
<p>For example:</p>
<pre><code>field3d_mask_1 = np.zeros(field3d.shape, dtype=bool)
field3d_mask_2 = np.zeros(field3d.shape, dtype=bool)
for t in range(nt):
field3d_mask_1[t,:,:] = fiel... | 4 | 2016-06-07T15:08:32Z | [
"python",
"arrays",
"numpy",
"mask"
] |
Mask a 3d array with a 2d mask in numpy | 37,682,284 | <p>I have a 3-dimensional array that I want to mask using a 2-dimensional array that has the same dimensions as the two rightmost of the 3-dimensional array. Is there a way to do this without writing the following loop?</p>
<pre><code>import numpy as np
nx = 2
nt = 4
field3d = np.random.rand(nt, nx, nx)
field2d = np... | 3 | 2016-06-07T14:35:48Z | 37,690,587 | <p>There's <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.broadcast_to.html" rel="nofollow"><code>numpy.broadcast_to</code></a> (new in Numpy 1.10.0):</p>
<pre><code>field3d_mask = np.broadcast_to(field2d > 0.3, field3d.shape)
</code></pre>
| 2 | 2016-06-07T22:43:16Z | [
"python",
"arrays",
"numpy",
"mask"
] |
Output exception to browser when Flask app has error | 37,682,376 | <p>When my deployed Flask application has an error, I only see a standard error message in the browser.</p>
<blockquote>
<p>Internal Server Error</p>
<p>The server encountered an internal error and was unable to complete
your request. Either the server is overloaded or there is an error in
the application.<... | 0 | 2016-06-07T14:39:31Z | 37,682,477 | <p>For debugging purposes you may try this:</p>
<pre><code>import traceback
@app.errorhandler(Exception)
def handle_500(e=None):
app.logger.error(traceback.format_exc())
return 'Internal server error occured', 500
</code></pre>
| 0 | 2016-06-07T14:44:05Z | [
"python",
"flask"
] |
A rather special parsing of a txt file | 37,682,482 | <p>Alright good people of stackOverflow, my question is on the broad subject of parsing. The information i want to obtain is on multiple positions on a text file marked by begin and end headers (special strings) on each appearance. I want to get everything that's between these headers. The code i have implemented so fa... | 1 | 2016-06-07T14:44:18Z | 37,682,846 | <p>Oye gentle stack traveller. Time hast come for thee to use the power of regex</p>
<p>Basic usage</p>
<pre><code>import re
m = re.search('start(.*?)end', 'startsecretend')
m.group(1)
'secret'
</code></pre>
<ul>
<li><code>.</code> matches any character</li>
<li><code>*</code> repeats any number of times</li>
<li><c... | 2 | 2016-06-07T14:59:01Z | [
"python",
"python-3.x",
"parsing"
] |
A rather special parsing of a txt file | 37,682,482 | <p>Alright good people of stackOverflow, my question is on the broad subject of parsing. The information i want to obtain is on multiple positions on a text file marked by begin and end headers (special strings) on each appearance. I want to get everything that's between these headers. The code i have implemented so fa... | 1 | 2016-06-07T14:44:18Z | 37,683,808 | <p>I agree regex is a good way to go here, but this is a more direct application to your problem:</p>
<pre><code>import re
options = re.DOTALL | re.MULTILINE
contents = open('parsexample.txt').read()
m = re.search('ga_group_create(.*)ga_group_create', contents,
options)
lines_in_between = m.gro... | 1 | 2016-06-07T15:43:39Z | [
"python",
"python-3.x",
"parsing"
] |
Why Eclipse Pydev Hierarchy view doesn't work? | 37,682,510 | <p>I am using PyDev to navigate the code of a relatively large Python projects. I want to view the hierarchy graph of the classes. I hit f4 to open the Hierarchy View.</p>
<p>But the view is completely empty, and there is nothing in it. I don't know why. </p>
| 0 | 2016-06-07T14:45:39Z | 37,685,321 | <p>I just tested it here and it worked for me... To give an example:</p>
<p>Say you have:</p>
<pre><code>class ClassA(object):
pass
class ClassB(ClassA):
pass
</code></pre>
<p>Now, with the cursor over 'ClassB' press 'F4': the hierarchy should be showing properly.</p>
<p>If it doesn't work for you, the fir... | 0 | 2016-06-07T17:09:16Z | [
"python",
"eclipse",
"pydev"
] |
Ansible lineine file with regex is adding new line when it shouldn't | 37,682,639 | <p>I currently have this file for configuring nagios nrpe:</p>
<pre><code>/etc/xinetd.d/nrpe:
# default: on
# description: NRPE (Nagios Remote Plugin Executor)
service nrpe
{
flags = REUSE
socket_type = stream
port = 5666
wait = no
us... | 0 | 2016-06-07T14:51:00Z | 37,688,624 | <p>The problem is you are matching the newline too. Don't include the newline in your match. This should work:</p>
<pre><code>regexp: '\s*only_from\s+=\s*((\d{1,3}\.){3}\d{1,3})\s*'
</code></pre>
<p>Now why did your plain python work? Because you conveniently omitted the newline in your test. Your test string should ... | 2 | 2016-06-07T20:22:04Z | [
"python",
"regex",
"ansible",
"ansible-playbook",
"python-2.x"
] |
access elements of the list of tuples with variable length and save the output in the same format | 37,682,744 | <p>I have a list of tuples like below</p>
<pre><code>a=[(40, 41, 42, 43), (44, 45, 46, 47, 48), (109, 110, 111, 112, 113, 114)]
</code></pre>
<p>Each number represents the ID of a chord. Each tuple represent a part which can have variable number of chords. </p>
<p>I want to apply a loop in such a way that I can acce... | 1 | 2016-06-07T14:54:53Z | 37,682,894 | <pre><code>[tuple(getLength(i) for i in tup) for tup in a]
</code></pre>
<p>Basically you loop over each "part", which is in fact a tuple through the fragment of code <code>for tup in a</code>. For each of these "part" you want you apply the function you want - here <code>getLength</code> - to each chord. Basically wh... | 1 | 2016-06-07T15:00:54Z | [
"python",
"linux",
"list",
"tuples"
] |
How to force dtype to integer in dataframe | 37,682,801 | <p>I am working with a dataframe that has a column in which all values are None. By default the dtype for this column is object. I need it to be an integer type, likely int64. Why is irrelevant; that's what I need.</p>
<p>I've tried the following:</p>
<pre><code>df['field'] = df['field'].astype(int)
</code></pre>
<p... | 1 | 2016-06-07T14:57:05Z | 37,683,806 | <p>One thing I had not tried, since it just shouldn't work, actually is the answer. Substituting np.NaN for None results in the table being populated with NULL in the desired field.</p>
| 1 | 2016-06-07T15:43:33Z | [
"python",
"pandas",
"dataframe",
null
] |
Python Pandas DF - Group column with corresponding frequency count of another column | 37,682,921 | <p>I have a data frame in python. In it I have one column with different people and another column with different products they bought.
I try to create a summary for each person how much they bought of each product. Therefore, I tried to group by persons and products and count, but somehow I'm running into trouble. </... | 1 | 2016-06-07T15:01:57Z | 37,682,997 | <p>You can first add string <code>cat</code> to values, but you need cast <code>int</code> to <code>str</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>. Then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pand... | 2 | 2016-06-07T15:04:55Z | [
"python",
"pandas",
"dataframe",
"pivot-table"
] |
SQL in Python - using global variables | 37,682,923 | <p>I'm using <code>pymysql</code> package and need to write a query that will get 3 numeric variables that represent the specific date as: year month and day - and use them.</p>
<p>This will look like this:</p>
<pre><code>INSERT INTO tbl1
SELECT id, user_id, search_term
FROM main_table
WHERE year = (var1) AND mont... | 0 | 2016-06-07T15:01:59Z | 37,683,400 | <p>You can use python's string interpolation:</p>
<pre><code>v1 = 2016
v2 = 6
v3 = 17
query = """INSERT INTO tbl1
SELECT id, user_id, search_term
FROM main_table
WHERE year = {var1}
AND month = {var2}
AND day = {var3};
INSERT INTO tbl2
SELECT id,user_id, find_term
FROM main_table
WHERE year = {var1}
AND mon... | 0 | 2016-06-07T15:24:02Z | [
"python",
"sql",
"variables",
"dynamic",
"impala"
] |
SQL in Python - using global variables | 37,682,923 | <p>I'm using <code>pymysql</code> package and need to write a query that will get 3 numeric variables that represent the specific date as: year month and day - and use them.</p>
<p>This will look like this:</p>
<pre><code>INSERT INTO tbl1
SELECT id, user_id, search_term
FROM main_table
WHERE year = (var1) AND mont... | 0 | 2016-06-07T15:01:59Z | 37,683,587 | <p>First of all - i want to say that it works fine with 1 query. the problems begins when i have 2 (or more) queries and python think its too much variables.</p>
<p>This is the code.</p>
<p>This part is for getting the 3 variables:</p>
<p><code>yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()... | 0 | 2016-06-07T15:32:23Z | [
"python",
"sql",
"variables",
"dynamic",
"impala"
] |
Python sum(generator): calling an external function | 37,682,948 | <p>take the code:</p>
<pre><code>SUM = sum(x() for x in xs)
</code></pre>
<p>I am writing some code that is in need of calling another function before each x() such that x() will compute the right value</p>
<p>is the only way to do this like so?</p>
<pre><code>for x in xs: x.pre()
SUM = sum(x() for x in xs)
</code... | 3 | 2016-06-07T15:02:50Z | 37,683,571 | <p>I would simply use the <code>for</code>-loop you already presented.</p>
<p>There are ways to do what you want in other ways. For example you could use <code>functools.reduce</code> with a customized function here instead of <code>sum</code> :</p>
<pre><code>def pre_then_add(accumulated, new_one):
new_one.pre()... | 1 | 2016-06-07T15:31:37Z | [
"python",
"generator"
] |
Matrix assignment in rpy2 | 37,682,986 | <p>With rpy2, in python 3.5, I can define an R matrix:</p>
<pre><code>import rpy2.robjects as robjects
m = robjects.r.matrix(robjects.IntVector(range(10)), nrow=2, ncol = 5)
print(m)
[,1] [,2] [,3] [,4] [,5]
[1,] 0 2 4 6 8
[2,] 1 3 5 7 9
</code></pre>
<p>I can then <a href="http://... | 1 | 2016-06-07T15:04:27Z | 37,703,636 | <p>This should normally be described in the documentation.</p>
<p>Let us know if the following is not answering the question: <a href="http://rpy2.readthedocs.io/en/version_2.8.x/vector.html#assigning-r-style" rel="nofollow">http://rpy2.readthedocs.io/en/version_2.8.x/vector.html#assigning-r-style</a></p>
| 1 | 2016-06-08T13:16:57Z | [
"python",
"python-3.x",
"rpy2"
] |
python wheel file install TA_lib*.whl | 37,683,003 | <p>I am trying to install the 'TA_Lib-0.4.9-cp27-*.whl' file with powershell (windows). I receive the message 'file ... looks like a filename, but the file does not exist'.</p>
<p>I run '<code>pip install C:\Programs\TA_Lib-0.4.9-cp27-*.whl</code>' from <code>C:\Programs></code> where the whl file is located.</p>
... | 1 | 2016-06-07T15:05:11Z | 37,704,826 | <p>What ended up working for me is to write the full name of the file, instead of using '*' after the beginning of the file name. 'pip install' command works fine with the full name of the wheel (.whl) file - in this instance.</p>
| 0 | 2016-06-08T14:05:11Z | [
"python",
"python-wheel"
] |
How to create HTTP GET request Scapy? | 37,683,026 | <p>I need to create HTTP GET request and save the data response.
I tried to use this: </p>
<pre><code> syn = IP(dst=URL) / TCP(dport=80, flags='S')
syn_ack = sr1(syn)
getStr = 'GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n'
request = IP(dst='www.google.com') / TCP(dport=80, sport=syn_ack[TCP].dport,
... | 3 | 2016-06-07T15:06:17Z | 37,696,246 | <p>You are sending a RST segment in response to the SYN-ACK because your kernel has no knowledge of the SYN you sent via Scapy (see <a href="http://stackoverflow.com/questions/9058052/unwanted-rst-tcp-packet-with-scapy">here</a>). This could be solved with an iptable rule:</p>
<p><code>iptables -A OUTPUT -p tcp --tcp-... | 2 | 2016-06-08T07:43:00Z | [
"python",
"http",
"get",
"scapy"
] |
How to create HTTP GET request Scapy? | 37,683,026 | <p>I need to create HTTP GET request and save the data response.
I tried to use this: </p>
<pre><code> syn = IP(dst=URL) / TCP(dport=80, flags='S')
syn_ack = sr1(syn)
getStr = 'GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n'
request = IP(dst='www.google.com') / TCP(dport=80, sport=syn_ack[TCP].dport,
... | 3 | 2016-06-07T15:06:17Z | 37,716,000 | <p>You are sending a SYN and correctly receiving a SYN_ACK. At this point, you should generate and send an ACK based on the SYN_ACK that you've received, and THEN finally transmit the HTTP GET request. It seems that you are somewhat confused about the TCP 3-way handshake mechanism. In short, you are not supposed to 'ge... | 2 | 2016-06-09T02:45:21Z | [
"python",
"http",
"get",
"scapy"
] |
Splitting csv file of multiple objects over time by time-point | 37,683,085 | <p>Here I have an example file of multiple objects each measured at the same time-points (also ND.T represents each unique time point). I would like to split this file into separate files (using a python script) containing all objects unique to each time-point still containing the header.</p>
<p>Original file:</p>
<p... | 1 | 2016-06-07T15:08:56Z | 37,683,227 | <p>You can use <a href="http://pandas.pydata.org/" rel="nofollow"><code>pandas</code></a> to achieve this:</p>
<pre><code>import pandas as pd
df = pd.read_csv(your_file)
df.groupby('Time [s]').apply(lambda x: x.to_csv(str(x.name) + '.csv'))
</code></pre>
<p>The above will load your csv using <a href="http://pandas.py... | 4 | 2016-06-07T15:15:50Z | [
"python",
"excel",
"csv",
"split",
"divide"
] |
Raise exception on multiple specific "strings", python | 37,683,112 | <p>I have a file which contains:</p>
<p>XYZname_1</p>
<p>XYZname_2</p>
<p>XYZname_3</p>
<p>In my script I am using a re.search to check if the names are incorrect, if they are I do a <code>raise exception</code>. If both names are incorrect it will only raise exception on the first on and then "crash", in other wor... | 0 | 2016-06-07T15:10:41Z | 37,683,213 | <p>Collect the names/matches in a list. Then, after the loop, raise an exception if necessary. You also need <code>findall()</code> instead of <code>search()</code> from what I understand.</p>
<p>At the end you would have something like:</p>
<pre><code>matches = []
for x in range(0, 3):
#Some code here which is ... | 1 | 2016-06-07T15:15:11Z | [
"python"
] |
Raise exception on multiple specific "strings", python | 37,683,112 | <p>I have a file which contains:</p>
<p>XYZname_1</p>
<p>XYZname_2</p>
<p>XYZname_3</p>
<p>In my script I am using a re.search to check if the names are incorrect, if they are I do a <code>raise exception</code>. If both names are incorrect it will only raise exception on the first on and then "crash", in other wor... | 0 | 2016-06-07T15:10:41Z | 37,683,319 | <p>Use try/catch on each item in your iteration instead of a single pass:</p>
<pre><code>for x in range():
try:
re.search ...
except:
raise exception ...
</code></pre>
<p>Not a python expert but from a pure code/logic perspective that should do the trick.</p>
| 0 | 2016-06-07T15:20:26Z | [
"python"
] |
How to make MyHDL generate variable with arbitrary width in process? | 37,683,137 | <p>I would like to do a sum of signals that I have in a list, naturally I have used variable and for (as I would in VHDL):</p>
<pre><code> @always_comb
def sum():
sum = 0
for i in range(len(summands)):
sum = sum + summands[i]
product.next = sum
</code></pre>
<p>The problem i... | 0 | 2016-06-07T15:12:04Z | 37,683,739 | <p>I have managed to make very ugly workaround:</p>
<pre><code>@always_comb
def sum():
sum = intbv(0, min=vmin, max=vmax)
for i in range(len(summands)):
sum = intbv(sum + summands[i], min=vmin, max=vmax)
product.next = sum
</code></pre>
<p>In this manner it will generate correct VHDL:</p>
<pre><c... | 0 | 2016-06-07T15:39:30Z | [
"python",
"fpga",
"myhdl"
] |
Getting <script> and <div> tags from Plotly using Python | 37,683,147 | <p>I was wondering if anyone knew a good way (preferably a built in method, but I'm open to writing my own of course) to get the and tags from the HTML output of the Plotly offline client.</p>
<p>I'm already familiar with bokeh and really enjoy using it for 2D visualization, but would really like to integrate Plotly... | 0 | 2016-06-07T15:12:23Z | 38,033,016 | <p>If you call:</p>
<pre><code>plotly.offline.plot(data, filename='file.html')
</code></pre>
<p>It creates a file named <code>file.html</code> and opens it up in your web browser. However, if you do:</p>
<pre><code>plotly.offline.plot(data, include_plotlyjs=False, output_type='div')
</code></pre>
<p>the call will r... | 1 | 2016-06-25T21:12:31Z | [
"python",
"html",
"plotly"
] |
Elasticsearch : Cannot connect using python when shield is installed | 37,683,303 | <p>I am using elasticsearch 2.3.1 and python 2.7. I am trying to create a simple instance and testing as</p>
<pre><code>esInstance = Elasticsearch(['https://'+shield_uname+":"+shield_pass+"@"+server+":"+port])
print esInstance.info()
</code></pre>
<p>but i get</p>
<pre><code>elasticsearch.exceptions.SSLError: Conne... | 0 | 2016-06-07T15:19:50Z | 37,683,845 | <p>I think you're better off just <a href="http://elasticsearch-py.readthedocs.io/en/2.3.0/#ssl-and-authentication" rel="nofollow">passing the fields as arguments</a>, given that you have them as separate variables already.</p>
<p>This the "fullest" version of the authentication example, with your variables plugged in... | 1 | 2016-06-07T15:45:41Z | [
"python",
"python-2.7",
"ssl",
"elasticsearch",
"elasticsearch-2.0"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.