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 |
|---|---|---|---|---|---|---|---|---|---|
json2html, python: json data not converted to html | 39,831,894 | <p>I'm trying to format json data to html using json2html.
The json data look like this:</p>
<pre><code>json_obj = [{"Agent Status": "status1", "Last backup": "", "hostId": 1234567, "hostfqdn": "test1.example.com", "username": "user1"}, {"Agent Status": "status2", "Last backup": "", "hostId": 2345678, "hostfqdn": "tes... | 0 | 2016-10-03T12:39:22Z | 39,855,460 | <p>My list of dictionaries <code>anomaly_list</code> was already in a json format, so trying to convert it using <code>json.dumps(anomaly_list, sort_keys=True)</code> was turning into a string, which was not what I wanted.
I solved the issue by leaving my list of dictionaries as it is and this code now works:</p>
<pre... | 0 | 2016-10-04T14:51:29Z | [
"python",
"html",
"json",
"json2html"
] |
How do I transfer varibles through functions in Python | 39,831,915 | <p>I am trying to read from keyboard a number and validate it</p>
<p>This is what I have but it doesn't work. </p>
<p>No error but it doesn't <strong>remember</strong> the number I introduced</p>
<pre><code>def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
... | 1 | 2016-10-03T12:40:56Z | 39,831,969 | <p>It appears as though you are not returning the result of the read() function.</p>
<p>The last line of your read function should be "return a"</p>
<p>And then when you call the read function you would say "a = read()"</p>
| 0 | 2016-10-03T12:43:44Z | [
"python",
"variables"
] |
How do I transfer varibles through functions in Python | 39,831,915 | <p>I am trying to read from keyboard a number and validate it</p>
<p>This is what I have but it doesn't work. </p>
<p>No error but it doesn't <strong>remember</strong> the number I introduced</p>
<pre><code>def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
... | 1 | 2016-10-03T12:40:56Z | 39,831,996 | <p><code>a</code> is a local variable to the two functions and isn't visible to the rest of your code as is. The best way to fix your code is by returning <code>a</code> from your <code>read()</code> function. Also, the spacing is off in your <code>IsInteger()</code> function.</p>
<pre><code>def IsInteger(b):
tr... | 1 | 2016-10-03T12:45:08Z | [
"python",
"variables"
] |
How do I transfer varibles through functions in Python | 39,831,915 | <p>I am trying to read from keyboard a number and validate it</p>
<p>This is what I have but it doesn't work. </p>
<p>No error but it doesn't <strong>remember</strong> the number I introduced</p>
<pre><code>def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
... | 1 | 2016-10-03T12:40:56Z | 39,832,009 | <p>I think this is what you are trying to achieve.</p>
<pre><code>def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
global a
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)
</code></p... | 1 | 2016-10-03T12:45:44Z | [
"python",
"variables"
] |
MissingSectionHeaderError: File contains no section headers.(configparser) | 39,831,956 | <p>I'm using configparser in order to read and modify automatically a file conf named 'streamer.conf'.
I'm doing this :</p>
<pre><code>import configparser
config = configparser.ConfigParser()
config.read('C:/Users/../Desktop/streamer.conf')
</code></pre>
<p>And then it breaks apart with this Error message :</p>
<p... | 0 | 2016-10-03T12:42:44Z | 39,833,493 | <p>You didn't include <code>streamer.conf</code>, but from the error message, it's not in the right format. <code>configparser</code> is used for parsing "INI" files:</p>
<pre><code>[section1]
setting1 = value
setting2 = value
[section2]
setting3 = value
setting1 = value
</code></pre>
<p>etc.</p>
| 0 | 2016-10-03T14:01:54Z | [
"python",
"python-2.7",
"configuration",
"configuration-files",
"configparser"
] |
User inputted integer using while statement | 39,832,113 | <p>Ok need to understand why my code is not working.
At the moment it's getting stuck in a infinite loop of asking the user for a pin after a wrong pin is inputted.</p>
<p>I believe I'm screwing up the while statement somehow.</p>
<pre><code>def inputValidator():
userInput = requestInteger("Please input a PIN bet... | 0 | 2016-10-03T12:50:48Z | 39,832,196 | <p>You don't assign nothing in the while loop. userInput never gets updated - hence you can't exit the loop</p>
| 1 | 2016-10-03T12:54:53Z | [
"python"
] |
User inputted integer using while statement | 39,832,113 | <p>Ok need to understand why my code is not working.
At the moment it's getting stuck in a infinite loop of asking the user for a pin after a wrong pin is inputted.</p>
<p>I believe I'm screwing up the while statement somehow.</p>
<pre><code>def inputValidator():
userInput = requestInteger("Please input a PIN bet... | 0 | 2016-10-03T12:50:48Z | 39,832,205 | <p>you aren't assigning requestInteger to userInput </p>
<pre><code>while 1 > userInput > 1000 :
userInput =requestInteger("Your PIN is not within 1 - 1000, please try again")
</code></pre>
| 1 | 2016-10-03T12:55:20Z | [
"python"
] |
User inputted integer using while statement | 39,832,113 | <p>Ok need to understand why my code is not working.
At the moment it's getting stuck in a infinite loop of asking the user for a pin after a wrong pin is inputted.</p>
<p>I believe I'm screwing up the while statement somehow.</p>
<pre><code>def inputValidator():
userInput = requestInteger("Please input a PIN bet... | 0 | 2016-10-03T12:50:48Z | 39,832,223 | <p>Try this:</p>
<pre><code>def inputValidator():
userInput = requestInteger("Please input a PIN between 1 - 1000")
while userInput<1 or userInput>1000:
userInput = requestInteger("Your PIN is not within 1 - 1000, please try again")
print("Thanks! your new PIN is " + str(userInput))
</code></... | 2 | 2016-10-03T12:56:05Z | [
"python"
] |
Strange behavior when appending dictionary to list | 39,832,125 | <p>I am reading JSON into my script and building a list consisting of dictionaries.</p>
<p>My JSON:</p>
<pre><code>{
"JMF": {
"table1": {
"email": "JMF1@fake.com",
"guests": [
"test1",
"test2"
]
},
"table2": {
"email": "JMF2@f... | 0 | 2016-10-03T12:51:28Z | 39,832,231 | <p>You are re-appending the <em>same single dictionary</em> each iteration:</p>
<pre><code>users_dict = {} # only one copy of this dictionary is ever created
users_list = []
for user in json_file[key][table_key]['guests']:
users_dict['username'] = user
users_dict['password'] = generate_password()
users_li... | 2 | 2016-10-03T12:56:28Z | [
"python",
"json",
"python-3.x"
] |
Tensorflow control_dependencies not working with list | 39,832,190 | <p>I have a cost, which depends on two list of variables <code>a</code> and <code>b</code>.<br>
I want to :</p>
<ol>
<li>calculate both gradients of the cost at the current point, </li>
<li>update the loss w.r.t. the first list of variables (<code>a</code>)</li>
<li>update the loss w.r.t. the second list of variable (... | 0 | 2016-10-03T12:54:38Z | 39,837,261 | <p>Your <code>grad_cost_wrt_a</code> and <code>grad_cost_wrt_b</code> variables are lists, do something like <code>grad_cost_wrt_a[0], grad_cost_wrt_b[0]</code></p>
| 1 | 2016-10-03T17:33:53Z | [
"python",
"tensorflow",
"deep-learning"
] |
Testing of existence of a repeated field in a protobuff message | 39,832,547 | <p>I have a google protobuf message:</p>
<pre><code>message Foo {
required int bar = 1;
}
</code></pre>
<p>I know that in order to test the fields of message, we can use:</p>
<pre><code>foo.bar = 1
assert foo.HasField("bar")
</code></pre>
<p>However "HasField" doesn't work for repeated field types.
How to test fo... | 0 | 2016-10-03T13:13:30Z | 39,963,852 | <p>You could try to test the lenght of the repeated field:</p>
<pre><code>assert len(foo.bar) == 0
</code></pre>
| 0 | 2016-10-10T17:42:12Z | [
"python",
"unit-testing",
"protocol-buffers"
] |
Repeat for i in list - n number of times | 39,832,566 | <p>After some confusion (probably if not definitely caused by a bad question asking on my part) I am trying to work how to achieve a code to perform the following operation, but n number of times:</p>
<pre><code>def 1_level:
for i in list:
for j in i:
mylist.append(i)
def 2_levels:
for i i... | 2 | 2016-10-03T13:14:40Z | 39,841,003 | <p>You were almost there with your <code>prunelist</code> function, there are just a few issues:</p>
<ul>
<li>You cannot overwrite a passed list by simply doing <code>mylist = templist</code>. This does modify the <code>mylist</code> variable but not the original variable. You could replace the contents of the origina... | 2 | 2016-10-03T21:53:47Z | [
"python",
"python-3.x"
] |
python lxml: how to get text from a element which has a child element | 39,832,587 | <p>I want to extract sometext from the html code, but the following doesn't r
eturn sometext, instead it return "\n". So how to get sometest?</p>
<pre><code>a=html.fromstring("""
<p class="clearfix">
<i class="xueli"></i>
sometext
</p>
""")
a.find(".//i").getparent().text
</code></pre>
| 1 | 2016-10-03T13:15:55Z | 39,832,753 | <p>Instead of <code>.text</code>, use <code>text_content()</code> method:</p>
<pre><code>In [5]: a.find(".//i").getparent().text_content().strip()
Out[5]: 'sometext'
</code></pre>
<p>Or, you can get to the <em>following text sibling</em> of the <code>i</code> element:</p>
<pre><code>In [6]: a.xpath(".//i/following-s... | 1 | 2016-10-03T13:23:57Z | [
"python",
"lxml"
] |
PyQt: How do I load a ui file from a resource? | 39,832,610 | <p>In general, I load all my ui files via the <code>loadui()</code> method, and this works fine for me. This looks like this:</p>
<pre><code>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
The modules for Qt are imported.
PyQt are a set of Python bindings for Qt.
'''
from PyQt4.QtGui import QDialog
from PyQt4.uic imp... | 1 | 2016-10-03T13:16:36Z | 39,835,058 | <p>It's not really much different from what you were already doing:</p>
<pre><code>from PyQt4.QtCore import QFile
from PyQt4.uic import loadUiType
import resources_rc
def loadUiClass(path):
stream = QFile(path)
stream.open(QFile.ReadOnly)
try:
return loadUiType(stream)[0]
finally:
str... | 1 | 2016-10-03T15:22:06Z | [
"python",
"qt",
"pyqt",
"pyqt4"
] |
Meaning of self.__dict__ = self in a class definition | 39,832,721 | <p>I'm trying to understand the following snippet of code:</p>
<pre><code>class Config(dict):
def __init__(self):
self.__dict__ = self
</code></pre>
<p>What is the purpose of the line <code>self.__dict__ = self</code>? I suppose it overrides the default <code>__dict__</code> function with something that s... | 3 | 2016-10-03T13:22:41Z | 39,832,796 | <p>Assigning the dictionary <code>self</code> to <code>__dict__</code> allows attribute access and item access:</p>
<pre><code>>>> c = Config()
>>> c.abc = 4
>>> c['abc']
4
</code></pre>
| 3 | 2016-10-03T13:26:39Z | [
"python"
] |
Meaning of self.__dict__ = self in a class definition | 39,832,721 | <p>I'm trying to understand the following snippet of code:</p>
<pre><code>class Config(dict):
def __init__(self):
self.__dict__ = self
</code></pre>
<p>What is the purpose of the line <code>self.__dict__ = self</code>? I suppose it overrides the default <code>__dict__</code> function with something that s... | 3 | 2016-10-03T13:22:41Z | 39,833,012 | <p>As per <a href="https://docs.python.org/2/library/stdtypes.html#object.__dict__" rel="nofollow">Python Document</a>, <code>object.__dict__</code> is:</p>
<blockquote>
<p>A dictionary or other mapping object used to store an objectâs (writable) attributes.</p>
</blockquote>
<p>Below is the sample example:</p>
... | 2 | 2016-10-03T13:36:20Z | [
"python"
] |
Convert Pandas Dataframe Date Index and Column to Numpy Array | 39,832,735 | <p>How can I convert 1 column and the index of a Pandas dataframe with several columns to a Numpy array with the dates lining up with the correct column value from the dataframe?</p>
<p>There are a few issues here with data type and its driving my nuts trying to get both the index and the column out and into the one a... | 0 | 2016-10-03T13:23:19Z | 39,832,803 | <p>IIUC you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html" rel="nofollow"><code>values</code></a>:</p>
<pre><code>start = pd.to_datetime('2015-02-24')
rng = pd.date_range(start, periods=5)
df = pd.DataFrame({'a': range(5), 'b':list('ABCDE')}, index=rng)
print (df)
... | 1 | 2016-10-03T13:26:59Z | [
"python",
"arrays",
"pandas",
"numpy",
"dataframe"
] |
Convert Pandas Dataframe Date Index and Column to Numpy Array | 39,832,735 | <p>How can I convert 1 column and the index of a Pandas dataframe with several columns to a Numpy array with the dates lining up with the correct column value from the dataframe?</p>
<p>There are a few issues here with data type and its driving my nuts trying to get both the index and the column out and into the one a... | 0 | 2016-10-03T13:23:19Z | 39,833,244 | <p>If <code>A</code> is dataframe and <code>col</code> the column:</p>
<p><code>import pandas as pd
output = pd.np.column_stack((A.index.values, A.col.values))</code></p>
| 1 | 2016-10-03T13:47:56Z | [
"python",
"arrays",
"pandas",
"numpy",
"dataframe"
] |
Getting previous index values of a python list items after shuffling | 39,832,773 | <p>Let's say I have such a python list:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>by using <code>random.shuffle</code>, </p>
<pre><code>>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>
<p>I am having the above list.</p>
<... | 3 | 2016-10-03T13:25:10Z | 39,832,824 | <p>If your values are unique, just use the <code>list.index</code> method. For example, you can do this:</p>
<pre><code>import random
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
start_l = l[:]
random.shuffle(l)
for elem in l:
print(elem, '->', start_l.index(elem))
</code></pre>
<p>Of course, in your example this is tri... | 2 | 2016-10-03T13:27:52Z | [
"python"
] |
Getting previous index values of a python list items after shuffling | 39,832,773 | <p>Let's say I have such a python list:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>by using <code>random.shuffle</code>, </p>
<pre><code>>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>
<p>I am having the above list.</p>
<... | 3 | 2016-10-03T13:25:10Z | 39,832,854 | <p>You could pair each item with its index using <code>enumerate</code>, then shuffle that.</p>
<pre><code>>>> import random
>>> l = [4, 8, 15, 16, 23, 42]
>>> x = list(enumerate(l))
>>> random.shuffle(x)
>>> indices, l = zip(*x)
>>> l
(4, 8, 15, 23, 42, 16)
>&g... | 12 | 2016-10-03T13:28:48Z | [
"python"
] |
Getting previous index values of a python list items after shuffling | 39,832,773 | <p>Let's say I have such a python list:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>by using <code>random.shuffle</code>, </p>
<pre><code>>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>
<p>I am having the above list.</p>
<... | 3 | 2016-10-03T13:25:10Z | 39,832,887 | <p>To keep track of everything using a dictionary, one can do this: </p>
<p>Use <code>enumerate</code> in your dictionary comprehension to have index and value in your iteration, and then assign value as key, and index as value. </p>
<pre><code>import random
l = [5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
d = {v: i for i, v in e... | 1 | 2016-10-03T13:30:32Z | [
"python"
] |
Getting previous index values of a python list items after shuffling | 39,832,773 | <p>Let's say I have such a python list:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>by using <code>random.shuffle</code>, </p>
<pre><code>>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>
<p>I am having the above list.</p>
<... | 3 | 2016-10-03T13:25:10Z | 39,832,896 | <p>Create a copy of the original <code>list</code> and shuffle the copy:</p>
<pre><code>>>> import random
>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l_copy = list(l) # <-- Creating copy of the list
>>> random.shuffle(l_copy) # <-- Shuffling the copy
>>> l_copy ... | 1 | 2016-10-03T13:30:52Z | [
"python"
] |
Getting previous index values of a python list items after shuffling | 39,832,773 | <p>Let's say I have such a python list:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>by using <code>random.shuffle</code>, </p>
<pre><code>>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>
<p>I am having the above list.</p>
<... | 3 | 2016-10-03T13:25:10Z | 39,833,394 | <p>A more intuitive alternative to the other answers:</p>
<p>Shuffle a range of indices, and use that to get a shuffled list of the original values.</p>
| 1 | 2016-10-03T13:56:05Z | [
"python"
] |
python3 12 digits script each digit equal three time beore him? | 39,832,820 | <p>Write a program that displays <strong>12 digits</strong>,</p>
<p>each digit is equal to three times the digit before him.</p>
<p>I tried to code like this </p>
<pre><code>a , b , c = 1 , 1 , 1
print(c)
while c < 12 : # for looping
c = c + 1 # c for counting
b = a+b
y = 3*b
pr... | 0 | 2016-10-03T13:27:44Z | 39,833,305 | <p>You can use <a href="https://docs.python.org/3/reference/expressions.html#the-power-operator" rel="nofollow">power operator</a> for that:</p>
<pre><code>from itertools import islice
def numbers(x, base=3):
n = 0
while True:
yield x * base ** n
n += 1
for n in islice(numbers(1), 12):
pr... | 0 | 2016-10-03T13:50:55Z | [
"python",
"python-3.x"
] |
python3 12 digits script each digit equal three time beore him? | 39,832,820 | <p>Write a program that displays <strong>12 digits</strong>,</p>
<p>each digit is equal to three times the digit before him.</p>
<p>I tried to code like this </p>
<pre><code>a , b , c = 1 , 1 , 1
print(c)
while c < 12 : # for looping
c = c + 1 # c for counting
b = a+b
y = 3*b
pr... | 0 | 2016-10-03T13:27:44Z | 39,834,337 | <p>You can start with a list where first element is the beginning of the multiples:</p>
<p>-- start with 1 or the number you like</p>
<pre><code>multiples = [1]
for i in range(1, 12):
multiples.append(3 * multiples[i - 1])
print(multiples)
</code></pre>
<p>-- Output : [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 196... | 0 | 2016-10-03T14:44:50Z | [
"python",
"python-3.x"
] |
pip show xml shows Null | 39,832,830 | <p>I am using Python 2.7.12,tried</p>
<pre><code>import xml.etree # successfully imported,
</code></pre>
<p>tried</p>
<pre><code>import lxml.etree # successfully imported.
</code></pre>
<p>when i tried to get the version of xml through </p>
<pre><code>pip show xml #Result is Null
pip show lxml show version 3.4.2
... | -1 | 2016-10-03T13:28:04Z | 39,832,906 | <p>Because <a href="https://docs.python.org/2/library/xml.html#module-xml" rel="nofollow"><code>xml</code></a> is a built-in package in Python 2.7. Built-in modules and packages are tied to the Python version; they're usually only upgraded whenever you upgrade your Python version.</p>
<p><code>pip version</code> only ... | 1 | 2016-10-03T13:31:24Z | [
"python",
"xml",
"python-2.7",
"lxml"
] |
Django refresh session to obtain any new messages for user | 39,832,988 | <p>I'm trying to do a simple push protocol for <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/messages/" rel="nofollow">django messages</a>. So in my REST call, I have the following snippet:</p>
<pre><code> storage = get_messages(self.request)
res = dict(messages=[dict(level=item.level, message=ite... | 0 | 2016-10-03T13:35:40Z | 39,899,673 | <p>I have managed to come to an acceptable solution with a couple of caveats.
Using existing message stores (either cookie or session) proved to be either impossible (cookies) or much too ridden with internal method calls & setting / deleting internal members (session).</p>
<p>This solution uses a new message stor... | 0 | 2016-10-06T15:11:42Z | [
"python",
"django",
"django-messages"
] |
Extending a black box python module | 39,833,042 | <p>I have a "blackbox" python module which I would like to extend. The module provides a class <code>class Foo</code> with no <code>__init__</code> function, and a helper function <code>FooMaker</code> which returns objects of type <code>Foo</code>. The usual strategy of extending modules:</p>
<pre><code>class Extende... | 0 | 2016-10-03T13:37:59Z | 39,833,250 | <p>Unless the module does some serious hacking, you can just replace its members. Note that all references and assignment work on the <code>blackbox.</code> names, not local names!</p>
<p>If you want your new class' <code>__init__</code> to be run inside <code>FooMaker</code>, simply inherit and replace <code>Foo</cod... | -1 | 2016-10-03T13:48:09Z | [
"python",
"python-2.7",
"cython"
] |
Extending a black box python module | 39,833,042 | <p>I have a "blackbox" python module which I would like to extend. The module provides a class <code>class Foo</code> with no <code>__init__</code> function, and a helper function <code>FooMaker</code> which returns objects of type <code>Foo</code>. The usual strategy of extending modules:</p>
<pre><code>class Extende... | 0 | 2016-10-03T13:37:59Z | 39,839,163 | <p>It turned out that the <code>Foo</code> class had a setter function, so what eventually worked for me was</p>
<pre><code>class ExtendedFoo(blackbox.Foo):
pass
def ExtendedFooMaker(*args):
_efoo = ExtendedFoo()
_efoo.set(FooMaker(*args).get())
return _efoo
</code></pre>
| 0 | 2016-10-03T19:38:32Z | [
"python",
"python-2.7",
"cython"
] |
Extending a black box python module | 39,833,042 | <p>I have a "blackbox" python module which I would like to extend. The module provides a class <code>class Foo</code> with no <code>__init__</code> function, and a helper function <code>FooMaker</code> which returns objects of type <code>Foo</code>. The usual strategy of extending modules:</p>
<pre><code>class Extende... | 0 | 2016-10-03T13:37:59Z | 39,857,805 | <p>This should do the same as your solution but is a bit shorter:</p>
<pre><code>from blackbox import Foo, FooMaker
class ExtendedFoo(Foo):
def __init__(self, *args, **kwargs):
self.set(FooMaker(*args, **kwargs).get())
</code></pre>
| 1 | 2016-10-04T16:52:13Z | [
"python",
"python-2.7",
"cython"
] |
select data from table where name = list? | 39,833,070 | <p>Let's say I have a table names like this :</p>
<pre><code>cust_id cust_name
1 John
2 Mary
3 Pete
</code></pre>
<p>and I create a list of customers and orders in python like this :</p>
<pre><code>{'Pete','pen','Mary','apple','Pete','pencil','John','shirt','John','watch','Mary','... | -1 | 2016-10-03T13:39:05Z | 39,833,180 | <p>I am assuming all the required columns are already present in your current table say <code>MY_TABLE</code>. Your SQL query should be like:</p>
<pre><code>SELECT id_order, cust_id, orders from MY_TABLE where cust_name IN ('Pete', 'Mary', 'John');
</code></pre>
<p>Columns I am expecting in "MY_TABLE":</p>
<ul>
<li... | 1 | 2016-10-03T13:44:30Z | [
"python",
"mysql"
] |
Python 3 - How to return all rows as a dict using csv? | 39,833,308 | <p>Listed below is my code to read rows and return one row based on the key value (a specific column i.e. player). How do I return the rest of records?</p>
<pre><code>with open('Players.csv', 'rt') as f:
reader = csv.DictReader(f)
for row in reader:
key = row.pop('PLAYER') #this is my key column
... | -2 | 2016-10-03T13:51:09Z | 39,833,377 | <p>you can try to look at<code>row.keys()</code> and <code>row.items()</code></p>
| 0 | 2016-10-03T13:55:00Z | [
"python",
"python-3.x",
"csv"
] |
Return data from struct using Numpy Array | 39,833,373 | <p>I am writing Python C-extensions to a library and wish to return data as an Numpy Array. The library has a function that returns data from a sensor into a C structure. I would like to take the data from that structure and return it as a Numpy Array.</p>
<p>The structure definition in the library:</p>
<pre><code>... | 0 | 2016-10-03T13:54:50Z | 39,833,533 | <p>PyArrayObject, apart from data, have multiple fields:</p>
<pre><code>typedef struct PyArrayObject {
PyObject_HEAD
char *data;
int nd;
npy_intp *dimensions;
npy_intp *strides;
PyObject *base;
PyArray_Descr *descr;
int flags;
PyObject *weakreflist;
} PyArrayObject;
</code></pre>
<... | 0 | 2016-10-03T14:03:50Z | [
"python",
"c",
"arrays",
"numpy",
"python-c-extension"
] |
Dataframe Nested Loop - set_value variable inputs | 39,833,405 | <p>Hoping someone may be able to point me in the right direction as I am new to Python. </p>
<p>I am doing a small project to get to grips with data analysis in Python using some football data. I have two dataframes, one with player information and another with match information (match_df). The match_df has 22 column... | 1 | 2016-10-03T13:56:38Z | 39,834,000 | <p>here is a manipulation you can do, assuming df is the dataframe of match where columns 0 to 2 is the player ID: </p>
<pre><code>df = pd.DataFrame([['c' , 'a', 'b'], ['b', 'c', 'a']])
df
Out[70]:
0 1 2
0 c a b
1 b c a
df_player = pd.DataFrame([['a', 100], ['b', 230], ['c', 200]],columns=['ID', 'skill']... | 0 | 2016-10-03T14:26:38Z | [
"python",
"pandas",
"dataframe"
] |
Alternatively replace chars in the string with the corresponding index | 39,833,473 | <p>How to replace the alternative characters in the string with the corresponding index without iterating? For example:</p>
<pre><code>'abcdefghijklmnopqrstuvwxyz'
</code></pre>
<p>should be returned as:</p>
<pre><code>'a1c3e5g7i9k11m13o15q17s19u21w23y25'
</code></pre>
<p>I have the below code to achieve this. <em>... | 1 | 2016-10-03T14:00:42Z | 39,833,537 | <p>You could use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>, and re-join the characters with <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join()</code></a>; the latter avoids repeated (slow) ... | 2 | 2016-10-03T14:03:59Z | [
"python",
"string",
"list-comprehension"
] |
How to add an initial/default value using Django Filters? | 39,833,494 | <p>How can I add an initial/default value when using <a href="https://github.com/carltongibson/django-filter" rel="nofollow">Django Filters</a>?</p>
<p>For example, something like this <code>initial=False</code></p>
<pre><code>class UserFilter(django_filters.FilterSet):
archive = django_filters.BooleanFilter(init... | 1 | 2016-10-03T14:02:04Z | 39,833,570 | <p>You can try overriding the <code>__init__</code> method of <code>UserFilter</code>:</p>
<pre><code>def __init__(self, *args, **kwargs):
super(UserFilter, self).__init__(*args, **kwargs)
self.form.initial['archive'] = False
</code></pre>
| 1 | 2016-10-03T14:05:36Z | [
"python",
"django"
] |
Use python script in robot framework | 39,833,518 | <p>Please help to understand.</p>
<p>I have script (SplitModule.py) :</p>
<pre><code>from robot.api.deco import keyword
@keyword('Split Function')
def splitfunction(string):
print "atata"
new_list = string.split(",")
return new_list
</code></pre>
<p>And robot framework script test.txt :</p>
<pre><code>... | -1 | 2016-10-03T14:03:16Z | 39,836,092 | <p>Read what the error message is telling you:</p>
<blockquote>
<p>No keyword with name 'Split Function ${services}' found. </p>
</blockquote>
<p>It thinks the test is trying to call the keyword <code>Split Function ${services}</code>. You don't have a keyword with that name. What you <em>do</em> have is a keyword ... | 0 | 2016-10-03T16:20:07Z | [
"python",
"robotframework"
] |
How to save the edited .csv file in python | 39,833,520 | <p>I have sensor readings stored in csv files and now I am adding some more values to these files. How can I save these files in new locations in csv format for future use. </p>
| 0 | 2016-10-03T14:03:18Z | 39,833,594 | <p>Take a look at this guide: <a href="http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python/" rel="nofollow">http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python/</a></p>
<p>Basically the <a href="https://docs.python.org/3.3/library/csv.html" rel="nofollo... | 0 | 2016-10-03T14:06:41Z | [
"python",
"csv"
] |
Django test discovery fails | 39,833,731 | <p>I have a bunch of apps, all are inside a <code>apps</code> folder.
I'm adding some tests to my project.
It works well, the models / templates / static discovery works super well.
Now I would like to add some tests to my projects, so I created a <code>tests.py</code> file inside my app. When I want to run the test (<... | 0 | 2016-10-03T14:13:29Z | 39,848,161 | <p>I installed <code>django-nose</code> and run it with the option <code>--where apps</code></p>
| 0 | 2016-10-04T08:58:52Z | [
"python",
"django",
"testing",
"discover"
] |
pass several parameters in Django rest Framework | 39,833,747 | <p>I am new with <code>Django</code> and <code>Django rest framework</code>, I try to create several routes to get the data from the database.</p>
<p>Right now in my <code>urls.py</code> file I have this</p>
<pre><code>router = routers.DefaultRouter()
router.register(r'cpuProjects', cpuProjectsViewSet, base_name='cp... | 1 | 2016-10-03T14:14:20Z | 39,833,934 | <p>The routers framework isn't meant to be used with several parameters .. you can manually do it with primary keys (in the regular expressions).</p>
| 0 | 2016-10-03T14:23:20Z | [
"python",
"django",
"django-rest-framework"
] |
pass several parameters in Django rest Framework | 39,833,747 | <p>I am new with <code>Django</code> and <code>Django rest framework</code>, I try to create several routes to get the data from the database.</p>
<p>Right now in my <code>urls.py</code> file I have this</p>
<pre><code>router = routers.DefaultRouter()
router.register(r'cpuProjects', cpuProjectsViewSet, base_name='cp... | 1 | 2016-10-03T14:14:20Z | 39,863,393 | <p>This is somewhat similar to what we did in our earlier <a href="http://stackoverflow.com/questions/39729388/using-django-rest-framework-to-return-info-by-name/39736838#39736838">Q&A</a></p>
<pre><code>from rest_framework.decorators import detail_route, list_route
@detail_route(url_path='(?P<slug>[\w-]+)/(... | 1 | 2016-10-04T23:47:03Z | [
"python",
"django",
"django-rest-framework"
] |
Python Gtk3 create cell of treeview with a color field | 39,833,792 | <p>I want to fill a cell of a treeview with a color field and searching for a good method to do this.</p>
<p>Here is what I have tried already:</p>
<pre><code>#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk, GdkPixbu... | 0 | 2016-10-03T14:16:32Z | 39,835,802 | <p><strong>Solution</strong></p>
<p>Finally I got it working now:</p>
<pre><code>#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GdkPixbuf
window = Gtk.Window()
window.set_default_size(300, 100)
window.connect("delete-e... | 0 | 2016-10-03T16:03:03Z | [
"python",
"gtk3"
] |
QSpacerItem crashes pyQT when instantiated twice | 39,833,793 | <p>I've been hunting a nasty crash-upon-exit bug in my pyQt Application <a href="https://github.com/chipmuenk/pyfda" rel="nofollow">https://github.com/chipmuenk/pyfda</a> for more than a year now and have just found it by chance: The following code snippet</p>
<pre><code> self.cmbResponseType = QtGui.QComboBox(self... | 1 | 2016-10-03T14:16:38Z | 39,836,017 | <p>This looks like a typical case of the Python garbage-collector deleting objects in an order that Qt is not expecting. It's possible that adding a spacer multiple times to the same layout may result in Qt trying to delete it twice, or delete it when it's no longer there. With the obvious solution being simply: don't ... | 1 | 2016-10-03T16:16:33Z | [
"python",
"user-interface",
"crash",
"pyqt"
] |
OpenCV NoneType object has no attribute shape | 39,833,796 | <p>Hello I'm working on Raspberry Pi with OpenCV. I want to try a tutorial which is ball tracking in link
<a href="http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/" rel="nofollow">http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/</a></p>
<p>But when I compile it, i get an error: 'Non... | -2 | 2016-10-03T14:16:43Z | 39,834,344 | <p>It means that somewhere a function which should return a image just returned None and therefore has no shape attribute. Try
"print img"
to check if your image is None or an actual numpy object.</p>
| 0 | 2016-10-03T14:45:10Z | [
"python",
"opencv",
"raspberry-pi2"
] |
how do I prevent my list items from being broken up into individual strings when writing to CSV? | 39,833,801 | <p>When writing to my CSV my list item gets broken up into individual strings even though I am using the append function. I think the problem is in how I am using <em>writerow</em>, but I'm not quite sure.</p>
<p>This is my code.</p>
<pre><code>twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
... | 0 | 2016-10-03T14:16:53Z | 39,833,890 | <p><code>writerow</code> expects an <em>iterable</em>, and once it gets a string, each character in the string gets <em>splitted</em> as separate columns.</p>
<p>To write the entire list as a single row in to the csv, you won't need the second <em>for</em> loop:</p>
<pre><code>for tweet in user_timeline:
tweet_l... | 0 | 2016-10-03T14:21:37Z | [
"python",
"csv",
"twitter",
"twython"
] |
How to count values in a list Python 3 | 39,833,902 | <p>I have code like this:</p>
<pre><code>winners = [red, blue, yellow]
player_1_guesses = [red, green, orange]
player_2_guesses = [red, blue, orange]
player_3_guess = [red, green, yellow]
</code></pre>
<p>I'd like to count how many times each value in <code>winners</code> appears across the three <code>player_x_gues... | 0 | 2016-10-03T14:22:13Z | 39,833,975 | <p>Try doing this:</p>
<pre><code>all_guesses = player_1_guess + player_2_guess + player_3_guess
dct = {i:all_guesses.count(i) for i in winners}
</code></pre>
<p>output:</p>
<pre><code>{'blue': 1, 'yellow': 1, 'red': 3}
</code></pre>
<p>Using <code>collections</code>:</p>
<pre><code>from collections import Counter... | 5 | 2016-10-03T14:25:35Z | [
"python",
"list",
"dictionary",
"counting"
] |
How to count values in a list Python 3 | 39,833,902 | <p>I have code like this:</p>
<pre><code>winners = [red, blue, yellow]
player_1_guesses = [red, green, orange]
player_2_guesses = [red, blue, orange]
player_3_guess = [red, green, yellow]
</code></pre>
<p>I'd like to count how many times each value in <code>winners</code> appears across the three <code>player_x_gues... | 0 | 2016-10-03T14:22:13Z | 39,834,552 | <p>Not sure if I'm breaking the rules here, but my approach was to search for
"python compare string arrays" and I got this: <a href="http://stackoverflow.com/questions/2783969/compare-string-with-all-values-in-array">Compare string with all values in array</a></p>
<p>You have one list/array of strings that you want t... | 0 | 2016-10-03T14:56:34Z | [
"python",
"list",
"dictionary",
"counting"
] |
How to describe scopes in EBNF? | 39,833,913 | <p>I'm trying to write a parser for Cisco IOS and ASA configurations, using Grako and Python. I'm trying to figure out how to represent 'scoped' keywords in EBNF - for example, the 'description' keyword must appear inside an <code>interface</code> scope, but there are multiple options for <code>interface</code> and the... | 0 | 2016-10-03T14:22:30Z | 39,852,149 | <p>A trick I use in these situations is to use repetition even if the options can appear only once:</p>
<pre><code>interface_options
=
{ @+:(if_name | sec_level | if_addr | if_bridgegroup) NEWLINE}*
;
</code></pre>
<p>If necessary, you can use a semantic action to validate that options are not repeated.<... | 1 | 2016-10-04T12:18:55Z | [
"python",
"ebnf",
"cisco-ios",
"grako",
"ciscoconfparse"
] |
Add items in nested dictionaries based on ID number in python | 39,833,927 | <p>I have dictionaries nested in a list. The dictionaries are set up as follows:</p>
<p><code>{'ID': 123, 'Balance': 45, 'Comments': None}</code></p>
<p>I have multiple of these dictionaries in a list, so the list looks like this:</p>
<pre><code>[{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 7... | 0 | 2016-10-03T14:22:59Z | 39,833,999 | <p>What I'm hearing here is "how do I get an item from a list, given that I know some unique key value about it?". How much are you committed to keeping the current data structure? I'm inclined to dispense with the list entirely and use a dict-of-dicts.</p>
<pre><code>d = {
123: {'Balance': 45, 'Comments': None}
... | 0 | 2016-10-03T14:26:37Z | [
"python",
"list",
"dictionary",
"nested"
] |
Add items in nested dictionaries based on ID number in python | 39,833,927 | <p>I have dictionaries nested in a list. The dictionaries are set up as follows:</p>
<p><code>{'ID': 123, 'Balance': 45, 'Comments': None}</code></p>
<p>I have multiple of these dictionaries in a list, so the list looks like this:</p>
<pre><code>[{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 7... | 0 | 2016-10-03T14:22:59Z | 39,834,023 | <pre><code>data = [{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 78, 'Comments': None}]
any( inputData == item['ID'] for item in data )
inputData = 123
True
</code></pre>
| 0 | 2016-10-03T14:28:05Z | [
"python",
"list",
"dictionary",
"nested"
] |
Add items in nested dictionaries based on ID number in python | 39,833,927 | <p>I have dictionaries nested in a list. The dictionaries are set up as follows:</p>
<p><code>{'ID': 123, 'Balance': 45, 'Comments': None}</code></p>
<p>I have multiple of these dictionaries in a list, so the list looks like this:</p>
<pre><code>[{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 7... | 0 | 2016-10-03T14:22:59Z | 39,834,026 | <p>Iterate over the list, check that whether there is match with the <code>ID</code>, if yes, add the value to the existing value of <code>BALANCE</code> of that dict. Below is the sample code:</p>
<pre><code>>>> my_dict_list = [{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 78, 'Comment... | 0 | 2016-10-03T14:28:13Z | [
"python",
"list",
"dictionary",
"nested"
] |
Add items in nested dictionaries based on ID number in python | 39,833,927 | <p>I have dictionaries nested in a list. The dictionaries are set up as follows:</p>
<p><code>{'ID': 123, 'Balance': 45, 'Comments': None}</code></p>
<p>I have multiple of these dictionaries in a list, so the list looks like this:</p>
<pre><code>[{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 7... | 0 | 2016-10-03T14:22:59Z | 39,834,676 | <pre><code>accounts = [
{'ID': 123, 'Balance': 45, 'Comments': None},
{'ID': 456, 'Balance': 78, 'Comments': None},
]
def update_balance(account_id, amount):
account = next((a for a in accounts if a['ID'] == account_id), None)
if account:
account['Balance'] += amount
return account
ac... | 0 | 2016-10-03T15:03:01Z | [
"python",
"list",
"dictionary",
"nested"
] |
How does the automatic Ansible documentation work? | 39,834,013 | <p>So this is my situation:
I am writing Ansible playbooks and roles in a huge project directory. Currently my documentation is stored in .md files. But I want to use Ansible's documentation mechanism, so I looked into the sphinx documentation system. It seems pretty neat to me, so I installed it and got into the mecha... | 1 | 2016-10-03T14:27:24Z | 39,835,639 | <p>Auto doc is only for Ansible modules, not playbooks.<br>
If you want to document your playbooks, you are on your own.<br>
There is a small project on github: <a href="https://github.com/starboarder2001/ansible-docgen" rel="nofollow">ansible-docgen</a> â it fetches a list of tasks into MD files and adds a couple of... | 0 | 2016-10-03T15:54:20Z | [
"python",
"documentation",
"ansible",
"yaml",
"python-sphinx"
] |
Insert dictionary into SQLlite3 | 39,834,047 | <p>I want to insert data from a dictionary into a sqlite table, I am using slqalchemy to do that, the keys in the dictionary and the column names are the same, and I want to insert the values into the same column name in the table. So this is my code:</p>
<pre><code>#This is the class where I create a table from with ... | 0 | 2016-10-03T14:28:59Z | 39,837,714 | <p>Yes, it's possible (though aren't you missing primary keys/foreign keys on this table?).</p>
<pre><code>session.add(Sizecurve(**o))
session.commit()
</code></pre>
<p>That should insert the row.</p>
<p><a href="http://docs.sqlalchemy.org/en/latest/core/tutorial.html#executing-multiple-statements" rel="nofollow">ht... | 0 | 2016-10-03T18:02:45Z | [
"python",
"sqlite",
"dictionary",
"sqlalchemy"
] |
Insert dictionary into SQLlite3 | 39,834,047 | <p>I want to insert data from a dictionary into a sqlite table, I am using slqalchemy to do that, the keys in the dictionary and the column names are the same, and I want to insert the values into the same column name in the table. So this is my code:</p>
<pre><code>#This is the class where I create a table from with ... | 0 | 2016-10-03T14:28:59Z | 39,855,876 | <p>I have found this answer to a similar question, though this is about reading the data from a json file, so now I am working on understanding the code and also changing my data type to json so that I can insert them in the right place.
<a href="http://stackoverflow.com/questions/8811783/convert-json-to-sqlite-in-pyth... | -1 | 2016-10-04T15:09:34Z | [
"python",
"sqlite",
"dictionary",
"sqlalchemy"
] |
guessing numbers from 1 to 8 | 39,834,132 | <p>My program needs to guess the user's number (from 1 to 8) by only asking 3 questions. It prints the first two questions correctly but then when I press enter for the third question, it just prints the last input I did.
How to make all inputs (yes or no) lower case? </p>
<pre><code># Simple Expert System
#firstQuest... | 0 | 2016-10-03T14:33:22Z | 39,834,335 | <p>Indeed your program can't go further than the second question,</p>
<pre><code>if firstQuestion == "yes":
print(raw_input(secondQuestion))
elif firstQuestion == "no":
print(raw_input(thirdQuestion))
</code></pre>
<p>whether I answer yes or no to the first question, the code will go in one of those two cases... | 0 | 2016-10-03T14:44:47Z | [
"python",
"python-2.7",
"python-3.x",
"if-statement"
] |
guessing numbers from 1 to 8 | 39,834,132 | <p>My program needs to guess the user's number (from 1 to 8) by only asking 3 questions. It prints the first two questions correctly but then when I press enter for the third question, it just prints the last input I did.
How to make all inputs (yes or no) lower case? </p>
<pre><code># Simple Expert System
#firstQuest... | 0 | 2016-10-03T14:33:22Z | 39,834,361 | <p>First you ask for the input on the first question. This puts the answer into the firstQuestion variable. Then you go into the if-section. There you ask for the raw_input for another question and then you tell the program to print that value. At that point one the elif's has been succesfull and the others are skipped... | 0 | 2016-10-03T14:46:05Z | [
"python",
"python-2.7",
"python-3.x",
"if-statement"
] |
guessing numbers from 1 to 8 | 39,834,132 | <p>My program needs to guess the user's number (from 1 to 8) by only asking 3 questions. It prints the first two questions correctly but then when I press enter for the third question, it just prints the last input I did.
How to make all inputs (yes or no) lower case? </p>
<pre><code># Simple Expert System
#firstQuest... | 0 | 2016-10-03T14:33:22Z | 39,834,453 | <p>Can you provide the input you used?</p>
<p>It isn't needed though, as I think improving the structure of this program would help answer your question.</p>
<p>For instance, notice how you write:</p>
<pre><code>firstQuestion = (raw_input("Is it an even number? "))
secondQuestion = "Is it less than or equal to 4? "
... | 0 | 2016-10-03T14:50:30Z | [
"python",
"python-2.7",
"python-3.x",
"if-statement"
] |
guessing numbers from 1 to 8 | 39,834,132 | <p>My program needs to guess the user's number (from 1 to 8) by only asking 3 questions. It prints the first two questions correctly but then when I press enter for the third question, it just prints the last input I did.
How to make all inputs (yes or no) lower case? </p>
<pre><code># Simple Expert System
#firstQuest... | 0 | 2016-10-03T14:33:22Z | 39,834,491 | <p>Consider that your program doesn't scale well at all for larger numbers: if you have to guess a number between 1 and 1000, you're going to have to write a lot of code.</p>
<p>Instead, consider looping through all the ranges that you might get:</p>
<pre><code>lower_limit = 1
upper_limit = 100
while lower_limit <... | 6 | 2016-10-03T14:52:42Z | [
"python",
"python-2.7",
"python-3.x",
"if-statement"
] |
guessing numbers from 1 to 8 | 39,834,132 | <p>My program needs to guess the user's number (from 1 to 8) by only asking 3 questions. It prints the first two questions correctly but then when I press enter for the third question, it just prints the last input I did.
How to make all inputs (yes or no) lower case? </p>
<pre><code># Simple Expert System
#firstQuest... | 0 | 2016-10-03T14:33:22Z | 39,834,530 | <p>What you've got there doesn't actually use the input from any of the questions except the first. For example:</p>
<pre><code>secondQuestion = "Is it less than or equal to 4? "
# other stuff
elif secondQuestion == "yes": # will never be true
</code></pre>
<p>Calling <code>raw_input(secondQuestion)</code> doesn't ch... | 0 | 2016-10-03T14:55:05Z | [
"python",
"python-2.7",
"python-3.x",
"if-statement"
] |
convert python operations to numpy | 39,834,321 | <p>I wrote a basic code which accepts two point coordinates, derives the eqaution of the line passing through it and of the perpendicular, then outputs two points which are the edges of the same perpendicular line. My aim is to do something like what is shown in the pictures of <a href="http://gis.stackexchange.com/que... | 1 | 2016-10-03T14:43:55Z | 39,841,573 | <p>1) Yes, numpy would increase the performance a lot. Instead of doing a loop in python, you have it in C using the vectorization of numpy.</p>
<p>2) ideas:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
# get random coords
npts = 10
distance_factor = 0.05
points = (np.sort(np.random.random(2*npt... | 1 | 2016-10-03T22:44:15Z | [
"python",
"python-2.7",
"numpy",
"coordinates"
] |
scipy.signal.spectrogram output not as expected | 39,834,345 | <p>I am using <code>scipy.signal.spectrogram()</code> for analysing a dataset containing values for a current. My input to the function is as follows:</p>
<pre><code>f, t, Sxx = signal.spectrogram(y, fs)
</code></pre>
<p>(for plotting in subplot 3 (from the top) I use <code>plt.pcolormesh(t, f, Sxx)</code>)</p>
<p>W... | 0 | 2016-10-03T14:45:16Z | 39,877,490 | <p>I wrote some code to explain my comments above about the sizes of the data:</p>
<pre><code>#!/usr/bin/env python
import numpy as np
import scipy.signal
from scipy.signal import spectrogram
WINDOW_LEN = 256
OVERLAP_LEN = WINDOW_LEN / 8
DATA_LEN = 10002
DURATION = 2.0001997
fs = (DATA_LEN - 1) / DURATION
eps = 1/(... | 0 | 2016-10-05T15:00:14Z | [
"python",
"scipy",
"signal-processing",
"fft",
"spectrogram"
] |
Flask-restful app fails when authentication is enabled | 39,834,436 | <p>I'm getting this error whenever I try and enable authentication using flask_httpauth for my flask_restful project:</p>
<pre><code>AttributeError: 'function' object has no attribute 'as_view'
</code></pre>
<p>Here's a very basic example:
apicontroller.py:</p>
<pre><code>from flask_restful import Resource, Api
from... | 0 | 2016-10-03T14:49:49Z | 39,834,643 | <p>I believe that you cannot not apply decorators to class.</p>
<p>To solve that:</p>
<pre><code>from flask_restful import Resource, Api
from flasktest import api, app
from flask_httpauth import HTTPTokenAuth
auth = HTTPTokenAuth()
class ApiController(Resource):
decorators = [auth.login_required]
def get(... | 2 | 2016-10-03T15:01:00Z | [
"python",
"flask-restful",
"flask-httpauth"
] |
Updating matplotlib plot during code execution | 39,834,523 | <p>I have found that the latest update to python/matplotlib has broken a crucial feature, namely, the ability to regularly update or "refresh" a matplotlib plot during code execution. Below is a minimally (non-)working example.</p>
<pre><code>import numpy as np
from matplotlib.pyplot import *
from time import sleep
x... | 3 | 2016-10-03T14:54:40Z | 39,839,489 | <p>That is interesting. I'm used to draw interactive plots a little bit differently: </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from time import sleep
x = np.array([0])
y = np.array([0])
plt.ion()
fig = plt.figure()
ax=fig.add_subplot(111)
ax.set_xlim([0,50])
ax.set_ylim([0,2500])
line, = ax... | 0 | 2016-10-03T20:00:59Z | [
"python",
"matplotlib",
"plot"
] |
Function for Iteration over tuples | 39,834,536 | <p>I have the following problem:
I want to iterate over a given list and return the minimum of the sum of all possible cartesian products:</p>
<pre><code>from itertools import product
z = ((1, 2),(2, 3))
def zmin(tup):
return min(sum(a*a for a in s) for s in product(tup))
zmin(z) --> ERROR MESSAGE
</code></p... | 0 | 2016-10-03T14:55:38Z | 39,836,330 | <p>I found an soloution myself:
I added <code>*args</code> for return value:</p>
<pre><code>def zmin(tup):
return min(sum(a*a for a in s) for s in product(*tup))
</code></pre>
| 0 | 2016-10-03T16:35:29Z | [
"python",
"tuples",
"itertools"
] |
Appending a Path to a Path | 39,834,556 | <p>Is it possible to append a <code>pathlib.Path</code> generator or, combine two <code>Path</code>s?</p>
<pre><code>from pathlib import Path
paths = Path('folder_with_pdfs').glob('**/*.pdf')
paths.append(Path('folder_with_xlss').glob('**/*.xls'))
</code></pre>
<p>With this attempt you'll get:</p>
<pre><code>Attribu... | 0 | 2016-10-03T14:56:44Z | 39,834,727 | <p>That's because <a href="https://docs.python.org/3.5/library/pathlib.html#pathlib.Path.glob" rel="nofollow"><code>Path.glob</code></a> returns a <code>generator</code>, i.e an object that returns values when <code>next</code> is called which has absolutely no idea what <code>append</code>ing is.</p>
<p>You have two ... | 1 | 2016-10-03T15:05:36Z | [
"python",
"python-3.x",
"pathlib"
] |
TypeError: coercing to Unicode: need string or buffer, int found ( Str method doesn't work ) | 39,834,604 | <p>i am trying to conclude the unfinished module, but i'm having major problem which i can't find fix for, Also note, that i am doing this in Python2. Full code is <a href="https://github.com/GTB3NW/SteamTradingServices/blob/master/Exchange/exchange.py" rel="nofollow">here</a>.</p>
<p>When the code was executed, the f... | 1 | 2016-10-03T14:59:26Z | 39,835,744 | <p>The <em>coercing</em> error happens when trying so do an operation with a unicode and something which cannot be automatically converted to unicode.</p>
<p>For example:</p>
<pre><code>>>> u'something' + 11
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: coerc... | 2 | 2016-10-03T15:59:47Z | [
"python",
"python-2.7",
"unicode"
] |
Ansible VM:TypeError: __init__() takes at least 3 arguments (2 given) | 39,834,641 | <p>I'm learning about virtual machine and others, I'm trying to configure a VM(with Ansible and DigitalOcean API V2)that needs a file.py to the full correct configuration of this machine (according to the book that I'm studying), but when I try use the command <strong>python do_api_v1.py</strong> the output says:</p>
... | 0 | 2016-10-03T15:00:54Z | 39,834,764 | <p>You are not passing enough arguments to <a href="https://github.com/Wiredcraft/dopy/blob/8b7bcbc85ef27ec4ae2fb46eae9bac827c4c3df0/dopy/manager.py#L47" rel="nofollow"><code>DoManager</code></a> as the error message says. You need to pass an obligatory <code>client_id</code> as the first argument, and an <code>api_key... | 0 | 2016-10-03T15:07:32Z | [
"python",
"virtual-machine",
"ansible"
] |
Ansible VM:TypeError: __init__() takes at least 3 arguments (2 given) | 39,834,641 | <p>I'm learning about virtual machine and others, I'm trying to configure a VM(with Ansible and DigitalOcean API V2)that needs a file.py to the full correct configuration of this machine (according to the book that I'm studying), but when I try use the command <strong>python do_api_v1.py</strong> the output says:</p>
... | 0 | 2016-10-03T15:00:54Z | 39,834,767 | <p>DoManager requires more arguments. </p>
<p>From the <a href="https://pypi.python.org/pypi/dopy" rel="nofollow">docs</a>:</p>
<p>For V1 of the API:</p>
<pre><code># export DO_CLIENT_ID='client_id'
# export DO_API_KEY='long_api_key'
>>> from dopy.manager import DoManager
>>> do = DoManager('client... | 0 | 2016-10-03T15:07:40Z | [
"python",
"virtual-machine",
"ansible"
] |
Using Django outside of view.py | 39,834,690 | <p>I have a twisted based script running that is managing IO, monitoring serial inputs, writing logs etc. It uses Twisted to run events every minute and every hour as well as interrupt on serial traffic.</p>
<p>Can Django be used to provide an interface for this, for example taking live values and display them using <... | -1 | 2016-10-03T15:03:31Z | 39,834,798 | <p>Why do you need Django for such a simple use case?
For simple Http requests you can you the included Python tool:</p>
<p><a href="https://docs.python.org/2/library/simplehttpserver.html" rel="nofollow">https://docs.python.org/2/library/simplehttpserver.html</a></p>
| 0 | 2016-10-03T15:09:45Z | [
"python",
"django",
"twisted"
] |
Flask can't redirect me to home page, it just gives me the html code as response | 39,834,722 | <p>I'm building a login with flask and flask-login, and the authentication works perfectly. When a user is authenticated, he should be automatically redirected to the home page (which is unavailable for a not-logged user). The issue is that <code>flask.redirect</code> function just returns me the html code of the home ... | 0 | 2016-10-03T15:05:15Z | 39,860,813 | <p>If I look at your screen copy, you have something like this:</p>
<pre><code>"POST /login HTTP/1.1" 302 -
"POST /home HTTP/1.1" 200 -
</code></pre>
<p><em>note:</em> you can have exit code 302 or 307, which is approximately the same: a redirection.</p>
<p>So, the redirection from <code>/login</code> to <code>/hom... | 0 | 2016-10-04T20:01:13Z | [
"python",
"flask"
] |
Read lines from text as a list in Python | 39,834,839 | <p>I am read data from text file. Every line of my data have the following structure </p>
<pre><code>(110, 'Math', 1, 5)
(110, 'Sports', 1, 5)
(110, 'Geography', 4, 10)
(112, 'History', 1, 9)
....
</code></pre>
<p>and when I am reading the data from the file it is parsed as a string. So for all the lines I parse th... | 1 | 2016-10-03T15:11:34Z | 39,834,931 | <p>Assuming that the format is always as you described (i.e. corresponds to the Python tuple syntax), this is easily done with <a href="https://docs.python.org/3.5/library/ast.html#ast.literal_eval"><code>ast.literal_eval()</code></a>:</p>
<pre><code>>>> ast.literal_eval("(110, 'Math', 1, 5)")
(110, 'Math', 1... | 5 | 2016-10-03T15:16:30Z | [
"python"
] |
Read lines from text as a list in Python | 39,834,839 | <p>I am read data from text file. Every line of my data have the following structure </p>
<pre><code>(110, 'Math', 1, 5)
(110, 'Sports', 1, 5)
(110, 'Geography', 4, 10)
(112, 'History', 1, 9)
....
</code></pre>
<p>and when I am reading the data from the file it is parsed as a string. So for all the lines I parse th... | 1 | 2016-10-03T15:11:34Z | 39,834,937 | <p>Do as follow :</p>
<pre><code>data1 = [line.strip(')').strip('(').split() for line in open("data.txt", 'r')]
</code></pre>
| 1 | 2016-10-03T15:16:43Z | [
"python"
] |
Python .pyd equivalent on linux | 39,834,856 | <p>I have some c++ code that is working as a python module using boost.
It is actually a plugin of another c++ python module.</p>
<p>On windows, I have to link against a <code>libavg.pyd</code> file of this library.</p>
<p>On linux I tried linking against <code>libavg.so</code>, but when doing that, dlopen fails with... | 0 | 2016-10-03T15:12:33Z | 39,835,809 | <p>On linux .pyd equivalent is .so files.</p>
<p>I'm not know about Boost::Python specifics, but you can try to use script like this:</p>
<pre><code>from distutils.core import setup, Extension
module = Extension('ModuleName', sources=['yourmodule.cpp'], language="c++")
setup(name="ModuleName",
version='1.0',
... | 1 | 2016-10-03T16:03:23Z | [
"python",
"c++",
"linux",
"python-2.7"
] |
Sublime Text: Add character in column position | 39,834,861 | <p>I have a Python file with a few hundred lines of code. The longest line is 146 characters. How would I put <code>#</code> in column 200 down the whole file within Sublime Text? Preferably with one or two Sublime Text commands?</p>
<p><code>1 200</code></p... | -2 | 2016-10-03T15:12:35Z | 39,835,077 | <p>You can try something like this. Note that this writes to a new file: let me know if you want me to modify so that it overwrites the existing file:</p>
<pre><code>data = []
with open('data.txt', 'r') as f:
data = [line[:-1] + ' ' * (200 - len(line)) + '#\n' for line in f]
with open('new_data.txt', 'w') as f:
f... | 1 | 2016-10-03T15:23:17Z | [
"python",
"comments",
"sublimetext2",
"sublimetext3"
] |
Sublime Text: Add character in column position | 39,834,861 | <p>I have a Python file with a few hundred lines of code. The longest line is 146 characters. How would I put <code>#</code> in column 200 down the whole file within Sublime Text? Preferably with one or two Sublime Text commands?</p>
<p><code>1 200</code></p... | -2 | 2016-10-03T15:12:35Z | 39,835,417 | <p>Here's a possible solution:</p>
<pre><code>N = 200
output = [l.rstrip() for l in f]
output = ["{0}#{1}".format(
l[:len(l[:N])] + ' ' * (N - len(l[:N])), l[N:]) for l in output]
print("\n".join(output))
</code></pre>
<p>Or written differently:</p>
<pre><code>N = 200
output = []
for l in f:
l = l.rstrip()
... | 0 | 2016-10-03T15:41:54Z | [
"python",
"comments",
"sublimetext2",
"sublimetext3"
] |
Running twisted reactor in iPython | 39,834,949 | <p>I'm aware this is normally done with twistd, but I'm wanting to use iPython to test out code 'live' on twisted code.</p>
<p><a href="http://stackoverflow.com/questions/4673375/how-to-start-twisteds-reactor-from-ipython">How to start twisted's reactor from ipython</a> asked basically the same thing but the first... | 0 | 2016-10-03T15:17:16Z | 39,841,749 | <p>While this doesn't answer the question I thought I had, it does answer (sort of) the question I posted. Embedding ipython works in the sense that you get access to business objects with the reactor running.</p>
<pre><code>from twisted.internet import reactor
from twisted.internet.endpoints import serverFromString
f... | 0 | 2016-10-03T23:04:46Z | [
"python",
"ipython",
"twisted"
] |
Running twisted reactor in iPython | 39,834,949 | <p>I'm aware this is normally done with twistd, but I'm wanting to use iPython to test out code 'live' on twisted code.</p>
<p><a href="http://stackoverflow.com/questions/4673375/how-to-start-twisteds-reactor-from-ipython">How to start twisted's reactor from ipython</a> asked basically the same thing but the first... | 0 | 2016-10-03T15:17:16Z | 39,843,043 | <p>Async code in general can be troublesome to run in a live interpreter. It's best just to run an async script in the background and do your iPython stuff in a separate interpreter. You can intercommunicate using files or TCP. If this went over your head, that's because it's not always simple and it might be best to a... | 0 | 2016-10-04T01:52:00Z | [
"python",
"ipython",
"twisted"
] |
Adding row to dataframe | 39,834,999 | <p>Suppose I am trying add rows to a dataframe with 40 columns. Ordinarily it would be something like this:</p>
<pre><code>df = pandas.DataFrame(columns = 'row1', 'row2', ... ,'row40'))
df.loc[0] = [value1, value2, ..., value40]
</code></pre>
<p>(don't take the dots literally)</p>
<p>However let's say value1 to val... | 1 | 2016-10-03T15:19:35Z | 39,835,057 | <p>I think you need:</p>
<pre><code>df.loc[0] = list1 + [value11, value12, ..., value40]
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame(columns = ['row1', 'row2','row3', 'row4','row5', 'row6','row40'])
list1 = ['a','b','c']
df.loc[0] = list1 + ['d','e','f', 'g']
print (df)
row1 row2 row3 row4 row5 row... | 2 | 2016-10-03T15:22:06Z | [
"python",
"list",
"pandas",
"append",
"multiple-columns"
] |
IOError: [Errno socket error] using BeautifulSoup | 39,835,010 | <p>I am trying to get the data from US Census website using beautiful soup with Python 2.7. This is the code that I use:</p>
<pre><code>import urllib
from bs4 import BeautifulSoup
url = "https://www.census.gov/quickfacts/table/PST045215/01"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
</code></pre>
<... | 1 | 2016-10-03T15:19:59Z | 39,835,375 | <p>One workaround to this problem would be to switch to <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
url = "https://www.census.gov/quickfacts/table/PST045215/01"
response = requests.get(url)
soup = Beautiful... | 2 | 2016-10-03T15:39:49Z | [
"python",
"beautifulsoup"
] |
Pandas random sample with remove | 39,835,021 | <p>I'm aware of <code>DataFrame.sample()</code>, but how can I do this and also remove the sample from the dataset? (<em>Note: AFAIK this has nothing to do with sampling with replacement</em>)</p>
<p>For example here is <strong>the essence</strong> of what I want to achieve, this does not actually work:</p>
<pre><cod... | 2 | 2016-10-03T15:20:13Z | 39,835,095 | <p>If your index is unique</p>
<pre><code>df = df.drop(df_subset.index)
</code></pre>
<hr>
<p><strong><em>example</em></strong></p>
<pre><code>df = pd.DataFrame(np.arange(10).reshape(-1, 2))
</code></pre>
<hr>
<p><strong><em>sample</em></strong></p>
<pre><code>df_subset = df.sample(2)
df_subset
</code></pre>
<p... | 2 | 2016-10-03T15:24:00Z | [
"python",
"pandas"
] |
Pandas random sample with remove | 39,835,021 | <p>I'm aware of <code>DataFrame.sample()</code>, but how can I do this and also remove the sample from the dataset? (<em>Note: AFAIK this has nothing to do with sampling with replacement</em>)</p>
<p>For example here is <strong>the essence</strong> of what I want to achieve, this does not actually work:</p>
<pre><cod... | 2 | 2016-10-03T15:20:13Z | 39,835,133 | <p>pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="nofollow">random sample</a> : </p>
<pre><code>train=df.sample(frac=0.8,random_state=200)
test=df.drop(train.index)
</code></pre>
| 1 | 2016-10-03T15:26:00Z | [
"python",
"pandas"
] |
Find linear part and slope in curve | 39,835,069 | <p>For a device that monitors the mass change in function of time, we would like to calculate the slope of the linear part of the data.</p>
<p>The example shown below is produced by reading a dataframe produced by the device.</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
#Find DataFrame
df = pd.... | 1 | 2016-10-03T15:22:52Z | 39,835,435 | <p>Use <strong>numpy.polyfit()</strong> :</p>
<pre><code>df_sampled = df[:max_value] #select the points you want to keep
m, p = numpy.polyfit(df_sampled.index, df_sampled, deg=1)
</code></pre>
<p>The function returns the <strong>slope</strong> and the <strong>intercept</strong> of your linear regression.</p>
| 1 | 2016-10-03T15:42:50Z | [
"python",
"pandas",
"plot",
"dataframe"
] |
What is the right way to switch between many choices in Python | 39,835,176 | <p>I want to write something like a AI in Python:</p>
<ol>
<li><p>My first code is like this:</p>
<pre><code>def run()
if choice_a_is_avilable:
choice_a()
return
elif choice_b_is_avilable:
if choice_b_1_is_avilable:
choice_b_1()
return
elif choice_b_2_is... | 2 | 2016-10-03T15:28:32Z | 39,835,314 | <p>If your <code>choice_</code> functions are returning <code>True</code> if successful, <code>False</code> if unsuccessful, then you can try each in turn until one is successful with simply:</p>
<pre><code>choice_a() or choice_b() or choice_c()
</code></pre>
<p>Because <code>or</code> is short-circuited, the express... | 0 | 2016-10-03T15:36:29Z | [
"python"
] |
What is the right way to switch between many choices in Python | 39,835,176 | <p>I want to write something like a AI in Python:</p>
<ol>
<li><p>My first code is like this:</p>
<pre><code>def run()
if choice_a_is_avilable:
choice_a()
return
elif choice_b_is_avilable:
if choice_b_1_is_avilable:
choice_b_1()
return
elif choice_b_2_is... | 2 | 2016-10-03T15:28:32Z | 39,835,316 | <p>There is nothing "wrong" in your exception method if this is what you want to do. To me it looks a bit static, though. </p>
<p>Not exactly knowing your problem, one alternative to consider is having a list of available function calls if it helps. You can store functions, classes and pretty much anything you want in... | 0 | 2016-10-03T15:36:37Z | [
"python"
] |
What is the right way to switch between many choices in Python | 39,835,176 | <p>I want to write something like a AI in Python:</p>
<ol>
<li><p>My first code is like this:</p>
<pre><code>def run()
if choice_a_is_avilable:
choice_a()
return
elif choice_b_is_avilable:
if choice_b_1_is_avilable:
choice_b_1()
return
elif choice_b_2_is... | 2 | 2016-10-03T15:28:32Z | 39,835,343 | <p>Would this work:</p>
<pre><code>choices = {'a': 1, 'b': 2}
result = choices.get(key, 'default')
</code></pre>
| 0 | 2016-10-03T15:38:19Z | [
"python"
] |
What is the right way to switch between many choices in Python | 39,835,176 | <p>I want to write something like a AI in Python:</p>
<ol>
<li><p>My first code is like this:</p>
<pre><code>def run()
if choice_a_is_avilable:
choice_a()
return
elif choice_b_is_avilable:
if choice_b_1_is_avilable:
choice_b_1()
return
elif choice_b_2_is... | 2 | 2016-10-03T15:28:32Z | 39,838,131 | <p>I'm a big fan of table-driven programs.</p>
<pre><code>ctrl_table = [
[choice_a_test, choice_a_func],
[choice_b_test, choice_b_func],
[choice_c_test, choice_c_func]]
for test, func in ctrl_table:
if test():
func()
break
</code></pre>
| 0 | 2016-10-03T18:28:50Z | [
"python"
] |
python/psychopy: for loop to split image names | 39,835,238 | <p>I have a list of images and I want to split their names at the '=' symbol.</p>
<p>e.g. from:</p>
<pre><code>'set_one-C:\Users\Documents\stim\01=aa.png'
</code></pre>
<p>to </p>
<pre><code>'aa.png'
</code></pre>
<p>I have tried to create a 'for loop' to run through each item in the list and split the names in t... | 0 | 2016-10-03T15:31:55Z | 39,835,533 | <pre><code>item = item.name.split('=')[1]
</code></pre>
<p>This doesn't work.... You want this instead:</p>
<pre><code>new_list = []
for item in list:
new_list.append(item.name.split('=')[1])
print(new_list)
</code></pre>
<p>Since you aren't changing your <code>list</code> in the for loop. You are only changin... | 1 | 2016-10-03T15:47:55Z | [
"python",
"psychopy"
] |
Python, QT and matplotlib scatter plots with blitting | 39,835,300 | <p>I am trying to animate a scatter plot (it needs to be a scatter plot as I want to vary the circle sizes). I have gotten the matplotlib documentation tutorial <a href="http://matplotlib.org/examples/animation/rain.html" rel="nofollow">matplotlib documentation tutorial </a> to work in my PyQT application, but would li... | 1 | 2016-10-03T15:35:44Z | 39,902,728 | <p>You need to add <code>return self.scat,</code> at the end of the <code>update</code> method if you want to use <code>FuncAnimation</code> with <code>blit=True</code>. See also this nice <a href="http://stackoverflow.com/a/9416663/4481445">StackOverflow post</a> that presents an example of a scatter plot animation w... | 1 | 2016-10-06T17:58:49Z | [
"python",
"qt",
"matplotlib",
"scatter-plot",
"blit"
] |
How do I find an Index of a header in a csv file in Python? | 39,835,362 | <p>My program list the headers of a CSV file to a user and asks him to pick an x and an y to plot. It works fine, but I don't want the user to type out the header string. I would rather find the index of each of the header and ask him to type a number instead. My csv file looks as follows:</p>
<pre><code>time(s),speed... | 0 | 2016-10-03T15:39:14Z | 39,835,457 | <p>You can get the header with <code>df.columns</code>,</p>
<pre><code>print(", ".join(["{0}.{1}".format(i,x) for i,x in enumerate(df.columns)]))
x_index = input("index of the x series:")
x_header = df.columns[x_index]
y_index = input("index of the y series:")
y_header = df.columns[y_index]
df.plot(x= x_header , y= y_... | 0 | 2016-10-03T15:44:05Z | [
"python"
] |
Trying to calculate distance between points from a .txt file | 39,835,405 | <p>I am trying to figure out how to calculate the length of a line segment using coordinates that are in a text file:</p>
<blockquote>
<p>X,Y format (x,y,x,y,x,y,etc...)</p>
<p>4.5,10.0,4.5,5.7,5.5,2.5,6.5,0.3,6.8,0.0,1.0,1.0,3.5,3.5,2,5,6.0,2.0</p>
</blockquote>
<p>This is what I have so far:</p>
<blockquote... | 1 | 2016-10-03T15:41:18Z | 39,836,218 | <p>From what you have provided I do not see the need to over complicate this. Assuming you can properly import your text-file data, and split it, you could do this: </p>
<pre><code>points = ['4.5','10.0','4.5','5.7','5.5','2.5','6.5','0.3','6.8','0.0','1.0','1.0','3.5','3.5','2','5','6.0','2.0']
x = [float(r) for r... | 0 | 2016-10-03T16:27:56Z | [
"python",
"loops",
"for-loop",
"coordinates",
"gis"
] |
Get all pairs from elements in sublists | 39,835,426 | <p>I have a list of sublists. I need all possible pairs between the elements in the sublists. For example, for a list like this: </p>
<pre><code>a=[[1,2,3],[4,5],[6]]
</code></pre>
<p>The result should be: </p>
<pre><code>result=[[1,4], [1,5], [1,6],
[2,4], [2,5], [2,6],
[3,4], [3,5], [3,6],
... | -2 | 2016-10-03T15:42:31Z | 39,835,612 | <p>You can do the following</p>
<pre><code>>>> from itertools import chain
>>> a=[[1,2,3],[4,5],[6]]
>>> b=[]
>>> for index, item in enumerate(a):
... b.extend([[i, j] for i in item for j in chain.from_iterable(a[index+1:])])
>>> b
[[1, 4],
[1, 5],
[1, 6],
[2, 4],
[2... | 1 | 2016-10-03T15:52:42Z | [
"python"
] |
Get all pairs from elements in sublists | 39,835,426 | <p>I have a list of sublists. I need all possible pairs between the elements in the sublists. For example, for a list like this: </p>
<pre><code>a=[[1,2,3],[4,5],[6]]
</code></pre>
<p>The result should be: </p>
<pre><code>result=[[1,4], [1,5], [1,6],
[2,4], [2,5], [2,6],
[3,4], [3,5], [3,6],
... | -2 | 2016-10-03T15:42:31Z | 39,835,618 | <pre><code>from itertools import chain, product, combinations
sublists = [[1, 2, 3], [4, 5], [6]]
pairs = chain.from_iterable(
product(*sublist_pair) for sublist_pair in combinations(sublists, 2)
)
for x, y in pairs:
print(x, y)
</code></pre>
| 1 | 2016-10-03T15:53:28Z | [
"python"
] |
Get all pairs from elements in sublists | 39,835,426 | <p>I have a list of sublists. I need all possible pairs between the elements in the sublists. For example, for a list like this: </p>
<pre><code>a=[[1,2,3],[4,5],[6]]
</code></pre>
<p>The result should be: </p>
<pre><code>result=[[1,4], [1,5], [1,6],
[2,4], [2,5], [2,6],
[3,4], [3,5], [3,6],
... | -2 | 2016-10-03T15:42:31Z | 39,835,733 | <pre><code># create an empty set to store unique sublist elements
initSet = set()
# combine all sublist elements
for sublist in a:
tempSet = set(sublist)
initSet = intiSet.union(tempSet)
initSet = list(initSet)
# find all possible non-repeating combinations
for _element in initSet:
combinations = list()
... | 0 | 2016-10-03T15:59:22Z | [
"python"
] |
combine SQLAlchemy Core and ORM get problems | 39,835,530 | <p>How do I combine the two component of SQLAlchemy -- Core (SQL Expression) and ORM ?
I have some table that using ORM mapper and others just Table object, and I want <strong>one connection and one transaction for the two</strong>. </p>
<p>I have following two examples but run into problems (result is not consistent... | 0 | 2016-10-03T15:47:44Z | 39,843,661 | <p>After reading more about <code>session</code>, I have answer about it. </p>
<hr>
<p><code>session</code> has its working mechanisms, one is <code>unit of work</code> --</p>
<blockquote>
<p>"All changes to objects maintained by a Session are tracked - before
the database is queried again or before the curren... | 0 | 2016-10-04T03:24:33Z | [
"python",
"sql",
"orm",
"sqlalchemy",
"relational-database"
] |
Python multiplying all even numbers in a list | 39,835,536 | <p>I am working on this python code for my first programming class. Yesterday it partially worked but then I changed something and now it is only passing 1 test case. The goal is to multiply all even numbers in list "xs" and return 1 if there are no even numbers. What am I doing wrong and how can I fix it?</p>
<pre><c... | 0 | 2016-10-03T15:48:16Z | 39,835,582 | <p>This will be your answer:</p>
<pre><code>def evens_product(xs):
product = 1
for i in xs:
if i%2 == 0:
product *= i
return product
</code></pre>
<p>There is no need to <code>return</code> <code>1</code> since the product is already assigned <code>1</code>.
Since you has the <code>... | -1 | 2016-10-03T15:50:54Z | [
"python",
"list",
"numbers",
"multiplying"
] |
Python multiplying all even numbers in a list | 39,835,536 | <p>I am working on this python code for my first programming class. Yesterday it partially worked but then I changed something and now it is only passing 1 test case. The goal is to multiply all even numbers in list "xs" and return 1 if there are no even numbers. What am I doing wrong and how can I fix it?</p>
<pre><c... | 0 | 2016-10-03T15:48:16Z | 39,835,649 | <p>You need to initialize <code>product = 1</code>, for two reasons. One, simply put, you'll get the wrong answer. <code>evens_product([4])</code> should return 4, not 8.
Two, it saves you from having to treat a list with no even numbers as a special case. If there are no even numbers, you never change the value of <co... | 3 | 2016-10-03T15:54:49Z | [
"python",
"list",
"numbers",
"multiplying"
] |
how to remove gibberish that exhibits no pattern using python nltk? | 39,835,546 | <p>I am writing a code to clean the urls and extract just the underlying text.</p>
<pre><code> train_str = train_df.to_string()
letters_only = re.sub("[^a-zA-Z]", " ", train_str)
words = letters_only.lower().split()
stops = set(stopwords.words("english"))
stops.update(['url','https','http','com'])
meaningful_word... | 1 | 2016-10-03T15:48:50Z | 39,836,090 | <p>create an empty list. Loop through all the words in the current list. use <code>words.words()</code> from the corpera to check if it is a real world. Append all the "non-junk words" to that new list. Use that new list for whatever you'd like.</p>
<pre><code>from nltk.corpus import words
test = ['uact', 'ahukewim',... | 0 | 2016-10-03T16:19:57Z | [
"python",
"python-3.x",
"nltk"
] |
Convert the key of a dictionary into a string | 39,835,555 | <p>I think that the problem of my code is that each time the loop in iterating on a new variable, the previous variable is not deleted. So I end up with plot that contains all the previous data coming from the previous iterations.
What I may need is a function to clear up the memory at the end of each loop...
The rea... | -3 | 2016-10-03T15:49:30Z | 39,837,360 | <p>I added a pyplot function : plt.close() at the end of my loop which solved the problem</p>
| 0 | 2016-10-03T17:41:06Z | [
"python",
"string",
"dictionary"
] |
Solving a second-order boundary value equation on a non-uniform mesh | 39,835,627 | <p>I have an equation of the form </p>
<p><code>y'' + a(x) y' + b(x) y = f(x)
y(0) = y(1) = 1</code></p>
<p>where <code>x</code> is non-uniformly spaced. </p>
<p>How can I solve this type of second-order boundary value problem in python? </p>
| 0 | 2016-10-03T15:53:55Z | 39,840,646 | <p>Are you searching for the family of functions [ y<sub>x</sub><code>(t)</code> ] where <code>t</code> is the variable on which you derive <code>y</code>?</p>
<p>Are your boundary conditions true for all x?</p>
<p>You might want to look at <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.... | 0 | 2016-10-03T21:24:40Z | [
"python",
"numpy",
"scipy",
"numerical-methods",
"differential-equations"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.