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 |
|---|---|---|---|---|---|---|---|---|---|
Remove numbers conditionally? | 38,793,863 | <p>I'm sorry if the title isn't very descriptive. I don't exactly know how to sum up my problem in a few words.</p>
<p>Here's my issue. I'm cleaning addresses and some of them are causing some issues.</p>
<p>I have a list of delimiters (avenue, street, road, place, etc etc etc) named <code>patterns</code>.</p>
<p>Le... | 1 | 2016-08-05T16:25:54Z | 38,794,500 | <p>If you want to apply this replacement <em>only</em> when one of your "separator" words is used, and <em>only</em> when there are two numbers, you can use a fancier regular expression.</p>
<pre><code>import re
pattern = r"\d+ +(\d+ .*(STREET|AVENUE|ROAD|WHATEVER))"
input = "SUITE 1603 200 PARK AVENUE SOUTH NEW YORK... | 3 | 2016-08-05T17:06:37Z | [
"python"
] |
Parsing '\n' to '\n ctrl-l' with Python | 38,793,990 | <p>I have a program that can access Python from inside within it's initial file, that looks like</p>
<blockquote>
<p>#initial file<br>
source py_commands.py<br>
py_cmd </p>
</blockquote>
<p>I want to grep from inside that program <code>\n</code> and parse it to <code>\n ctrl-l</code>.
Ctrl-l is just a combined... | 0 | 2016-08-05T16:34:14Z | 38,968,979 | <p><code>raw_input()</code> strips the trailing newline. If you want the string to end with <code>\n</code> <code>\f</code> (Ctrl-L is <em>Form Feed</em>), you have to add both.</p>
<pre><code>x = raw_input()
print(x+'\n\f')
</code></pre>
| 1 | 2016-08-16T07:30:50Z | [
"python",
"linux",
"parsing"
] |
Selenium Python : extract field from json data in <a> tag | 38,794,012 | <p>On a particular webpage, I have the following tag :</p>
<pre><code><a id="AAA" class="BBB" data-json="{"link":"thelink","field1":1,"field2":5}">
Load more
</a>
</code></pre>
<p>I am using Selenium / Python. I want to click 5 times on this tag, where 5 is the value from "field2" in "data-json".</p>
<... | 0 | 2016-08-05T16:35:35Z | 38,794,172 | <p>To get the value of an attribute you can use the function <code>get_attribute</code> <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.get_attribute" rel="nofollow">link</a>, in this particular case we have to parse the data-json to a dict and get the number. My ... | 1 | 2016-08-05T16:46:58Z | [
"python",
"json",
"selenium",
"xpath"
] |
Selenium Python : extract field from json data in <a> tag | 38,794,012 | <p>On a particular webpage, I have the following tag :</p>
<pre><code><a id="AAA" class="BBB" data-json="{"link":"thelink","field1":1,"field2":5}">
Load more
</a>
</code></pre>
<p>I am using Selenium / Python. I want to click 5 times on this tag, where 5 is the value from "field2" in "data-json".</p>
<... | 0 | 2016-08-05T16:35:35Z | 38,794,272 | <p>As mentionned by peers, it would be far better with <strong>id</strong>.</p>
<p>You can use <code>get_attribute</code> and json convertion:</p>
<pre><code>>>> import json
>>> data = browser.find_element_by_id("AAA").get_attribute("data-json")
>>> json.loads(data)["field2"]
>>> 5... | 0 | 2016-08-05T16:53:09Z | [
"python",
"json",
"selenium",
"xpath"
] |
Creating class object from pandas series and applying methods | 38,794,077 | <p>I have a function that reads in a bunch of raw data with some user-input and compiles it into a Pandas series. In the example below I call it <code>create_data</code> and it just builds a random Series of length <code>n</code>. </p>
<pre><code>>>> def create_data(n):
... return pd.Series(np.random.rand... | 1 | 2016-08-05T16:40:12Z | 38,855,563 | <p>Essentially you're looking for an object that acts like a <code>Series</code> but is more <em>specialized</em>, so, just create a class that inherits from <code>pd.Series</code>:</p>
<pre><code>import pandas as pd
from numpy.random import randint
class mySeries(pd.Series):
def __init__(self, n):
super... | 1 | 2016-08-09T16:02:44Z | [
"python",
"pandas"
] |
Creating class object from pandas series and applying methods | 38,794,077 | <p>I have a function that reads in a bunch of raw data with some user-input and compiles it into a Pandas series. In the example below I call it <code>create_data</code> and it just builds a random Series of length <code>n</code>. </p>
<pre><code>>>> def create_data(n):
... return pd.Series(np.random.rand... | 1 | 2016-08-05T16:40:12Z | 38,878,992 | <p>If I understand your question correctly, I think you're looking to do the following:</p>
<pre><code>import pandas as pd
import numpy as np
class MyObjMaker(object):
def __init__(self, n):
self.myobj = pd.Series(np.random.randint(1, 100, n))
def temporal_corr(self):
return pd.concat([self... | 0 | 2016-08-10T16:32:28Z | [
"python",
"pandas"
] |
Django ForeignKeys not saving | 38,794,192 | <p>Currently have a problem where I will assign a both Client foreignkey to a Signin and its not saving either reference. Heres the Signin Model</p>
<pre><code>#Sign-ins require just a user
class Signin(models.Model):
employee = models.ForeignKey(Employee)
sign_in_time = models.DateTimeField(null=True)
si... | 0 | 2016-08-05T16:47:58Z | 38,797,031 | <p>I found the answer! </p>
<p>So the problem was followed. Im dealing with a legacy database in mySQL, the problem was that when django was assigning the client id it was thinking the primary key was an integer field, so when it tried assigning the key (which was a varchar) it ran into an integer field, so it didn'... | 1 | 2016-08-05T20:04:32Z | [
"python",
"django"
] |
Python - Internationalization for Telegram bots | 38,794,237 | <p>I'm using Python <strong>gettext</strong> to translate my Telegram bot messages to pt_BR or leave them in en_US. This is my code:</p>
<pre><code># Config the translations
lang_pt = gettext.translation("pt_BR", localedir="locale", languages=["pt_BR"])
def _(msg): return msg
# Connecting to Redis db
db = redis.Stric... | 1 | 2016-08-05T16:51:20Z | 38,799,001 | <p>Solved!</p>
<p>I just forgot to declare the <strong>_()</strong> as being global. Here is the right code:</p>
<pre><code>def user_language(func):
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
lang = db.get(str(update.message.chat_id))
global _
if lang == b"pt_BR":
... | 0 | 2016-08-05T23:22:15Z | [
"python",
"internationalization",
"telegram"
] |
NoReverseMatch for Createview | 38,794,348 | <p>I am using the CreateView (CBV) with a template that has a form to review lawyers. </p>
<p>When I try to use the URL routing in the template, I get this error:</p>
<pre><code>Exception Value: Reverse for 'lawyerreview_create' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['father... | 0 | 2016-08-05T16:57:47Z | 38,794,880 | <p>The url tag takes the reverse name and arguments / keyword arguments as paramaters:</p>
<pre><code>url(r'^lawyers/(?P<lawyerreview_slug>[\w-]+)/createreview/$', LawyerReviewCreate.as_view(), name='lawyerreview_create'),
</code></pre>
<p>so in this case it expects your urls name (lawyerview_create) and the la... | 1 | 2016-08-05T17:31:08Z | [
"python",
"django",
"url"
] |
Replace dictionary's empty values python | 38,794,388 | <p>First of all, I'm modifying another guy's code.</p>
<p>I'm trying to print the values of dictionary that correspond to a <code>key</code> like so: </p>
<p><code>print (map(str, dict[key]))</code></p>
<p>All works fine, but there are some fields that are printed with just the double quotes, like so <code>['some_va... | 0 | 2016-08-05T16:59:44Z | 38,794,537 | <p>Try using </p>
<pre><code>print([k if k else "n/a" for k in map(str, dict[key])])
</code></pre>
| 0 | 2016-08-05T17:10:06Z | [
"python",
"dictionary"
] |
Replace dictionary's empty values python | 38,794,388 | <p>First of all, I'm modifying another guy's code.</p>
<p>I'm trying to print the values of dictionary that correspond to a <code>key</code> like so: </p>
<p><code>print (map(str, dict[key]))</code></p>
<p>All works fine, but there are some fields that are printed with just the double quotes, like so <code>['some_va... | 0 | 2016-08-05T16:59:44Z | 38,794,620 | <p>map function needs func and iterable</p>
<pre><code>data = { '':'',1:'a'}
print (map( lambda x: x if x else 'n/a', data.values()))
['n/a', 'a']
</code></pre>
<p>for value as list:</p>
<pre><code>data = { 'a' :[1,'',2]}
print (map( lambda x: str(x) if x else 'n/a', data['a']))
['1', 'n/a', '2']
</code></pre>
| 0 | 2016-08-05T17:14:24Z | [
"python",
"dictionary"
] |
Replace dictionary's empty values python | 38,794,388 | <p>First of all, I'm modifying another guy's code.</p>
<p>I'm trying to print the values of dictionary that correspond to a <code>key</code> like so: </p>
<p><code>print (map(str, dict[key]))</code></p>
<p>All works fine, but there are some fields that are printed with just the double quotes, like so <code>['some_va... | 0 | 2016-08-05T16:59:44Z | 38,794,641 | <p>You should probably just expand to a for loop and write:</p>
<pre><code>for value in dict.values():
if value == "":
print("n/a")
else:
print(str(value))
</code></pre>
| 0 | 2016-08-05T17:15:44Z | [
"python",
"dictionary"
] |
Replace dictionary's empty values python | 38,794,388 | <p>First of all, I'm modifying another guy's code.</p>
<p>I'm trying to print the values of dictionary that correspond to a <code>key</code> like so: </p>
<p><code>print (map(str, dict[key]))</code></p>
<p>All works fine, but there are some fields that are printed with just the double quotes, like so <code>['some_va... | 0 | 2016-08-05T16:59:44Z | 38,794,693 | <p>You could solve your problem in a more simple way without using map(). Just use list() than you can loop on every single character of your string (diz[key]) and then replace the empty space with the 'n/a' string as you wish.</p>
<pre><code>diz[key] = 'a val'
[w.replace(' ', 'n/a') for w in list(diz[key])]
>> ... | 0 | 2016-08-05T17:18:54Z | [
"python",
"dictionary"
] |
int() argument must be a string or a number, not 'SimpleLazyObject' in django | 38,794,393 | <p>I have this problem catching the pk of the Selfie model, i'm trying to save a comment, but i have this error, the mistake is in the CreateComment class in the views.py, please guys i need a hand</p>
<p><strong>in models.py</strong></p>
<pre><code>class Selfie(models.Model):
selfie_title = models.CharField(max_... | 0 | 2016-08-05T17:00:09Z | 38,794,616 | <p>You can't assign the <code>user</code> to <code>comment_user_id</code> because it expects an integer. Either of the following would work:</p>
<pre><code>obj.comment_user_id = self.request.user.id
obj.comment_user = self.request.user
</code></pre>
| 1 | 2016-08-05T17:14:17Z | [
"python",
"django"
] |
Why is matplotlib's notched boxplot folding back on itself? | 38,794,406 | <p>I tried to make a notched boxplot using matplotlib, but found the notched box tends to overextend and then fold back on itself. This does not happen when I make a regular boxplot. </p>
<p>This can be seen with the following code and the resulting plot that gets generated:</p>
<pre><code>import matplotlib.pyplot as... | 1 | 2016-08-05T17:00:55Z | 38,795,446 | <p>It means that the distribution of the data is skewed.
If two boxes' notches do not overlap, there is 95% confidence their medians differ.</p>
<p>The Notch displays the confidence interval around the median which is normally based on : <a href="http://i.stack.imgur.com/1GROL.png" rel="nofollow"><img src="http://i.st... | 2 | 2016-08-05T18:08:44Z | [
"python",
"matplotlib"
] |
Python unreachable variable assignment resulting in UnboundLocalError | 38,794,409 | <p>I am trying to understand how variables are managed internally by Python. </p>
<pre><code>x = 10
def ex1():
if False:
x=1
print(x)
ex1()
</code></pre>
<p>When ex1() is executed, it shows an UnboundLocalError since local variable 'x' is not referenced. </p>
<p>How does this happen?
Does the parsin... | 2 | 2016-08-05T17:01:08Z | 38,794,614 | <p>Python doesn't have variable declarations, so when variables are created/used it has to determine the scope itself. Python scoping is lexical, meaning that it can access a variable in its enclosed scope, it cannot modify them.
The way ex1() is written, x=1 is local to ex1(). However, when you go to run ex1() it tr... | 0 | 2016-08-05T17:14:15Z | [
"python",
"variables",
"scope",
"interpreter"
] |
Python unreachable variable assignment resulting in UnboundLocalError | 38,794,409 | <p>I am trying to understand how variables are managed internally by Python. </p>
<pre><code>x = 10
def ex1():
if False:
x=1
print(x)
ex1()
</code></pre>
<p>When ex1() is executed, it shows an UnboundLocalError since local variable 'x' is not referenced. </p>
<p>How does this happen?
Does the parsin... | 2 | 2016-08-05T17:01:08Z | 38,794,934 | <p>Conceptually this make sense. I can't tell how its implemented but I can tell why.</p>
<p>When you affect a variable it gets affected in the local scope unless you explicitly tell by using the keyword <code>global</code>. If you only access it and there is no affectation it will implicitly use the global variable s... | 0 | 2016-08-05T17:34:57Z | [
"python",
"variables",
"scope",
"interpreter"
] |
Asynchronious email sending in Django | 38,794,571 | <p>I'm trying to figure out how to send email asynchroniously so <code>User</code> don't have to wait until <code>email</code> is sent. </p>
<p>I've installer <code>celery</code> and <code>django-celery-email</code> and added <code>django-celery-email</code> into my <code>settings.py</code> - <code>djcelery_email</cod... | 0 | 2016-08-05T17:11:47Z | 38,809,391 | <h2>Problem</h2>
<p>From <a href="https://github.com/pmclanahan/django-celery-email" rel="nofollow">https://github.com/pmclanahan/django-celery-email</a></p>
<blockquote>
<p>By default django-celery-email will use Django's builtin SMTP email
backend for the actual sending of the mail.</p>
</blockquote>
<p>This m... | 0 | 2016-08-06T22:43:22Z | [
"python",
"django",
"django-celery",
"django-email"
] |
How to get constant function to keep shape in NumPy | 38,794,622 | <p>I have a <code>NumPy</code> array <code>A</code> with shape <code>(m,n)</code> and want to run all the elements through some function <code>f</code>. For a non-constant function such as for example <code>f(x) = x</code> or <code>f(x) = x**2</code> broadcasting works perfectly fine and returns the expected result. Fo... | 0 | 2016-08-05T17:14:26Z | 38,794,679 | <p><code>F(x) = 1</code> is not a function you need to create a function with <code>def</code> or <code>lambda</code> and return 1. Then use <code>np.vectorize</code> to apply the function on your array.</p>
<pre><code>>>> import numpy as np
>>> f = lambda x: 1
>>>
>>> f = np.vecto... | 1 | 2016-08-05T17:18:12Z | [
"python",
"numpy",
"numpy-broadcasting"
] |
How to get constant function to keep shape in NumPy | 38,794,622 | <p>I have a <code>NumPy</code> array <code>A</code> with shape <code>(m,n)</code> and want to run all the elements through some function <code>f</code>. For a non-constant function such as for example <code>f(x) = x</code> or <code>f(x) = x**2</code> broadcasting works perfectly fine and returns the expected result. Fo... | 0 | 2016-08-05T17:14:26Z | 38,794,707 | <p>Use <code>x.fill(1)</code>. Make sure to return it properly as <code>fill</code> doesn't return a new variable, it modifies <code>x</code></p>
| 0 | 2016-08-05T17:19:31Z | [
"python",
"numpy",
"numpy-broadcasting"
] |
How to get constant function to keep shape in NumPy | 38,794,622 | <p>I have a <code>NumPy</code> array <code>A</code> with shape <code>(m,n)</code> and want to run all the elements through some function <code>f</code>. For a non-constant function such as for example <code>f(x) = x</code> or <code>f(x) = x**2</code> broadcasting works perfectly fine and returns the expected result. Fo... | 0 | 2016-08-05T17:14:26Z | 38,794,735 | <p>This sounds like a job for <code>np.ones_like</code>, or <code>np.full_like</code> in the general case:</p>
<pre><code>def f(x):
result = np.full_like(x, 1) # or np.full_like(x, 1, dtype=int) if you don't want to
# inherit the dtype of x
if result.shape == 0:
# Retu... | 0 | 2016-08-05T17:21:07Z | [
"python",
"numpy",
"numpy-broadcasting"
] |
Python split multiples comma | 38,794,692 | <p>I have a CSV string like this : </p>
<pre><code>foo = "value0,value1,value2,value3,value4".split(",")
test(foo)
</code></pre>
<p>I'm using split to split this string in an array. Then I've a function that takes the array and assign these value to some internal variables :</p>
<pre><code>def test(foo):
var0 = f... | -2 | 2016-08-05T17:18:53Z | 38,794,760 | <p>You need to remove/filter the empty strings after splitting the string, and since you are not aware of the length of your items you can use a dictionary in order to preserve your strings.</p>
<pre><code>my_vars = {'var{}'.format(i):j for i, j in enumerate(mystr.split(',')) if j}
</code></pre>
<p>Here is a Demo:</... | 0 | 2016-08-05T17:22:58Z | [
"python",
"arrays",
"split"
] |
Python split multiples comma | 38,794,692 | <p>I have a CSV string like this : </p>
<pre><code>foo = "value0,value1,value2,value3,value4".split(",")
test(foo)
</code></pre>
<p>I'm using split to split this string in an array. Then I've a function that takes the array and assign these value to some internal variables :</p>
<pre><code>def test(foo):
var0 = f... | -2 | 2016-08-05T17:18:53Z | 38,794,802 | <p>Simply use <code>splitlines</code> with <code>split</code>, it working fine on my system
or you can Try this</p>
<pre><code>for lines in foo.splitlines():
print (lines.split(','))
</code></pre>
<p>will produce this result</p>
<pre><code>['value0', 'value1', '', '', 'value4']
</code></pre>
<p>where foo was <c... | -1 | 2016-08-05T17:25:37Z | [
"python",
"arrays",
"split"
] |
How to Multithreading Python with my laptop | 38,794,706 | <p>I have project in python, structure of my project like this :</p>
<pre><code>def makeRecommendation:
.....do something here....
insertRecomenderToDB(result)
def insertRecomenderToDB(result):
.....do something here....
if __name__ == '__main__':
makeRecommendation()
</code></pre>... | -2 | 2016-08-05T17:19:30Z | 38,801,021 | <p>Python's multithreading cannot make use of multicore. The only way is to use multi-processing. There are several modules that you could use:</p>
<p><a href="https://docs.python.org/3.5/library/multiprocessing.html" rel="nofollow">multiprocessing</a>: This module gives you complete control over new process.<br>
<a h... | 0 | 2016-08-06T05:54:00Z | [
"python",
"multithreading",
"multiprocessing"
] |
How to visualize a layered graph (for GraphPlan planning algorithm) | 38,794,714 | <p>I did a quick web search and having not found readily available (and library-provided) solutions for what I think is a well specified and fairly standard visualization problem, decided to quickly implement it myself. But before doing this, though, I wanted to get a sanity advice from the community.</p>
<p>I need to... | 0 | 2016-08-05T17:20:04Z | 38,798,362 | <p>Turned out not too terrible:
<a href="http://i.stack.imgur.com/P2OW5.png" rel="nofollow"><img src="http://i.stack.imgur.com/P2OW5.png" alt="enter image description here"></a></p>
<p>Basically:</p>
<ol>
<li>Stored my objects in a 2d array</li>
<li>Generated Xs and Ys for a scatter plot grid (some additional care wa... | 0 | 2016-08-05T22:05:40Z | [
"python",
"matplotlib",
"graph",
"visualization"
] |
Bit field specialization in python | 38,794,715 | <p>Here is a code in C++:</p>
<pre><code>void sign_extending(int x)
{
int r; // resulting sign extended number goes here
struct {signed int x:5 ;} s;
r = s.x = x;
cout << r;
}
void Run()
{
int x=29; // this 29 is -3 ( 11101 ) in 5 bits
// convert this from using 5 bits to a full int
sign_extendi... | 1 | 2016-08-05T17:20:04Z | 38,795,330 | <p>I think that this might possibly do what you want (as long as x is non-negative and can be written using b bits).</p>
<pre><code>def sign_extend(x, b):
if x >= 2 ** (b - 1):
return x - 2 ** b
else:
return x
</code></pre>
| 1 | 2016-08-05T18:00:14Z | [
"python",
"ctypes",
"bit-fields",
"sign-extension"
] |
Bit field specialization in python | 38,794,715 | <p>Here is a code in C++:</p>
<pre><code>void sign_extending(int x)
{
int r; // resulting sign extended number goes here
struct {signed int x:5 ;} s;
r = s.x = x;
cout << r;
}
void Run()
{
int x=29; // this 29 is -3 ( 11101 ) in 5 bits
// convert this from using 5 bits to a full int
sign_extendi... | 1 | 2016-08-05T17:20:04Z | 38,799,936 | <p>In your code <code>s</code> is a class and the class <code>x</code> member actually represents the field type, so assigning <code>s.x = 29</code> essentially destroys that object and assigns a normal Python int to it. Example:</p>
<pre><code>>>> from ctypes import *
>>> class S(Structure):
... ... | 2 | 2016-08-06T02:05:49Z | [
"python",
"ctypes",
"bit-fields",
"sign-extension"
] |
Python get last month and year | 38,794,935 | <p>I am trying to get last month and current year in the format: July 2016.</p>
<p>I have tried (but that didn't work) and it does not print July but the number:</p>
<pre><code>import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
</code></pre>
| 1 | 2016-08-05T17:34:58Z | 38,794,963 | <pre><code>now = datetime.datetime.now()
last_month = now.month-1 if now.month > 1 else 12
last_year = now.year - 1
</code></pre>
<p>to get the month name you can use</p>
<pre><code>"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[last_month-1]
</code></pre>
| 1 | 2016-08-05T17:37:20Z | [
"python",
"date",
"datetime"
] |
Python get last month and year | 38,794,935 | <p>I am trying to get last month and current year in the format: July 2016.</p>
<p>I have tried (but that didn't work) and it does not print July but the number:</p>
<pre><code>import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
</code></pre>
| 1 | 2016-08-05T17:34:58Z | 38,795,214 | <pre><code>def subOneMonth(dt):
day = dt.day
res = dt.replace(day=1) - datetime.timedelta(days =1)
try:
res.replace(day= day)
except ValueError:
pass
return res
print subOneMonth(datetime.datetime(2016,07,11)).strftime('%d, %b %Y')
11, Jun 2016
print subOneMonth(datetime.datetime(2016,01,11))... | 2 | 2016-08-05T17:53:22Z | [
"python",
"date",
"datetime"
] |
Python get last month and year | 38,794,935 | <p>I am trying to get last month and current year in the format: July 2016.</p>
<p>I have tried (but that didn't work) and it does not print July but the number:</p>
<pre><code>import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
</code></pre>
| 1 | 2016-08-05T17:34:58Z | 38,795,233 | <p>An alternative solution using Pandas which converts today to a monthly period and then subtracts one (month). Converted to desired format using <code>strftime</code>.</p>
<pre><code>import datetime as dt
import pandas as pd
>>> (pd.Period(dt.datetime.now(), 'M') - 1).strftime('%B %Y')
u'July 2016'
</code... | 1 | 2016-08-05T17:54:36Z | [
"python",
"date",
"datetime"
] |
Python get last month and year | 38,794,935 | <p>I am trying to get last month and current year in the format: July 2016.</p>
<p>I have tried (but that didn't work) and it does not print July but the number:</p>
<pre><code>import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
</code></pre>
| 1 | 2016-08-05T17:34:58Z | 38,795,526 | <p>If you're manipulating dates then the <a href="https://pypi.python.org/pypi/python-dateutil">dateutil</a> library is always a great one to have handy for things the Python stdlib doesn't cover easily.</p>
<pre><code>from datetime import datetime
from dateutil.relativedelta import relativedelta
# Returns the same d... | 5 | 2016-08-05T18:13:45Z | [
"python",
"date",
"datetime"
] |
Pointing bash to a python installed on windows | 38,794,937 | <p>I am using Windows 10 and have Python installed. The new update brought bash to windows, but when I call python from inside bash, it refers to the Python installation which came with the bash, not to my Python installed on Windows. So, for example, I can't use the modules which I have already installed on Windows an... | 3 | 2016-08-05T17:35:17Z | 38,797,880 | <p>I do not have Windows 10 installed, but I use Babun and I had the same problem. As I read aliases work well in Windows 10 shell so simply add alias in your .bashrc pointing to your Python installation directory:</p>
<pre><code>alias python /mnt/c/Python27/python
</code></pre>
| 0 | 2016-08-05T21:17:53Z | [
"python",
"windows",
"bash",
"wsl"
] |
Pointing bash to a python installed on windows | 38,794,937 | <p>I am using Windows 10 and have Python installed. The new update brought bash to windows, but when I call python from inside bash, it refers to the Python installation which came with the bash, not to my Python installed on Windows. So, for example, I can't use the modules which I have already installed on Windows an... | 3 | 2016-08-05T17:35:17Z | 38,797,912 | <p>You have at least four options:</p>
<ol>
<li>Specify the complete absolute path to the python executable you want to use.</li>
<li>Define an alias in your .bashrc file</li>
<li>Modify the PATH variable in your .bashrc file to include the location of the python version you wish to use.</li>
<li>Create a symlink in a... | 0 | 2016-08-05T21:20:48Z | [
"python",
"windows",
"bash",
"wsl"
] |
Pointing bash to a python installed on windows | 38,794,937 | <p>I am using Windows 10 and have Python installed. The new update brought bash to windows, but when I call python from inside bash, it refers to the Python installation which came with the bash, not to my Python installed on Windows. So, for example, I can't use the modules which I have already installed on Windows an... | 3 | 2016-08-05T17:35:17Z | 39,480,122 | <p>You currently cannot run Windows apps from within Bash but this is a feature we're working on for a future release. If you're keen to be among the first to receive and run this feature when it's complete, be sure to sign up for the Windows 10 Insider Fast-Ring.</p>
| 0 | 2016-09-13T22:50:30Z | [
"python",
"windows",
"bash",
"wsl"
] |
Django error on admin search: Cannot resolve keyword 'username' into field | 38,794,986 | <p>I am having a problem in my admin in Django. I have a list of users, I can add, edit and delete them without any problem. However, when I use the search bar to find specific users, i get the error: </p>
<pre><code>Cannot resolve keyword 'username' into field. Choices are: bookreader, date_joined, email, full_name,... | 0 | 2016-08-05T17:38:51Z | 38,795,220 | <p>The <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields" rel="nofollow"><code>search_fields</code></a> option for the <code>UserAdmin</code> class contains <code>username</code>, <code>first_name</code> and <code>last_name</code> (<a href="https://github.co... | 1 | 2016-08-05T17:53:41Z | [
"python",
"django",
"python-3.x",
"django-admin"
] |
Python - Tweepy Regex | 38,795,153 | <p>I'm using Tweepy streamer to collect some tweets for certain tags, in this case #python. The streamer part of the script works fine but where I'm struggling is extracting the information from the output. </p>
<p>Tweepy sample:
{"created_at":"Fri Aug 05 17:27:00 +0000 2016","id":761614496666361857,"id_str":"7616144... | 0 | 2016-08-05T17:49:21Z | 38,797,181 | <p>The easisest way if you want to extract the text is with json module.</p>
<pre><code>import json
class MyListener(StreamListener):
def on_data(self, data):
try:
json.loads(data)
f = open('tmp', 'a')
f.write(data["text"])
... | 1 | 2016-08-05T20:16:07Z | [
"python",
"regex",
"tweepy"
] |
Numpy ValueError: setting an array element with a sequence reading in list | 38,795,183 | <p>I have this code that reads numbers and is meant to calculate std and %rms using numpy </p>
<pre><code>import numpy as np
import glob
import os
values = []
line_number = 6
road = '/Users/allisondavis/Documents/HCl'
for pbpfile in glob.glob(os.path.join(road, 'pbpfile*')):
lines = open(pbpfile, 'r').readlines... | 0 | 2016-08-05T17:51:19Z | 38,799,276 | <p>I can think of a modification to your code which can potentially fix your problem:</p>
<p>Initialize values as a numpy array, and use numpy append or concatenate:</p>
<pre><code>values = np.array([], dtype=float)
</code></pre>
<p>Then inside loop:</p>
<pre><code>values = np.append(values, [variables], axis=0)
# ... | 0 | 2016-08-06T00:02:58Z | [
"python",
"arrays",
"numpy"
] |
Use specific instance of DLL with ctypes | 38,795,189 | <p>Is it possible to use a specific instance of a DLL using ctypes? Basically my application is as follows:
We have a C DLL accessed by a C# DLL and then a C# WPF front end. I wrote a separate wrapper using ctypes to access the C DLL directly and bypass the C# all together. </p>
<p>We currently use an internal IronPyt... | 2 | 2016-08-05T17:51:38Z | 38,795,386 | <p>You have a program which loads a C# DLL which loads a C DLL. The same program also runs IronPython and you want Python to load the same C DLL.</p>
<p>I assume you are using <code>ctypes.windll.LoadLibrary(path)</code> in Python. So you just need to find the right path. For C# some ideas are here: <a href="http:/... | 0 | 2016-08-05T18:04:08Z | [
"python",
"ctypes"
] |
Django filter returning duplicates after order_by based on multiple criteria | 38,795,292 | <p>I'm having difficulty returning unique <code>Clazz</code> objects based off my criteria and ordering. <code>Clazz</code> and <code>Session</code> are two separate models and a class can have many sessions.</p>
<p>Once I introduced the <code>order_by</code> I'm seeing duplicate <code>Clazz</code> objects. How can I ... | 0 | 2016-08-05T17:57:47Z | 38,796,492 | <p>After @Alasdair's response, ended up just doing this:</p>
<pre><code>dup_list = []
class_list = []
for c in classes:
if c not in dup_list:
dup_list.append(c)
class_list.append(c)
classes = class_list
</code></pre>
| 0 | 2016-08-05T19:25:01Z | [
"python",
"django"
] |
Django filter returning duplicates after order_by based on multiple criteria | 38,795,292 | <p>I'm having difficulty returning unique <code>Clazz</code> objects based off my criteria and ordering. <code>Clazz</code> and <code>Session</code> are two separate models and a class can have many sessions.</p>
<p>Once I introduced the <code>order_by</code> I'm seeing duplicate <code>Clazz</code> objects. How can I ... | 0 | 2016-08-05T17:57:47Z | 38,797,032 | <p>I guess you can do something like this:</p>
<pre><code>classes = Clazz.objects.filter(location=loc).annotate(
startdate=Max('session__start_date'),
end_date=Max('session__end_date')
).order_by('startdate', 'end_date')
</code></pre>
| 0 | 2016-08-05T20:04:33Z | [
"python",
"django"
] |
How to pull a datetime object out of multiple file names? | 38,795,315 | <p>I have a mutiple files that I want to create a datetime object from, an example is as such: </p>
<pre><code>corr_20060122_082009_vt_unfolded
</code></pre>
<p>and I wanted to created a datetime object. 2006 is year, 01 month, 22 day, 08 hour, 20 mins, 09 seconds, time is in the 24 hour format (military time) in t... | 1 | 2016-08-05T17:59:30Z | 38,795,396 | <pre><code>>>> import re
>>> from datetime import datetime
>>> s = re.findall(r'\d+_\d+', 'corr_20060122_082009_vt_unfolded')[0]
>>> datetime.strptime(s, '%Y%m%d_%H%M%S')
datetime.datetime(2006, 1, 22, 8, 20, 9)
</code></pre>
| 1 | 2016-08-05T18:05:14Z | [
"python",
"datetime",
"filenames",
"jupyter-notebook"
] |
Django REST Framework - Fake objects for unit tests | 38,795,394 | <p>I'm writing unit tests for my Django app. Currently I'm using <a href="https://factoryboy.readthedocs.io/en/latest/index.html" rel="nofollow">factory_boy</a> to make fake objects for testing. This works fine for most of my tests, but I'm having the following problem: <strong>My factory_boy objects aren't showing up ... | 3 | 2016-08-05T18:04:48Z | 38,795,493 | <p>You need to <strong>inherit from <a href="http://factoryboy.readthedocs.io/en/latest/orms.html#the-djangomodelfactory-subclass" rel="nofollow"><code>DjangoModelFactory</code></a> instead of <code>Factory</code></strong> base class in your <code>UserFactory</code> for objects to be saved onto the database.</p>
<p>Fr... | 2 | 2016-08-05T18:11:35Z | [
"python",
"django",
"unit-testing",
"django-rest-framework"
] |
How to refence current object (F object) within RawSQL | 38,795,403 | <p>My <code>Order</code> model looks like this:</p>
<pre><code>class Order(models.Model):
...
billing_email = models.EmailField()
...
</code></pre>
<p>Desired output I am looking for is a <code>ValuesQuerySet</code> that would contain some fields values and a calculated value of the amount of orders with ... | 2 | 2016-08-05T18:05:53Z | 38,876,636 | <p>You can reference the "current" row using the table name of your Model:</p>
<pre><code>RawSQL( "SELECT COUNT(*) FROM appname_order order WHERE order.billing_email =appname_order.billing_email",[])
</code></pre>
| 0 | 2016-08-10T14:44:05Z | [
"python",
"django",
"postgresql"
] |
Flask-sqlalchemy disable autoflush for the whole session | 38,795,414 | <p>I am using Flask-sqlalchemy, how can I just configure it for <code>no autoflush</code>. Currently I am doing something like </p>
<pre><code>db = SQLAlchemy()
...
db.init_app(app)
...
db.session.configure(autoflush=False)
</code></pre>
<p>But it gives error. How to fix this. </p>
| 1 | 2016-08-05T18:06:27Z | 38,805,820 | <p>The <code>session_options</code> parameter can be used to override session options. If provided itâs a dict of parameters passed to the sessionâs constructor.</p>
<pre><code> db = SQLAlchemy(session_options={"autoflush": False})
</code></pre>
| 1 | 2016-08-06T15:23:47Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] |
Passing a command line argument to a py.test fixture as a parameter | 38,795,482 | <p>Admittedly it is not the best way to do it to start with and more importantly the fixture parameters are resolved i.e. Options.get_option() is called before everything else.
Recommendations and suggestions would be appreciated.</p>
<p>From config.py</p>
<pre><code>class Options(object):
option = None
@cl... | 1 | 2016-08-05T18:10:54Z | 38,804,497 | <p>Don't use custom <code>Options</code> class but directly ask for option from config.</p>
<p><code>pytest_generate_tests</code> may be used for parametrizing fixture-like argument for tests.</p>
<p>conftest.py</p>
<pre><code>def pytest_addoption(parser):
parser.addoption("--pg_tag", action="append", default=[]... | 1 | 2016-08-06T12:53:54Z | [
"python",
"py.test"
] |
Why does the MSE sklearn library give me a different squared error compared to the l2 norm squared error? | 38,795,494 | <p>I was trying to compute the mean squared error as in:</p>
<p><a href="http://i.stack.imgur.com/xXvG4.png" rel="nofollow"><img src="http://i.stack.imgur.com/xXvG4.png" alt="enter image description here"></a></p>
<p>in python. I saw that <a href="http://scikit-learn.org/stable/modules/model_evaluation.html#mean-squa... | 0 | 2016-08-05T18:11:36Z | 38,795,656 | <p>The formula that's used is a little unusual in that it doesn't take the square root of the sum of squares, whereas <code>LA.norm</code> does.</p>
<p>If you look carefully at the docs, you can recreate the formula</p>
<p><code>np.sum((X_truth-X_pred)**2)/X_truth.size</code></p>
<p>gives 0.49 just like</p>
<p><cod... | 2 | 2016-08-05T18:25:15Z | [
"python",
"numpy",
"machine-learning",
"scipy",
"scikit-learn"
] |
Autoranging PlotWidget without padding (pyqtgraph) | 38,795,508 | <p>I was searching for a half of day for this without luck. I have a PlotWidget that I want to autorange. Yet if it does, it has this "padding" (in other words the range is a bit larger then actual range). Do you know a way of avoiding this padding while keeping autoranging.</p>
| 0 | 2016-08-05T18:12:37Z | 38,804,586 | <p>The <code>autoRange</code> method actually has a padding parameter. By default this is <code>None</code> which means the padding is between 0.02 and 0.1 depending on the size of the ViewBox. See the docs <a href="http://www.pyqtgraph.org/documentation/graphicsItems/viewbox.html#pyqtgraph.ViewBox.autoRange" rel="nofo... | 0 | 2016-08-06T13:05:09Z | [
"python",
"pyqt",
"pyqtgraph"
] |
Performance between Python and Java drivers with OrientDB | 38,795,545 | <p>I want to develop a project that need a noSQL database. After searching a lot, I chose OrientDB. I want to make an API Rest that can connect to OrientDB. </p>
<p>Firstly, I wanted to use Flask to develop but I don't know if it's better to use Java native driver between Python binary driver to connect with database.... | 0 | 2016-08-05T18:15:11Z | 38,802,276 | <p>AFAIK on <em>remote</em> connection (with a standalone OrientDB server) performance would be the same.
The great advantage of using the Java native driver is the option to go embedded. If your deployment scenario allows it, you can avoid the standalone server and use OrientDB embedded into your Java application, av... | 0 | 2016-08-06T08:37:09Z | [
"java",
"python",
"performance",
"orientdb"
] |
Why does OSX fail on parsing the extras_require section of my setup.py file? | 38,795,583 | <p>In my <code>setup.py</code> file, I have the following:</p>
<pre><code>setup(
...
extras_require={
':python_version<="2.7"': [
'pydot>1.0',
],
':python_version>="3.5"': [
'pydot3k',
],
...
)
</code></pre>
<p>This works fine on Lin... | 0 | 2016-08-05T18:19:27Z | 38,803,004 | <p>The problem was solved by adding <code>- pip install --upgrade setuptools</code> to my <code>.travis.yml</code> file.</p>
| 0 | 2016-08-06T10:01:40Z | [
"python",
"osx",
"travis-ci",
"setup.py"
] |
Python crawler to get DOM info by using Selenium and PhantomJS | 38,795,628 | <p>I used <strong>Selenium</strong> and <strong>PhantomJS</strong> hoping to get data from a website which using javascript to build the DOM.</p>
<p>The simple code below works, but it's not always valid. I meant that most of time it would return an empty website which didn't execute the javascript. It could seldom ge... | -1 | 2016-08-05T18:23:18Z | 38,796,128 | <p>First of all, <code>driver = webdriver.PhantomJS</code> is not a correct way to initialize a selenium webdriver in Python, replace it with:</p>
<pre><code>driver = webdriver.PhantomJS()
</code></pre>
<p>The symptoms you are describing are similar to when you have the timing issues. <a href="http://selenium-python.... | 1 | 2016-08-05T18:59:00Z | [
"javascript",
"python",
"python-3.x",
"selenium",
"phantomjs"
] |
Pandas: Spliting cells in one column according to a character, then adding the part to other columns via a conditional? | 38,795,768 | <p>I was wondering if there's an optimal way to perform this sort of action. I have a column of file paths, we'll call <em>C Drive</em>, which contains paths like </p>
<pre><code>user\library\photos\item
</code></pre>
<p>This is a column in a dataframe, and the other columns are <em>Dir [1], Dir [2], ..., Dir [n], ... | 0 | 2016-08-05T18:33:39Z | 38,798,979 | <p>You can use the <code>split</code> function accessed by the <code>str</code> attribute of a Series to split your drive path into the constituent directories. Then convert the resulting Series of lists into a DataFrame. It can be done in one line, as follows:</p>
<pre><code>dir_df = pd.DataFrame(df['C Drive'].str.sp... | 0 | 2016-08-05T23:19:57Z | [
"python",
"pandas",
"dataframe"
] |
Read contents of files on s3 bucket without downloading | 38,795,783 | <p>I am quite new to aws and s3 so pardon if this looks like I haven't tried anything. I want to traverse the directories and files, read the files and retrieve specific lines from the publicly accessible s3 bucket: <code>s3://cgl-rnaseq-recompute-fixed/</code> without downloading it. I want to just be able perform bas... | 0 | 2016-08-05T18:34:40Z | 38,796,090 | <p><a href="http://boto.readthedocs.io/en/latest/s3_tut.html" rel="nofollow">http://boto.readthedocs.io/en/latest/s3_tut.html</a></p>
<pre><code>conn = boto.s3.connection.S3Connection(
aws_access_key_id='xxx',
aws_secret_access_key='yyy'
)
for key in conn.list(prefix='logs/*.log'):
print key
</cod... | 0 | 2016-08-05T18:56:47Z | [
"python",
"amazon-s3"
] |
python multiprocessing pool with expensive initialization | 38,795,826 | <p>Here is a complete simple working example</p>
<pre><code>import multiprocessing as mp
import time
import random
class Foo:
def __init__(self):
# some expensive set up function in the real code
self.x = 2
print('initializing')
def run(self, y):
time.sleep(random.random() / ... | 3 | 2016-08-05T18:37:34Z | 38,795,986 | <p>most obvious, lazy load</p>
<pre><code>_foo = None
def f(y):
global _foo
if not _foo:
_foo = Foo()
return _foo.run(y)
</code></pre>
| 1 | 2016-08-05T18:49:06Z | [
"python",
"python-multiprocessing",
"pool",
"object-initializers"
] |
python multiprocessing pool with expensive initialization | 38,795,826 | <p>Here is a complete simple working example</p>
<pre><code>import multiprocessing as mp
import time
import random
class Foo:
def __init__(self):
# some expensive set up function in the real code
self.x = 2
print('initializing')
def run(self, y):
time.sleep(random.random() / ... | 3 | 2016-08-05T18:37:34Z | 38,796,161 | <p>The intended way to deal with things like this is via the optional <code>initializer</code> and <code>initargs</code> arguments to the <code>Pool()</code> constructor. They exist precisely to give you a way to do stuff exactly once when a worker process is created. So, e.g., add:</p>
<pre><code>def init():
gl... | 2 | 2016-08-05T19:02:01Z | [
"python",
"python-multiprocessing",
"pool",
"object-initializers"
] |
Emulating bash's [ctrl]-l, **refreshing** | 38,795,864 | <p>I need a Python code snippet, that emulates Bash's clear-screen for <strong>refreshing</strong> the screen if it's messed up.</p>
<p>I need to use it in Bash, not in the Python interpreter.</p>
| -1 | 2016-08-05T18:40:08Z | 38,795,946 | <p>Here's a simple way to clear the terminal's screen in python:</p>
<pre><code>>>> import os
>>> os.system('clear')
</code></pre>
<p>And in bash, you simply have to type <code>clear</code> in the terminal.</p>
| 0 | 2016-08-05T18:46:01Z | [
"python",
"linux",
"bash",
"refresh",
"screen"
] |
Is it possible to increase the number of centroids in KMeans during fitting? | 38,795,912 | <p>I am attempting to use MiniBatchKMeans to stream NLP data in and cluster it, but have no way of determining how many clusters I need. What I would like to do is periodically take the silhouette score and if it drops below a certain threshold, increase the number of centroids. But as far as I can tell, <code>n_cluste... | 0 | 2016-08-05T18:43:11Z | 38,803,263 | <p>It is not a good idea to do this during optimization, because it changes the optimization procedure substantially. It will essentially reset the whole optimization. There are strategies such as bisecting k-means that try to learn the value of k during clustering, but they are a bit more tricky than increasing k by o... | 2 | 2016-08-06T10:29:55Z | [
"python",
"scikit-learn",
"cluster-analysis",
"k-means"
] |
How to send JSON data using SSL | 38,795,935 | <p>I'm trying to send JSON data using socket, but get this error</p>
<blockquote>
<p>b'HTTP/0.9 413 Request Entity Too Large\r\nServer:
inets/5.10.2\r\nDate: Fri, 05 Aug 2016 18:19:38 GMT\r\nContent-Type:
text/html\r\nContent-Length: 202\r\n\r\n'</p>
</blockquote>
<p>my code:</p>
<pre><code>def single_contract... | 2 | 2016-08-05T18:44:54Z | 38,796,064 | <p>You are sending too much data. You need to either decrease the size of what you are sending or, if you have control of the server, adjust it's settings to allow it to receive larger Https requests.</p>
<p><a href="http://cnedelcu.blogspot.com/2013/09/nginx-error-413-request-entity-too-large.html" rel="nofollow">ht... | 0 | 2016-08-05T18:54:44Z | [
"python",
"sockets",
"python-3.x",
"ssl"
] |
Why is this python generator function running correctly only once? | 38,796,024 | <p>This is almost certainly a result of my ignorance of how generators work, but I am completely lost.</p>
<p>If I interactively create the following generator:</p>
<pre><code>def neighborhood(iterable):
iterator = iter(iterable)
prev = None
item = next(iterator)
for post in iterator:
yield (... | 2 | 2016-08-05T18:52:27Z | 38,796,094 | <p>When you did</p>
<pre><code>for prev,item,next in ...
# ^^^^
</code></pre>
<p>you shadowed the built-in <code>next</code> function. The next time you try to use your generator, it fails because it gets your <code>next</code> variable instead of the function it needed.</p>
| 7 | 2016-08-05T18:57:02Z | [
"python",
"python-3.x",
"generator"
] |
Why is this python generator function running correctly only once? | 38,796,024 | <p>This is almost certainly a result of my ignorance of how generators work, but I am completely lost.</p>
<p>If I interactively create the following generator:</p>
<pre><code>def neighborhood(iterable):
iterator = iter(iterable)
prev = None
item = next(iterator)
for post in iterator:
yield (... | 2 | 2016-08-05T18:52:27Z | 38,796,095 | <p>It's because you're using a variable named <code>next</code> in your test code. Use a name that doesn't shadow the built-in function <code>next</code>.</p>
| 3 | 2016-08-05T18:57:08Z | [
"python",
"python-3.x",
"generator"
] |
Python Using Keyword and variable number of arguments in same function | 38,796,059 | <p>I am wondering if there is a way to do something like this in python 2.7.12</p>
<pre><code>def saveValues(file,*data,delim="|"):
buf=""
for d in data:
buf+=str(d) + delim
open(file,"w").write(buf[:-1])
</code></pre>
<p>So that I have the option to pass delim, or take the default.</p>
| 3 | 2016-08-05T18:54:23Z | 38,796,124 | <p>It's possible in python3. The python2 workaround is usually this:</p>
<pre><code>def saveValues(file, *data, **kwargs):
delim = kwargs.pop('delim', '|')
...
</code></pre>
| 7 | 2016-08-05T18:58:44Z | [
"python",
"python-2.7",
"function",
"arguments"
] |
efficiently merging tables on substrings, not perfect matches | 38,796,153 | <p>I want to merge two tables in R or Python, each with tens of thousands of rows. However, <strong>I won't be able to merge on perfect matches.</strong> I'm looking for cases when one key is a substring of another. The matching substring can contain multiple words. <strong>I'm looking for a solution that is faster... | -2 | 2016-08-05T19:01:20Z | 38,796,249 | <pre><code>library(tidyr)
library(dplyr)
df1 <- data.frame(
mealtime = c("breakfast","lunch","dinner","dinner"),
dish = c(
"cheese omelette",
"turkey sandwich",
"bean soup",
"something very long like this")
)
df2 <- read.table(textConnection(
'ingredient category
bean legume
beef ... | 0 | 2016-08-05T19:08:20Z | [
"python",
"string",
"optimization"
] |
efficiently merging tables on substrings, not perfect matches | 38,796,153 | <p>I want to merge two tables in R or Python, each with tens of thousands of rows. However, <strong>I won't be able to merge on perfect matches.</strong> I'm looking for cases when one key is a substring of another. The matching substring can contain multiple words. <strong>I'm looking for a solution that is faster... | -2 | 2016-08-05T19:01:20Z | 38,926,710 | <p>I am using your original post data.<br>
first split term <br>
second check the associated item in dictionary<br>
third combine together</p>
<pre><code>terms =["cheese omelette","turkey sandwich","bean soup",]
dictionary ={'turkey': 'meat', 'cheese': 'dairy', 'sandwich': 'bread', 'beef': 'meat', 'omelette': 'eggs',... | 1 | 2016-08-12T21:29:52Z | [
"python",
"string",
"optimization"
] |
Django form unittest with ChoiceField and MultipleChoiceField failing is_valid() | 38,796,191 | <p>I'm running into a small problem with writing a unit test for a Django form. I really just want to check the is_valid() method and have seen examples but my code isn't working and after a day or so of reading up on Google I've yet to find the answer I'm looking for. Below is the code for the forms.py and test_forms... | 0 | 2016-08-05T19:04:24Z | 38,796,529 | <p>You need to pass <code>result_list</code> and <code>band_list</code> when you construct your form.</p>
<pre><code># These aren't the actual choices you want, I'm just showing that
# choices should be a list of 2-tuples.
result_list = [('result1', 'result1'), ('result2', 'result2'), ...]
band_list = [('band1', 'band... | 2 | 2016-08-05T19:27:18Z | [
"python",
"django",
"forms",
"unit-testing",
"choicefield"
] |
ModelForm won't create instance of model | 38,796,217 | <p>I am trying to create a frontend form in my Django site that will allow users to add entries to my SQL database. </p>
<p><strong>But when I use the form nothing happens in my database. What am I doing wrong?</strong></p>
<p>I thought the right way would be to use the ModelForm technique.</p>
<p>My models looks li... | 0 | 2016-08-05T19:06:24Z | 38,796,365 | <p>You have to call the model form's <a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#the-save-method" rel="nofollow"><code>save()</code></a> method after checking that it's valid:</p>
<pre><code>def get_actor(request):
if request.method == 'POST':
form = ActorForm(request.POST)
... | 0 | 2016-08-05T19:16:35Z | [
"python",
"django",
"django-forms"
] |
How do I get a single piece of data from Quickbooks Online? | 38,796,225 | <p>I've got a client who uses Quickbooks Online for accounts, and he wants to be able to read data from it programmatically. We're using Clojure, so any solution in Java will work, or http gets etc can be made directly if necessary.</p>
<p>They've got what appears to be a nice RESTFUL interface to their stuff, and a j... | 0 | 2016-08-05T19:06:38Z | 38,808,492 | <p>This looks the best available documentation:</p>
<p><a href="https://developer.intuit.com/hub/blog/2016/04/25/quick-start-to-quickbooks-online-rest-api-with-oauth1-0" rel="nofollow">https://developer.intuit.com/hub/blog/2016/04/25/quick-start-to-quickbooks-online-rest-api-with-oauth1-0</a></p>
<p>It's a recent blo... | 0 | 2016-08-06T20:36:54Z | [
"java",
"python",
"clojure",
"quickbooks-online"
] |
Connecting a Tun to a socket | 38,796,252 | <p>I want to connect a Tun to a socket so that whatever data is stored in the Tun file will then end up being pushed out to a socket which will receive the data. I am struggling with the higher level conceptual understanding of how I am supposed to connect the socket and the Tun. Does the Tun get a dedicated socket tha... | 0 | 2016-08-05T19:08:32Z | 38,833,280 | <p>If I am understanding your problem, you should be able to write an application that connects to the tun device and also maintains another network socket. You will need some sort of multiplexing such as epoll or select. But, basically, whenever you see data on the tun interface, you can receive the data into a buffer... | 0 | 2016-08-08T15:34:47Z | [
"python",
"sockets",
"networking",
"tun"
] |
how to install hypothesis Python package? | 38,796,441 | <p>I'm using Wing IDE, how do I install hypothesis Python package to my computer?
I have already download the zip file, do I use command prompt to install it or there is an option in Wing IDE to do it?</p>
| 0 | 2016-08-05T19:20:58Z | 38,796,484 | <p><code>pip install hypothesis</code></p>
<p>Assuming you have pip.</p>
<p>If you want to install it from the downloaded package just open command prompt and <code>cd</code> to the directory where you downloaded it and do</p>
<p><code>python setup.py install</code></p>
| 1 | 2016-08-05T19:24:43Z | [
"python",
"wing-ide",
"python-packaging"
] |
how to install hypothesis Python package? | 38,796,441 | <p>I'm using Wing IDE, how do I install hypothesis Python package to my computer?
I have already download the zip file, do I use command prompt to install it or there is an option in Wing IDE to do it?</p>
| 0 | 2016-08-05T19:20:58Z | 38,796,568 | <p>As shakesbeer and hleggs wrote, and also by giving:</p>
<pre><code> easy_install hypothesis
</code></pre>
<p>hope this helps :)</p>
| 0 | 2016-08-05T19:29:53Z | [
"python",
"wing-ide",
"python-packaging"
] |
Python Unit Testing with Unordered Set for Tree Data Structure | 38,796,442 | <h2>Background</h2>
<p>I am trying to add unit tests for a tree data structure I am building (python 3). The tree structure uses sets (unordered) and I am struggling to find ways to test certain methods of my tree class.</p>
<h2>Example</h2>
<p>Given the diagramed tree...I have a method that will detach a node (say ... | 3 | 2016-08-05T19:21:04Z | 38,796,532 | <p>Test whether the method does the thing it's supposed to do. After the operation, has the correct node been replaced by one of its children? If so, great! If not, report a failure.</p>
<p>You don't need to assert that it's been replaced by any specific child.</p>
| 1 | 2016-08-05T19:27:34Z | [
"python",
"unit-testing",
"random",
"tree",
"unordered-set"
] |
Singly linked list is not reversing when using recursion | 38,796,550 | <p>I'm having trouble figuring out what's missing. I've taken a several looks at other solutions online, and those don't seem to work when I apply the differences. I've spent a good amount of time trying to debug. Here's my code:</p>
<pre><code>def recurse_reverse(self, curr, level):
print('-' * level, 'curr:', cu... | 0 | 2016-08-05T19:28:43Z | 38,797,106 | <p>There are two issues with your code. First if list contains more than one element you don't swap <code>_head.next</code>, after <code>recurse_reverse</code> it will still point to second element of the original list and thus the last two elements of reversed list form a loop.The second issue is what you don't swap <... | 1 | 2016-08-05T20:09:41Z | [
"python",
"recursion",
"linked-list",
"reverse"
] |
Django - UNIQUE constraint failed: auth_user.username | 38,796,713 | <p>I'm writing unit tests for a <code>Django REST Framework</code> app and using
<a href="https://factoryboy.readthedocs.io/en/latest/index.html" rel="nofollow"><code>factory_boy</code></a> to create my fake testing data. I'm getting the following error when I run my test: </p>
<pre><code>File "/usr/local/Cellar/pyth... | -1 | 2016-08-05T19:41:19Z | 38,796,820 | <p>Turns out I was calling the factory twice so both Users were getting <code>username = 'contributor'</code>. Simple fix is to not define the username inside the factory but to define it when you call the factory.</p>
| 0 | 2016-08-05T19:49:37Z | [
"python",
"django",
"django-rest-framework",
"factory-boy"
] |
Django - UNIQUE constraint failed: auth_user.username | 38,796,713 | <p>I'm writing unit tests for a <code>Django REST Framework</code> app and using
<a href="https://factoryboy.readthedocs.io/en/latest/index.html" rel="nofollow"><code>factory_boy</code></a> to create my fake testing data. I'm getting the following error when I run my test: </p>
<pre><code>File "/usr/local/Cellar/pyth... | -1 | 2016-08-05T19:41:19Z | 38,802,864 | <p>As stated in your response, the problem is that you're using a fixed value for a <code>unique=True</code> field.</p>
<p>One solution is to pass the <code>username</code> on each call to <code>UserFactory</code>; however, the goal of <code>factory_boy</code> is to avoid having to specify such fields unless the test ... | 0 | 2016-08-06T09:46:55Z | [
"python",
"django",
"django-rest-framework",
"factory-boy"
] |
How to figure out when k means converges for tf idf? | 38,796,898 | <p>I am fairly new with working with text data.</p>
<p>I have a data frame of about 300,000 unique product names and I am trying to use k means to cluster similar names together. I used sklearn's tfidfvectorizer to vectorize the names and convert to a tf-idf matrix.</p>
<p>After I transformed it to a sparse matrix I ... | 0 | 2016-08-05T19:55:29Z | 38,806,540 | <p>According to <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/cluster/k_means_.py#L814" rel="nofollow">the source</a> the attribute <code>n_iter_</code> should hold the number k-means iterations. If <code>n_iter_ < max_iter</code>, then the algorithm converged within the given tolerance.... | 1 | 2016-08-06T16:43:42Z | [
"python",
"scikit-learn",
"k-means",
"tf-idf",
"convergence"
] |
pytest unicode syntaxerror with '£' symbol | 38,796,927 | <p>I have a test file: <code>test_pytest.py</code>:</p>
<pre><code>def test_pytest():
s = '£'
assert True
</code></pre>
<p>Using pytest, I run it like this: <code>python -m pytest test_pytest.py</code></p>
<p>The result:</p>
<pre><code>> python -m pytest test_pytest.py
============================= test... | -1 | 2016-08-05T19:57:46Z | 38,802,021 | <p>Silly me, my Vim was saving the file with latin1 encoding instead of utf-8. Changing the encoding of the file to utf-8 fixed the problem. </p>
| 0 | 2016-08-06T08:08:12Z | [
"python",
"unit-testing",
"testing",
"py.test",
"python-3.5"
] |
Kivy Spinner Autoupdate | 38,796,943 | <p>I have a spinner in kivy that I cannot seem to get the "text_autoupdate" feature working. The documentation can be found here: <a href="https://kivy.org/docs/api-kivy.uix.spinner.html" rel="nofollow">https://kivy.org/docs/api-kivy.uix.spinner.html</a></p>
<p>My .py code: </p>
<pre><code>from kivy.app import App
fr... | 0 | 2016-08-05T19:58:33Z | 38,797,931 | <p>You forgot to define ports as ListProperty </p>
<p>Change:<br>
<code>ports = ["[None]"]</code></p>
<p>To:<br>
<code>ports = ListProperty(["[None]"])</code></p>
| 0 | 2016-08-05T21:21:34Z | [
"python",
"spinner",
"kivy"
] |
Python Convert Excel tabs to CSV files | 38,796,951 | <p>I've edited the post to reflect the changes recommended.</p>
<pre><code>def Excel2CSV(ExcelFile, Sheetname, CSVFile):
import xlrd
import csv
workbook = xlrd.open_workbook('C:\Users\aqureshi\Desktop\Programming\consolidateddataviewsyellowed.xlsx')
worksheet = workbook.sheet_by_name (ARC)
csvfile... | 1 | 2016-08-05T19:58:53Z | 38,797,455 | <p><strong>Response to edited code</strong></p>
<p><code>No module named xlrd</code> indicates that you have not installed the <code>xlrd</code> library. Bottom line, you need to install the xlrd module. Installing a module is an important skill which beginner python users must learn and it can be a little hairy if ... | 1 | 2016-08-05T20:38:57Z | [
"python",
"excel",
"csv",
"character-encoding",
"file-conversion"
] |
How to find the minimum element from two arrays in given time complexity in python | 38,797,001 | <p>I have 2 arrays A and B. I'm trying to find the minimum from the elements which are common in the arrays A and B.</p>
<p>Like , if <code>A = [1,3,2,1]</code> & <code>B = [4,2,5,3,2]</code>, so it should return <code>2</code> because it is the minimum element which comes in both A & B. My code below works fo... | -2 | 2016-08-05T20:01:45Z | 38,797,068 | <p>Itertools chain aproach:</p>
<pre><code>>>> import itertools
>>> A = [1,3,2,1]
>>> B = [4,2,5,3,2]
>>> min(x for x in itertools.chain(A, B) if x in A and x in B)
2
</code></pre>
| 1 | 2016-08-05T20:07:20Z | [
"python",
"time-complexity",
"minimum"
] |
How to find the minimum element from two arrays in given time complexity in python | 38,797,001 | <p>I have 2 arrays A and B. I'm trying to find the minimum from the elements which are common in the arrays A and B.</p>
<p>Like , if <code>A = [1,3,2,1]</code> & <code>B = [4,2,5,3,2]</code>, so it should return <code>2</code> because it is the minimum element which comes in both A & B. My code below works fo... | -2 | 2016-08-05T20:01:45Z | 38,797,073 | <pre><code>a = [1,2,3,4,5,6]
b = [3,5,7,9]
shared = (set(a).intersection(b))
shared = sorted(shared)
print shared[0]
</code></pre>
<p>Returns <code>3</code></p>
| 2 | 2016-08-05T20:07:34Z | [
"python",
"time-complexity",
"minimum"
] |
How to find the minimum element from two arrays in given time complexity in python | 38,797,001 | <p>I have 2 arrays A and B. I'm trying to find the minimum from the elements which are common in the arrays A and B.</p>
<p>Like , if <code>A = [1,3,2,1]</code> & <code>B = [4,2,5,3,2]</code>, so it should return <code>2</code> because it is the minimum element which comes in both A & B. My code below works fo... | -2 | 2016-08-05T20:01:45Z | 38,797,090 | <p>I'd suggest using <code>set</code>s because it would be much faster due to its implementation. You just need to use <code>min</code> function over the intersection of two lists converted to <code>set</code>s. It's too easy, performant and doesn't require any sorting.</p>
<pre><code>min(set(A) & set(B))
</code><... | 0 | 2016-08-05T20:08:30Z | [
"python",
"time-complexity",
"minimum"
] |
How to find the minimum element from two arrays in given time complexity in python | 38,797,001 | <p>I have 2 arrays A and B. I'm trying to find the minimum from the elements which are common in the arrays A and B.</p>
<p>Like , if <code>A = [1,3,2,1]</code> & <code>B = [4,2,5,3,2]</code>, so it should return <code>2</code> because it is the minimum element which comes in both A & B. My code below works fo... | -2 | 2016-08-05T20:01:45Z | 38,797,091 | <p>You're throwing in sort there which you don't really need, find the intersection of the two using a set, then take the min...</p>
<pre><code>>>> A = [1,3,2,1]
>>> B = [4,2,5,3,2]
>>> min(set(A).intersection(B))
2
</code></pre>
<p>Which would make your function:</p>
<pre><code>def findMi... | 5 | 2016-08-05T20:08:30Z | [
"python",
"time-complexity",
"minimum"
] |
How to find the minimum element from two arrays in given time complexity in python | 38,797,001 | <p>I have 2 arrays A and B. I'm trying to find the minimum from the elements which are common in the arrays A and B.</p>
<p>Like , if <code>A = [1,3,2,1]</code> & <code>B = [4,2,5,3,2]</code>, so it should return <code>2</code> because it is the minimum element which comes in both A & B. My code below works fo... | -2 | 2016-08-05T20:01:45Z | 38,797,617 | <p>In case there's a big difference in size of the arrays faster way is to create a <code>set</code> out of smaller one for the <code>intersection</code>:</p>
<pre><code>def find(a, b):
small, large = sorted([a, b], key=len)
return min(set(small).intersection(large), default=-1)
</code></pre>
<p>Comparison wi... | 0 | 2016-08-05T20:53:09Z | [
"python",
"time-complexity",
"minimum"
] |
How to compare list and dictionary values and assign a variable | 38,797,037 | <p>I have a list with a certain amount of winners from fights, entered by the user e.g. <code>winners = ['Hunt', 'Nunes', 'Cormier']</code></p>
<p>I then have a dictionary with each player's correct guess as values and their names as keys and my program then compares the list of winners with the values for each key an... | 0 | 2016-08-05T20:04:50Z | 38,797,217 | <p>The following calculates the number of <em>correct</em> guess' a player in the <code>players</code> dictionary has made. If so you can do this with the <code>intersection()</code> of a <code>list</code> with a <code>set</code> of <code>winners</code>. </p>
<p>To add to this, a list of the winners' names is added to... | 1 | 2016-08-05T20:19:03Z | [
"python",
"list",
"dictionary",
"comparison"
] |
Scroll tkinter ttk Entry text to the End in Python | 38,797,116 | <p>I am trying to create a GUI form using Python tkinter. For a ttk Entry widget, I want to set a default text. I do that using the insert() as shown below-</p>
<pre><code>from tkinter import *
from tkinter import ttk
root = Tk()
e = ttk.Entry(root, width=20)
e.pack()
e.insert(0, 'text greater than width of the widget... | 2 | 2016-08-05T20:10:38Z | 38,797,670 | <p>You can call the <code>xview</code> method to scroll a given index into view:</p>
<pre><code>e.xview("end")
</code></pre>
| 1 | 2016-08-05T20:58:08Z | [
"python",
"tkinter"
] |
Django Storages Boto Bad Digest | 38,797,175 | <p>I'm using S3 file storage through django-storages boto storage on Python 3. When I try to upload a file, I get this error:</p>
<pre><code>boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>BadDigest</Code>
<Message>The ... | 0 | 2016-08-05T20:15:35Z | 38,797,176 | <p>See this relevant boto issue: <a href="https://github.com/boto/boto/issues/2868" rel="nofollow">https://github.com/boto/boto/issues/2868</a></p>
<p>Boto has some problems with string encodings in Python3. If you know the encoding, you Using <code>response.content</code> instead of <code>response.text</code> fixes ... | 0 | 2016-08-05T20:15:35Z | [
"python",
"django",
"python-3.x",
"amazon-s3",
"django-storage"
] |
running python files from ipython and passing an object in as the argument | 38,797,177 | <p><strong>The overall goal</strong></p>
<p>I am trying to debug functions that I have written to analyze large data files. It takes too long to read the files into pandas dataframes for each debugging run. And so I am running an ipython console where I want to read the data in, then debug my functions. If I end the d... | 0 | 2016-08-05T20:15:40Z | 38,797,284 | <p>Just use <a href="http://ipython.org/ipython-doc/rel-1.1.0/interactive/reference.html" rel="nofollow">IPython.embed()</a> where you're currently using <code>code.InteractiveConsole(globals()).interact('')</code>.</p>
<p>Make sure you're importing IPython before you do that, though:</p>
<pre><code>import IPython
# ... | 0 | 2016-08-05T20:24:55Z | [
"python",
"debugging",
"pandas",
"ipython"
] |
hackerrank new year chaos code optimization | 38,797,194 | <p>I'm trying to optimize my solution for Hackerranks's 'New Year Chaos' problem. The gist of the problem goes like this (link to the problem <a href="https://www.hackerrank.com/challenges/new-year-chaos" rel="nofollow">here</a>): there's a queue of n people, labeled 1 through n, and each person can bribe the person di... | 0 | 2016-08-05T20:17:08Z | 39,414,942 | <p>There are two problems in your code.</p>
<p>First, you should iterate the given array from end to the beginning, not the other way around. The reason is that if you iterate from the beginning, you need to iterate the whole array in the inner loop. But if you iterate from the last element, you just need to check lef... | 0 | 2016-09-09T15:23:40Z | [
"python",
"optimization"
] |
How to turn off logging for favicon and robots in nginx for flask (python) apps | 38,797,219 | <p>I'm trying to find a way to turn off logging for favicon.ico and robots.txt in my <strong>NGINX</strong> web server powering a <strong>Flask (Python)</strong> app through <strong>uWSGI</strong>.</p>
<p>So, the first part of my nginx config is:</p>
<pre><code>location / {
try_files $uri @app;
}
location @app {... | 0 | 2016-08-05T20:19:11Z | 38,797,743 | <p><code>location</code> sections are not combined, try:</p>
<pre><code>location = /favicon.ico {
access_log off;
log_not_found off;
try_files $uri @app;
}
location = /robots.txt {
access_log off;
log_not_found off;
try_files $uri @app;
}
</code></pre>
| 0 | 2016-08-05T21:04:14Z | [
"python",
"nginx",
"flask",
"uwsgi"
] |
get first and last values in a groupby | 38,797,271 | <p>I have a dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(np.arange(20).reshape(10, -1),
[['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd'],
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']],
['X', 'Y'])
</code></pre>
<p>How do I get the first and... | 7 | 2016-08-05T20:23:54Z | 38,797,283 | <h3>Option 1</h3>
<pre><code>def first_last(df):
return df.ix[[0, -1]]
df.groupby(level=0, group_keys=False).apply(first_last)
</code></pre>
<p><a href="http://i.stack.imgur.com/PBecd.png" rel="nofollow"><img src="http://i.stack.imgur.com/PBecd.png" alt="enter image description here"></a></p>
<hr>
<h3>Option 2... | 8 | 2016-08-05T20:24:39Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Looping through Wagtail Streamfield Items | 38,797,281 | <p>I'm trying to create an index page containing links to multiple photo galleries in Wagtail. The GalleryIndexPage model looks like this:</p>
<pre><code>class GalleryIndexPage(Page):
subpage_types = ['home.GalleryPage']
gallery_thumb = StreamField ([
('cover_photo', ImageChooserBlock()),
('title', bl... | 0 | 2016-08-05T20:24:30Z | 38,797,557 | <p>It seems like what you want is a single gallery_item block that consists of an image, title, and link. You can do this by creating your own block type out of simpler block types. See <a href="http://docs.wagtail.io/en/v1.5.3/topics/streamfield.html#structural-block-types" rel="nofollow">http://docs.wagtail.io/en/v1.... | 0 | 2016-08-05T20:47:58Z | [
"python",
"django",
"templates",
"wagtail",
"wagtail-streamfield"
] |
Looping through Wagtail Streamfield Items | 38,797,281 | <p>I'm trying to create an index page containing links to multiple photo galleries in Wagtail. The GalleryIndexPage model looks like this:</p>
<pre><code>class GalleryIndexPage(Page):
subpage_types = ['home.GalleryPage']
gallery_thumb = StreamField ([
('cover_photo', ImageChooserBlock()),
('title', bl... | 0 | 2016-08-05T20:24:30Z | 38,833,620 | <p>I was able to access the values of the StructBlock in my template using this code: </p>
<pre><code><div class="photo-gallery">
{% for block in self.gallery %}
<div class="gallery-item">
<div class="thumb">
{% image block.value.cover_photo fill-200x150 %}
</div>
<div class="title... | 0 | 2016-08-08T15:53:24Z | [
"python",
"django",
"templates",
"wagtail",
"wagtail-streamfield"
] |
Openpyxl 2.3.2 Change Tab Color/Fit To Page Properties? | 38,797,468 | <p>I am trying to modify an excel spreadsheet to alter the colors of the tabs using Openpyxl 2.3.2 (using Anaconda), but can't seem to get the code to work. I am using the following code, where bdws is a worksheet already in the workbook, and bdws2 is a worksheet I added later. </p>
<p>I can't get either of the sheets... | 0 | 2016-08-05T20:40:14Z | 39,001,045 | <p>You just need to capitalize your Color :)</p>
<pre><code>bdws.sheet_properties.tabColor ='FFFF00'
bdws.sheet_properties.pageSetUpPr.fitToPage = True
bdws2.sheet_properties.tabColor = 'FF00FF'
bdws2.sheet_properties.pageSetUpPr.fitToPage = True
</code></pre>
<p>should do it for you.</p>
| 1 | 2016-08-17T15:44:57Z | [
"python",
"openpyxl"
] |
un-slicing numpy arrays | 38,797,494 | <p>Given a sliced numpy array as follows:</p>
<pre><code>b = [a[..., i] for i in a.shape[-1]]
</code></pre>
<p>What is the most simple way I can recreate <code>a</code> from <code>b</code>?</p>
<p>Something like:</p>
<pre><code>for i in range(a.shape[-1]):
c[..., i] = b[i]
</code></pre>
| 0 | 2016-08-05T20:42:29Z | 38,797,744 | <p>Instead of that list comprehension, your original operation should have been</p>
<pre><code>b = numpy.rollaxis(a, axis=-1)
</code></pre>
<p>which produces a view of <code>a</code> as a new array instead of a list of arrays.</p>
<p>The reverse operation is</p>
<pre><code>c = numpy.rollaxis(b, axis=0, start=b.ndim... | 1 | 2016-08-05T21:04:22Z | [
"python",
"numpy"
] |
TypeError: 'NoneType' does not support the buffer interface: when Transforming XML using XSLT | 38,797,546 | <p>Related to <a href="http://stackoverflow.com/questions/38248286/changing-loop-to-organize-and-reduce-xml-output">earlier question</a>, I want to thank @Parfait for helping me develop an XSLT foundation for my project with the current XSLT code being used. However I am getting an error when I run the python Module it... | 2 | 2016-08-05T20:47:00Z | 38,798,481 | <p>Two issues in XML emerge affecting the XSLT transformation: </p>
<ol>
<li>An undeclared namespace prefix (<code>xmlns="place2"</code>) where the <em>xmlns</em> special attribute in header does not have a colon separated identifier. Therefore, XSLT must declare a prefix.</li>
<li>Additional element levels where pare... | 1 | 2016-08-05T22:19:18Z | [
"python",
"xml",
"xslt",
"xpath",
"nonetype"
] |
if-if-else and if-elif-else statement | 38,797,578 | <p>Why is the 'else' statement getting printed even if a correct choice is picked? </p>
<pre><code> ch=0
print"Do you need Ice-Cream?"
ans=raw_input()
if ans=='y':
print"Pick a flavor"
ch=raw_input() # ch is a string
if ch=='1':
print"Vanilla"
if ch=='2':
... | -2 | 2016-08-05T20:49:17Z | 38,797,592 | <p>Because the if-statement checking "y" and the second if-statement checking "n" are two different. The else is only connected to the second if-statement with the "n"-check. You want to have the outermost statements like</p>
<pre><code>if "y":
....
elif "n":
....
else:
....
</code></pre>
| 5 | 2016-08-05T20:51:01Z | [
"python",
"if-statement"
] |
if-if-else and if-elif-else statement | 38,797,578 | <p>Why is the 'else' statement getting printed even if a correct choice is picked? </p>
<pre><code> ch=0
print"Do you need Ice-Cream?"
ans=raw_input()
if ans=='y':
print"Pick a flavor"
ch=raw_input() # ch is a string
if ch=='1':
print"Vanilla"
if ch=='2':
... | -2 | 2016-08-05T20:49:17Z | 38,797,597 | <p><code>ans</code> isn't <code>'n'</code> so the <code>else</code> clause fires. You probably want an <code>elif</code>:</p>
<pre><code>if ans == 'y':
...
elif ans == 'n':
...
else:
...
</code></pre>
| 1 | 2016-08-05T20:51:23Z | [
"python",
"if-statement"
] |
if-if-else and if-elif-else statement | 38,797,578 | <p>Why is the 'else' statement getting printed even if a correct choice is picked? </p>
<pre><code> ch=0
print"Do you need Ice-Cream?"
ans=raw_input()
if ans=='y':
print"Pick a flavor"
ch=raw_input() # ch is a string
if ch=='1':
print"Vanilla"
if ch=='2':
... | -2 | 2016-08-05T20:49:17Z | 38,797,605 | <p>It appears that you're conflating your series of <code>if</code>s with a series of <code>if</code>-<code>elifs</code>. </p>
<p>Note that this:</p>
<pre><code>if cond0:
...
if cond1:
...
else:
bar()
</code></pre>
<p>is <em>not</em> the same as:</p>
<pre><code>if cond0:
...
elif cond1:
...
else... | 2 | 2016-08-05T20:52:00Z | [
"python",
"if-statement"
] |
if-if-else and if-elif-else statement | 38,797,578 | <p>Why is the 'else' statement getting printed even if a correct choice is picked? </p>
<pre><code> ch=0
print"Do you need Ice-Cream?"
ans=raw_input()
if ans=='y':
print"Pick a flavor"
ch=raw_input() # ch is a string
if ch=='1':
print"Vanilla"
if ch=='2':
... | -2 | 2016-08-05T20:49:17Z | 38,797,614 | <p>The <code>else</code> in this chunk of code is only referring to the <code>if ans=='n'</code>.</p>
<p>It's not taking into account your first if statement. You're going to want to change it to this</p>
<pre><code>elif ans=='n':
print"Good, you can go!"
else:
print"wrong choice"
</code></pre>
| 1 | 2016-08-05T20:52:45Z | [
"python",
"if-statement"
] |
if-if-else and if-elif-else statement | 38,797,578 | <p>Why is the 'else' statement getting printed even if a correct choice is picked? </p>
<pre><code> ch=0
print"Do you need Ice-Cream?"
ans=raw_input()
if ans=='y':
print"Pick a flavor"
ch=raw_input() # ch is a string
if ch=='1':
print"Vanilla"
if ch=='2':
... | -2 | 2016-08-05T20:49:17Z | 38,797,798 | <p>You have two conditions not one.</p>
<ol>
<li><p>The first condition checks <code>ans</code> against <code>'y'</code>.</p>
<p>If <code>ans</code> is <code>'y'</code> the user gets to input an integer 1-8 and the appropriate string will be printed to the console. Processing then moves to the second condition (#2).<... | 0 | 2016-08-05T21:09:24Z | [
"python",
"if-statement"
] |
How to host flower on a remote machine that can also be accessed over the internet | 38,797,696 | <p>I am trying to run <code>flower</code> on a remote ubuntu server. However, I am unsure on what address/port to run it on so that other people can login (I have the basic auth set up) and check their <code>celery</code> workers. The ubuntu server is actually an EC2 instance, so am I supposed to use its private or pub... | -1 | 2016-08-05T20:59:56Z | 38,797,858 | <p>Flower runs on 5555 by default- which port are you running it on? The private IP is only available if the requests are coming from INSIDE your amazon network, so probably public.</p>
<p>So, if my guesses are right, you want to create an AWS security rule allowing traffic from "anywhere" to port 5555 and apply that... | 1 | 2016-08-05T21:15:45Z | [
"python",
"celery",
"flower"
] |
Algorithm to match arrays of occurrences by time | 38,797,806 | <p>Let's say that there's a "master" array of times with these values:</p>
<pre><code>master = [1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]
</code></pre>
<p>I want to find the most "compatible" array among several candidates:</p>
<pre><code>candidates = [
[0.01, 0.48, 1.03, 1.17, 1.5],
[1.25, 1.4, 1.5, ... | 1 | 2016-08-05T21:10:02Z | 38,798,544 | <p>One way would be to create those sliding 1D arrays as a stacked 2D array with <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> and then get the distances against the <code>2D</code> array with <a href="http://docs.scipy.org/doc/scipy-0.16.1/referenc... | 1 | 2016-08-05T22:28:12Z | [
"python",
"pandas",
"numpy",
"pattern-matching"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.