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 |
|---|---|---|---|---|---|---|---|---|---|
Using variable inside setUpClass (class method) - unittest python | 39,988,152 | <p>I would like to use a variable which I initialize in the subclass to be used in the setUpClass of parent class , here is the code snippet below:</p>
<pre><code>class BaseTest(unittest.TestCase):
def __init__(cls, arg):
unittest.TestCase.__init__(cls, arg)
@classmethod
def setUpClass(cls):
... | 0 | 2016-10-11T23:10:45Z | 39,988,745 | <p>You need to set <code>cls.param</code> <em>before</em> you call <code>BaseTest.__init__(cls, arg)</code>.</p>
| 0 | 2016-10-12T00:27:16Z | [
"python",
"python-2.7",
"unit-testing",
"testing",
"python-unittest"
] |
How to close an HDF5 using low level Python API? | 39,988,211 | <p>I was able to modify the cache settings of an HDF5 file by combining both the high and low level Python h5py API as defined in the following Stack Overflow question: <a href="http://stackoverflow.com/questions/14653259/how-to-set-cache-settings-while-using-h5py-high-level-interface/14656421?noredirect=1#comment67138... | 1 | 2016-10-11T23:16:47Z | 39,989,519 | <p>I think you are looking for .close()</p>
<pre><code>f.close()
</code></pre>
<p>Although looking closer, I'm not sure why contextlib.closing(...) didn't work.</p>
<p>I edited the line involving contextlib to be:</p>
<pre><code>with contextlib.closing(h5py.File(filename, fapl=propfaid)) as fid:
</code></pre>
<p>a... | 0 | 2016-10-12T02:20:12Z | [
"python",
"anaconda",
"hdf5",
"h5py"
] |
Searching through a file in Python | 39,988,223 | <p>Say that I have a file of restaurant names and that I need to search through said file and find a particular string like "Italian". How would the code look if I searched the file for the string and print out the number of restaurants with the same string?</p>
<pre><code>f = open("/home/ubuntu/ipynb/NYU_Notes/2-Intr... | 0 | 2016-10-11T23:18:33Z | 39,988,280 | <p>You input the file as a string.<br/>
Then use the count method of strings.<br/>
Code:</p>
<pre><code>#Let the file be taken as a string in s1
print s1.count("italian")
</code></pre>
| -1 | 2016-10-11T23:26:15Z | [
"python",
"file"
] |
Searching through a file in Python | 39,988,223 | <p>Say that I have a file of restaurant names and that I need to search through said file and find a particular string like "Italian". How would the code look if I searched the file for the string and print out the number of restaurants with the same string?</p>
<pre><code>f = open("/home/ubuntu/ipynb/NYU_Notes/2-Intr... | 0 | 2016-10-11T23:18:33Z | 39,988,411 | <p>You could count all the words using a Counter dict and then do lookups for certain words:</p>
<pre><code>from collections import Counter
from string import punctuation
f_name = "/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt"
with open(f_name) as f:
# sum(1 for _ in f) ->... | 2 | 2016-10-11T23:41:44Z | [
"python",
"file"
] |
python figure which properties belong to the child class | 39,988,258 | <p>I have a python class hierarchy as follows:</p>
<pre><code>class A:
def __init__(self):
self.a = 1
self.b = 2
class B(A):
def __init__(self):
super(B, self).__init__()
self.c = 3
</code></pre>
<p>Now when I do something like:</p>
<pre><code>obj = B()
obj.__dict__
</code></... | 2 | 2016-10-11T23:22:39Z | 39,988,555 | <p>For your simple example, you could get the difference in the dict items:</p>
<pre><code>print(obj.__dict__.items() - A().__dict__.items())
</code></pre>
<p>I suppose we should at least to it without knowing the name of the parent class:</p>
<pre><code> print(obj.__dict__.items() - obj.__class__.__bases__[0]().__d... | 2 | 2016-10-12T00:01:15Z | [
"python",
"class",
"python-3.x"
] |
(Python) Can I store the functions themselves, but not their value, in a list | 39,988,379 | <p>As you can see from the code below, I'm adding a series of functions to a list.
The result is that each function gets ran and the returned value is added to the list. </p>
<pre><code>foo_list = []
foo_list.append(bar.func1(100))
foo_list.append(bar.func2([7,7,7,9]))
foo_list.append(bar.func3(r'C:\Users\user\desktop... | 4 | 2016-10-11T23:38:26Z | 39,988,445 | <p>Yeah just use lambda:</p>
<pre><code>foo_list = []
foo_list.append(lambda: bar.func1(100))
foo_list.append(lambda: bar.func2([7,7,7,9]))
foo_list.append(lambda: bar.func3(r'C:\Users\user\desktop\output'))
for foo in foo_list:
print(foo())
</code></pre>
| 4 | 2016-10-11T23:45:20Z | [
"python",
"list"
] |
How to call pypdfocr functions to use them in a python script? | 39,988,381 | <p>Recently I downloaded <a href="https://github.com/virantha/pypdfocr" rel="nofollow">pypdfocr</a>, however, in the documentation there are no examples of how to call pypdfocr as a library, could anybody help me to call it just to convert a single file?. I just found a terminal command:</p>
<pre><code>$ pypdfocr file... | 0 | 2016-10-11T23:38:28Z | 39,989,237 | <p>If you're looking for the source code, it's normally under the directory site-package of your python installation. What's more, if you're using a IDE (i.e. Pycharm), it would help you find the directory and file. This is extremly useful to find class as well and show you how you can instantiate it, for example :
<... | 1 | 2016-10-12T01:38:41Z | [
"python",
"python-2.7",
"python-3.x",
"pdfbox"
] |
Gevent: Using two queues with two consumers without blocking each other at the same time | 39,988,398 | <p>I have the problem that I need to write values generated by a consumer to disk. I do not want to open a new instance of a file to write every time, so I thought to use a second queue and a other consumer to write to disk from a singe Greenlet. The problem with my code is that the second queue does not get consumed a... | 0 | 2016-10-11T23:40:22Z | 40,020,322 | <p>In general, that approach should work fine. There are some problems with this specific code, though:</p>
<ul>
<li><p>Calling <code>time.sleep</code> will cause all greenlets to block. You either need to call <code>gevent.sleep</code> or monkey-patch the process in order to have just one greenlet block (I see <code>... | 0 | 2016-10-13T11:56:01Z | [
"python",
"multithreading",
"queue",
"gevent",
"greenlets"
] |
Can't figure out what's wrong in Pygame app | 39,988,416 | <p>I'm writing this time reaction test. It is supposed to display the text, wait for a key stroke and start the trials, appending the resulting measure to the file. But it just displays the text and freezes. Damn. I would be very grateful if you could help me point out the issue</p>
<pre><code>import pygame
import ran... | 0 | 2016-10-11T23:42:12Z | 39,988,512 | <p>You need <code>=</code> instead of <code>==</code> in code</p>
<pre><code>if event.type == pygame.KEYDOWN:
start == True # <--- need `=` instead of `==`
</code></pre>
| 1 | 2016-10-11T23:54:30Z | [
"python",
"pygame",
"tr"
] |
Can't figure out what's wrong in Pygame app | 39,988,416 | <p>I'm writing this time reaction test. It is supposed to display the text, wait for a key stroke and start the trials, appending the resulting measure to the file. But it just displays the text and freezes. Damn. I would be very grateful if you could help me point out the issue</p>
<pre><code>import pygame
import ran... | 0 | 2016-10-11T23:42:12Z | 39,989,158 | <pre><code>while True:
start = False
</code></pre>
<p>This is an infinite loop.</p>
| 0 | 2016-10-12T01:28:04Z | [
"python",
"pygame",
"tr"
] |
Converting url encode data from curl to json object in python using requests | 39,988,480 | <p>What is the best way to convert the below curl post into python request using the requests module:</p>
<pre><code>curl -X POST https://api.google.com/gmail --data-urlencode json='{"user": [{"message":"abc123", "subject":"helloworld"}]}'
</code></pre>
<p>I tried using python requests as below, but it didn't work: <... | 0 | 2016-10-11T23:49:17Z | 39,988,758 | <p>As the comment mentioned, you should put your <code>url</code> variable string in quotes <code>""</code> first.</p>
<p>Otherwise, your question is not clear. What errors are being thrown and/or behavior is happening?</p>
<p><a href="http://stackoverflow.com/questions/17936555/how-to-construct-the-curl-command-from... | 0 | 2016-10-12T00:31:00Z | [
"python",
"http-post",
"python-requests"
] |
Find local non-loopback ip address in Python | 39,988,525 | <p>How can I find a list of local non-loopback IP addresses in Python (and stay platform-independent)?</p>
| 0 | 2016-10-11T23:56:51Z | 39,988,526 | <p>The <a href="https://pypi.python.org/pypi/netifaces" rel="nofollow">netifaces</a> package provides a platform-independent way of getting network interface and address info. The <a href="https://pypi.python.org/pypi/ipaddress" rel="nofollow">ipaddress</a> package (standard in Python3, external in Python2) provides a ... | 0 | 2016-10-11T23:56:51Z | [
"python"
] |
HTTP Error 400 Bad Request (Other similar questions aren't helping me) | 39,988,554 | <p>None of the other similarly names questions have solved my problem.</p>
<p>Why am I getting this error? I copied and pasted this example code from google's github.</p>
<pre><code>import pprint
from googleapiclient.discovery import build
def main():
# Build a service object for interacting with the API. Visit
... | 2 | 2016-10-12T00:00:54Z | 39,988,664 | <p>I tried to access that <a href="https://www.googleapis.com/customsearch/v1?q=lectures&alt=json&cx=017576662512468239146%3Aomuauf_lfve&key=AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0" rel="nofollow">bad URL</a> and is says that the reason is "keyExpired". Also the code you put here includes the following docu... | 1 | 2016-10-12T00:16:43Z | [
"python",
"google-api",
"google-api-python-client"
] |
How to pass through a list of queries to a pandas dataframe, and output the list of results? | 39,988,589 | <p>When selecting rows whose column value <code>column_name</code> equals a scalar, <code>some_value</code>, we use <code>==:</code></p>
<pre><code>df.loc[df['column_name'] == some_value]
</code></pre>
<p>or use <code>.query()</code> </p>
<pre><code>df.query('column_name == some_value')
</code></pre>
<p>In a concre... | 5 | 2016-10-12T00:06:20Z | 39,989,023 | <p>The best way to deal with this is by indexing into the rows using a Boolean series as you would in R.</p>
<p>Using your df as an example,</p>
<pre><code>In [5]: df.Col1 == "what"
Out[5]:
0 True
1 False
2 False
3 False
4 False
5 False
6 False
Name: Col1, dtype: bool
In [6]: df[df.Col1 == "wha... | 1 | 2016-10-12T01:09:00Z | [
"python",
"python-3.x",
"pandas",
"dataframe"
] |
How to pass through a list of queries to a pandas dataframe, and output the list of results? | 39,988,589 | <p>When selecting rows whose column value <code>column_name</code> equals a scalar, <code>some_value</code>, we use <code>==:</code></p>
<pre><code>df.loc[df['column_name'] == some_value]
</code></pre>
<p>or use <code>.query()</code> </p>
<pre><code>df.query('column_name == some_value')
</code></pre>
<p>In a concre... | 5 | 2016-10-12T00:06:20Z | 40,004,375 | <p>If I understood your question correctly you can do it either using boolean indexing as <a href="http://stackoverflow.com/a/39989023/5741205">@uhjish has already shown in his answer</a> or using <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-query-method-experimental" rel="nofollow">query()</a... | 1 | 2016-10-12T17:03:49Z | [
"python",
"python-3.x",
"pandas",
"dataframe"
] |
Running Fortran executable within Python script | 39,988,621 | <p>I am writing a Python script with the following objectives:</p>
<ol>
<li>Starting from current working directory, change directory to child directory 'A'</li>
<li>Make slight adjustments to a fort.4 file</li>
<li>Run a Fortran binary file (the syntax of which is <code>../../../../</code> continuing until I hit the ... | 3 | 2016-10-12T00:09:33Z | 39,988,971 | <p>Ok so there is a few important things here, first we need to be able to manage our cwd, for that we will use the os module </p>
<pre><code>import os
</code></pre>
<p>whenever a method operates on a folder it is important to change directories into the folder and back to the parent folder. This can also be achieved... | 0 | 2016-10-12T01:03:05Z | [
"python",
"fortran"
] |
Global connection to 3rd party api Flask | 39,988,650 | <p>I have a Flask app running on Heroku that connects to the Google Maps API during a request. Something like this:</p>
<pre><code>client = geocoders.GoogleV3(
client_id=self.config['GM_CLIENT_ID'],
secret_key=self.config['GM_SECRET_KEY']
)
client.do_geocoding(...)
</code></pre>
<p>Ri... | 2 | 2016-10-12T00:14:43Z | 39,991,524 | <p>Turns out it's as simple as storing the client instance in a global variable.</p>
| 0 | 2016-10-12T06:05:20Z | [
"python",
"flask"
] |
Strange NaN values for loss function (MLP) in TensorFlow | 39,988,687 | <p>I hope you can help me. I'm implementing a small multilayer perceptron using <strong>TensorFlow</strong> and a few tutorials I found on the internet. The problem is that the net is able to learn something, and by this I mean that I am able to somehow optimize the value of the training error and get a decent accuracy... | 2 | 2016-10-12T00:19:31Z | 40,043,524 | <p>I'll post the solution here just in case someone gets stuck in a similar way. If you see that plot very carefully, all of the NaN values (the triangles) come on a regular basis, like if at the end of every loop something causes the output of the loss function to just go NaN.
The problem is that, at every loop, I wa... | 0 | 2016-10-14T12:46:02Z | [
"python",
"machine-learning",
"tensorflow",
"deep-learning",
"tensorboard"
] |
How should I enforce permission checking when file is reached/downloaded in Django? | 39,988,697 | <p>I don't know this is a typical thing to do in web application, but what we achieve is that, let's say we have a Person model, inside this model, we have a <code>FileField</code> stores user's photo:</p>
<pre><code>class Person(models.Model):
photo = models.FileField(upload_to='Person_photo')
</code></pre>
<p>W... | 2 | 2016-10-12T00:21:50Z | 39,990,827 | <p>You can define view for this</p>
<p><strong>view.py</strong></p>
<pre><code>from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from appname.models import Person
@login_required
def show_photo(request):
person = get_obj... | 1 | 2016-10-12T05:00:22Z | [
"python",
"django"
] |
How to *not* create an instance | 39,988,779 | <p>I would like to avoid the creation of an instance if the arguments do not match the expected values.<br>
I.e. in short: </p>
<pre><code>#!/usr/bin/env python3
class Test(object):
def __init__(self, reallydoit = True):
if reallydoit:
self.done = True
else:
return None
m... | 2 | 2016-10-12T00:34:44Z | 39,988,807 | <p>Just <a href="https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement" rel="nofollow">raise</a> an exception in the <a href="https://docs.python.org/3/reference/datamodel.html#object.__init__" rel="nofollow"><em>__init__</em></a> method:</p>
<pre><code>class Test(object):
def __init__(self, re... | 7 | 2016-10-12T00:38:41Z | [
"python",
"python-3.x"
] |
using defaultdict in a array in python 2.7 | 39,988,788 | <p>I'm trying to create a dictionary where the same key can have different values from an array. In the past i created a dictionary with positions on each list of the list, but I found a bug where the same key can have more than one value and it's breaking the main code.
ie.</p>
<pre><code>my_array = [['a','b','c'],['... | -1 | 2016-10-12T00:35:38Z | 39,988,849 | <p>The <code>defaultdict</code> contructor takes a <em>callable</em> that will service as the default value for any undefined key. In your case, the default value is simply a <code>list</code>.</p>
<p>This code does what you want:</p>
<pre><code>from collections import defaultdict
my_dict = defaultdict(list)
for p in... | 2 | 2016-10-12T00:43:30Z | [
"python",
"python-2.7"
] |
using defaultdict in a array in python 2.7 | 39,988,788 | <p>I'm trying to create a dictionary where the same key can have different values from an array. In the past i created a dictionary with positions on each list of the list, but I found a bug where the same key can have more than one value and it's breaking the main code.
ie.</p>
<pre><code>my_array = [['a','b','c'],['... | -1 | 2016-10-12T00:35:38Z | 39,988,852 | <p>You can't do this with a comprehension/generator expression. Instead, try this:</p>
<pre><code>my_dict = {}
for p in my_array:
my_dict.setdefault(p[0], []).append(p[2])
</code></pre>
<p>You can also do it with a <code>defaultdict</code> if you insist, but it seems like overkill:</p>
<pre><code>my_dict = colle... | 2 | 2016-10-12T00:44:25Z | [
"python",
"python-2.7"
] |
re.sub correcting slashes in URL | 39,988,828 | <p>The input is a URL that may contain two or more sucessive slashes. I corrected it with the following two commands, which seems to be quite satisfying readable solution.</p>
<p>I wonder if you could achieve the same with only one re.sub() command.</p>
<pre><code>url = re.sub("/[/]+", "/", url) # two or more slashes... | 0 | 2016-10-12T00:40:57Z | 39,988,943 | <p>Yes you can. Use the negative lookbehind markup <code>?<!</code>:</p>
<pre><code>print(re.sub('(?<!http:)//+', '/', 'http://httpbin.org//ip'))
# http://httpbin.org/ip
</code></pre>
| 2 | 2016-10-12T00:58:49Z | [
"python",
"regex"
] |
Python For Loop Syntax to Java | 39,988,862 | <pre><code> for j in [c for c in coinValueList if c <= cents]:
</code></pre>
<p>How would you write this for loop out in java?
Is it</p>
<pre><code>for(j=0, j <= cents, j++){
for(c=0; c<= cents, j++){
</code></pre>
<p>I'm not sure what c and j are supposed to be compared to.
CoinValueList = {1,5,10,25}
... | -1 | 2016-10-12T00:45:31Z | 39,988,911 | <p>Let's decompose:</p>
<pre><code>array = [c for c in coinValueList if c <= cents] # produces an array of coins from coinValueList that are <= cents
for j in array: # iterates over array
#stuff
</code></pre>
<p>So we can do that in only one loop, and the java equivalent would be:</p>
<pre><code>for(int j=... | 3 | 2016-10-12T00:53:48Z | [
"java",
"python",
"for-loop",
"syntax"
] |
Python For Loop Syntax to Java | 39,988,862 | <pre><code> for j in [c for c in coinValueList if c <= cents]:
</code></pre>
<p>How would you write this for loop out in java?
Is it</p>
<pre><code>for(j=0, j <= cents, j++){
for(c=0; c<= cents, j++){
</code></pre>
<p>I'm not sure what c and j are supposed to be compared to.
CoinValueList = {1,5,10,25}
... | -1 | 2016-10-12T00:45:31Z | 39,989,180 | <p>if you want to translate very literally in Java</p>
<pre><code>List<Integer> newList = new ArrayList();
for(Integer c : coinValueList) {
if(c <= cents) {
newList.append(c);
}
}
for(Integer j : newList) {
# do something
}
</code></pre>
<p>but normally you don't need second <code>fo... | 0 | 2016-10-12T01:31:07Z | [
"java",
"python",
"for-loop",
"syntax"
] |
Python printing "<built-in method ... object" instead of list | 39,988,898 | <pre><code>import numpy as np
arr = list(map(float,input().split()))
print(np.array(arr.reverse))
</code></pre>
<p>Why is this printing this instead of the contents of the list?</p>
<pre><code># outputs "<built-in method reverse of list object at 0x107eeeec8>"
</code></pre>
| 1 | 2016-10-12T00:51:36Z | 39,988,929 | <p>You have two problems. </p>
<p>The first problem is that you are not actually <em>calling</em> the reverse method on your array <code>arr</code>.</p>
<p>You have this: <code>arr.reverse</code></p>
<p>You have to actually call it -> <code>arr.reverse()</code></p>
<p>Simple example below: </p>
<pre><code>>>... | 2 | 2016-10-12T00:56:17Z | [
"python",
"printing"
] |
How to get dataframe index from series? | 39,988,903 | <p>Say I extract a series from a dataframe (like what would happen with an apply function). I'm trying to find the original dataframe index from that series.</p>
<pre><code>df=pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]})
x=df.ix[0]
x
Out[109]:
a 1
b 4
c 7
Name: 0, dtype: int64
</code></pre>
<p>Noti... | 3 | 2016-10-12T00:52:28Z | 39,990,744 | <p>you access it with the <code>name</code> attribute</p>
<pre><code>x.name
0
</code></pre>
<p>take these examples</p>
<pre><code>for i, row in df.iterrows():
print row.name, i
0 0
1 1
2 2
</code></pre>
<p>Notice that the name attribute is the same as the variable <code>i</code> which is supposed to be the ro... | 2 | 2016-10-12T04:51:56Z | [
"python",
"pandas",
"indexing",
"dataframe",
"series"
] |
Setting Django with virtualenvironment on an Apache | 39,988,944 | <p>I just want to know if you really need to put this code in the <strong>wsgi.py</strong> when you want to deploy in apache with your django virtual environment</p>
<pre><code>activate_env=os.path.expanduser("/path/to/venv")
execfile(activate_env, dict(__file__=activate_env))
</code></pre>
<p>This is not mentioned i... | 0 | 2016-10-12T00:59:00Z | 39,989,515 | <p>If you configure mod_wsgi correctly, no you don't. Read:</p>
<ul>
<li><a href="http://blog.dscpl.com.au/2014/09/using-python-virtual-environments-with.html" rel="nofollow">http://blog.dscpl.com.au/2014/09/using-python-virtual-environments-with.html</a></li>
</ul>
| 0 | 2016-10-12T02:19:48Z | [
"python",
"django",
"apache"
] |
In SQLAlchemy, how to call a different database tables according to month | 39,989,014 | <p>In SQLAlchemy, how to call a different database tables according to month.
Each month corresponds to a database table.
I did this, but there was a problem.</p>
<pre><code>Class MyBaseClass (object):
    Id = db.Column (db.Integer, primary_key = True)
</code></pre>
<p>In my interface, this is the case</p>
<pr... | 0 | 2016-10-12T01:07:41Z | 40,028,237 | <p>I am an SQLAlchemy beginner and just won exactly the same battle with the ORM framework. Your approach of constructing a new type is on target. You should also look at <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html#augmenting-the-base" rel="nofollow">Augmenting the Base</a> manu... | 1 | 2016-10-13T18:19:53Z | [
"python",
"mysql",
"sqlalchemy"
] |
How to remove an item that appears multiple times in a list by Python? | 39,989,075 | <p>I am a python beginner and I am wondering how to remove an item that appears multiple times in a list by Python. Here is my list: </p>
<pre><code>["0101013132","0101410142","0101430144"]
</code></pre>
<p>The first thing I want to do is to replace all "01" by "1", the second thing is to replace"31","32" by "3" resp... | 0 | 2016-10-12T01:15:35Z | 39,989,172 | <pre><code>my_list = ["0101013132","0101410142","0101430144"]
normalized_list = []
for item in my_list:
normalized_list.append(item.replace('01', '1').replace('31', '3').replace('32', '3')) # and so one...)
print(normalized_list)
</code></pre>
| 1 | 2016-10-12T01:30:24Z | [
"python"
] |
How to remove an item that appears multiple times in a list by Python? | 39,989,075 | <p>I am a python beginner and I am wondering how to remove an item that appears multiple times in a list by Python. Here is my list: </p>
<pre><code>["0101013132","0101410142","0101430144"]
</code></pre>
<p>The first thing I want to do is to replace all "01" by "1", the second thing is to replace"31","32" by "3" resp... | 0 | 2016-10-12T01:15:35Z | 39,989,216 | <pre><code>L = ["0101013132","0101410142","0101430144"]
answer = [s[::2].replace('0', '1') for s in L]
In [7]: answer
Out[7]: ['11133', '11414', '11414']
</code></pre>
| 0 | 2016-10-12T01:36:37Z | [
"python"
] |
How to remove an item that appears multiple times in a list by Python? | 39,989,075 | <p>I am a python beginner and I am wondering how to remove an item that appears multiple times in a list by Python. Here is my list: </p>
<pre><code>["0101013132","0101410142","0101430144"]
</code></pre>
<p>The first thing I want to do is to replace all "01" by "1", the second thing is to replace"31","32" by "3" resp... | 0 | 2016-10-12T01:15:35Z | 39,989,298 | <pre><code>l = ["0101013132","0101410142","0101430144"]
[ ''.join( map( lambda x : str(x)[0] ,map( int, map(''.join, zip( *( [iter(s)]*2) ) ) ) ) ) for s in l ]
</code></pre>
| 0 | 2016-10-12T01:49:05Z | [
"python"
] |
Django: Template Does Not Exist Error | 39,989,150 | <p>In My django app I have a view called 'StatsView' given below:</p>
<pre><code>class StatsView(LoginRequiredMixin, View):
login_url = '/signin/'
def get(self, request, template='app_folder/ad_accounts/pixel_stats.html', *args, **kwargs):
#Code
return render(request, template, context)
</code... | -1 | 2016-10-12T01:26:50Z | 40,009,599 | <p>Silly mistake. Solved it by adding a <code>$</code> at the end in my <code>url</code>.</p>
<pre><code>url(
r'^ad_accounts/(?P<ad_account_id>[^/]+)/pixel_stats/$',
StatsView.as_view(),
name="pixel_stats"
),
</code></pre>
| 0 | 2016-10-12T22:49:29Z | [
"python",
"django"
] |
How to define function arguments partially? Python | 39,989,189 | <p>If I have a function with some arguments, I can define a duck function like this:</p>
<pre><code>>>> def f(x, y=0, z=42): return x + y * z
...
>>> f(1,2,3)
7
>>> g = f
>>> f(1,2)
85
>>> g(1,2)
85
</code></pre>
<p>I've tried to override the arguments partially but this... | 2 | 2016-10-12T01:32:21Z | 39,989,207 | <p>Use <a href="http://yourFile.write(str(self.textEdit.toPlainText()))" rel="nofollow"><code>functools.partial</code></a></p>
<pre><code>>>> from functools import partial
>>> def f(x, y=0, z=42): return x + y * z
...
>>> g = partial(f, z=23)
>>> g(1,2)
47
>>> f(1,2,23)
47... | 2 | 2016-10-12T01:34:31Z | [
"python",
"function",
"arguments",
"keyword-argument"
] |
How to handle urllib2 socket timeouts? | 39,989,350 | <p>So the following has worked for other links that have timed out and has continued to the next link in the loop. However for this link I got an error. I am not sure why that is and how to fix it so that when it happens it just browses to the next image.</p>
<pre><code>try:
image_file = urllib2.urlopen(submission... | 2 | 2016-10-12T01:55:47Z | 39,989,399 | <p>Explicitly catch the timeout exception: <a href="https://docs.python.org/3/library/socket.html#socket.timeout" rel="nofollow">https://docs.python.org/3/library/socket.html#socket.timeout</a></p>
<pre><code>try:
image_file = urllib2.urlopen(submission.url, timeout = 5)
except urllib2.URLError as e:
print(e)
... | 2 | 2016-10-12T02:02:51Z | [
"python",
"exception",
"urllib2",
"urllib",
"continue"
] |
Converting the contents of a while loop into a function | 39,989,381 | <pre><code>#Initialization
name=0
count=0
totalpr=0.0
#Load
name=input("Enter stock name OR -999 to Quit: ")
while name!='-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Ente... | 0 | 2016-10-12T02:00:19Z | 39,989,573 | <p>This is one way to convert inside of while loop to a function and then use the main function to call the function as many times as you like.</p>
<p>You can break this code down further to a print function. Just use return statement for that. </p>
<pre><code>def calculate(shares,pp,sp,commission,name):
totalpr ... | 1 | 2016-10-12T02:29:05Z | [
"python",
"function",
"python-3.x",
"while-loop"
] |
Converting the contents of a while loop into a function | 39,989,381 | <pre><code>#Initialization
name=0
count=0
totalpr=0.0
#Load
name=input("Enter stock name OR -999 to Quit: ")
while name!='-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Ente... | 0 | 2016-10-12T02:00:19Z | 39,994,563 | <p>It doesn't make sense for your few lines of code, as it blows up things unnecessarily, but here you go:</p>
<pre><code>def load():
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission... | 0 | 2016-10-12T09:01:49Z | [
"python",
"function",
"python-3.x",
"while-loop"
] |
'int' object is not subscriptable in my code | 39,989,384 | <p>I'm trying to write a program in Python that will compare two 4-digit numbers, one given by the player and one generated by the computer, and tell the player how many cows and bulls they get - cows being matching numbers in the wrong places and bulls being matching numbers in the right places. I keep getting an <cod... | 2 | 2016-10-12T02:00:34Z | 39,989,467 | <p>You can make the guess a list:</p>
<pre><code>guess = [1,2,3,4]
</code></pre>
| 1 | 2016-10-12T02:12:46Z | [
"python"
] |
'int' object is not subscriptable in my code | 39,989,384 | <p>I'm trying to write a program in Python that will compare two 4-digit numbers, one given by the player and one generated by the computer, and tell the player how many cows and bulls they get - cows being matching numbers in the wrong places and bulls being matching numbers in the right places. I keep getting an <cod... | 2 | 2016-10-12T02:00:34Z | 39,989,535 | <p>You should convert to string both <code>answer</code> and <code>guess</code>.</p>
<p>(Or access their digits in any other way, there are many)</p>
| 2 | 2016-10-12T02:23:03Z | [
"python"
] |
how to pass the text entered in entry box in tkinter from one function to another? | 39,989,385 | <p>I m tying to pass the entery box text from one function to another but it gives me error that the variable itself is not defined.Here is my code.</p>
<pre><code>from Tkinter import *
def mhello():
mtext=ment.get()
print mtext
def main():
root=Tk()
ment=StringVar()
root.title('Test')
mlabel=L... | -1 | 2016-10-12T02:00:44Z | 39,989,453 | <p>First off you have a variable scope issue, variables defined in functions are local to those functions so <code>ment</code> is defined in <code>main</code> but not in <code>mhello</code>. Either pass the variable in to <code>mhello</code> or make <code>ment</code> a global. So we can pass in the variable like this:<... | 0 | 2016-10-12T02:10:57Z | [
"python",
"python-2.7",
"tkinter"
] |
About Truthiness and the Booleans True and False | 39,989,478 | <p>My environment is : ubuntu 16.04 & python 2.7.12.</p>
<p>I read the documentation and found out that <code>''</code>, <code>()</code>, <code>[]</code>, <code>{}</code>, and <code>None</code> are all considered <code>False</code> by default.</p>
<p>But I don't understand what's going on in the examples below:<... | 2 | 2016-10-12T02:14:22Z | 39,989,511 | <p>It's not that those values <em>are equal to</em> <code>False</code>, it's that they <em>behave</em> as false when used in a boolean context.</p>
<p>It's certainly proper to cast to <code>bool</code> if you absolutely need a value of <code>True</code> or <code>False</code>, but in most cases it's not necessary.</p>
| 2 | 2016-10-12T02:18:59Z | [
"python"
] |
About Truthiness and the Booleans True and False | 39,989,478 | <p>My environment is : ubuntu 16.04 & python 2.7.12.</p>
<p>I read the documentation and found out that <code>''</code>, <code>()</code>, <code>[]</code>, <code>{}</code>, and <code>None</code> are all considered <code>False</code> by default.</p>
<p>But I don't understand what's going on in the examples below:<... | 2 | 2016-10-12T02:14:22Z | 39,989,513 | <p>The <a href="https://docs.python.org/2/library/stdtypes.html" rel="nofollow">docs</a> say:</p>
<blockquote>
<p>Any object can be tested for truth value, for use <strong>in an if or while condition or as operand of the Boolean operations</strong> below.</p>
</blockquote>
<p>In other words, this works for <code>a ... | 1 | 2016-10-12T02:19:38Z | [
"python"
] |
Django forms security, model form vs forms | 39,989,487 | <p>I'm learning django little by little I realized that I have some way to make a form, modelforms, forms and basic html with 'action= to view'.</p>
<p>If we talk bout security, what is the best option, I asked that because I have create a form to update data un db, do it with modelform it's very easy but I have follo... | 0 | 2016-10-12T02:15:56Z | 39,990,379 | <p>It will be safer to validate input by forms validation instead of making a direct query. That's also one of the main purpose of django form too.
And here's the reference of <a href="https://docs.djangoproject.com/en/1.10/topics/forms/" rel="nofollow">django forms</a>.</p>
<p>Back to your code and question I guess ... | 0 | 2016-10-12T04:10:30Z | [
"python",
"django",
"forms"
] |
hash() returning different values on different OSs | 39,989,534 | <p>When python builtin <code>hash()</code> is just wired cross-platform. I have an app use builtin <code>hash()</code> for <code>'test'</code>. Both systems are 64bit, python 2.7.12</p>
<p>windows:</p>
<pre><code>>>> hash('test')
1308370872
</code></pre>
<p>linux:</p>
<pre><code>>>> hash('test')
2... | 0 | 2016-10-12T02:22:59Z | 40,014,604 | <p>There are no guarantees about the value <code>hash</code> returns in Python. It appears that you're using a 32-bit Windows Python (that's a guess), and that you're using a 64-bit python on linux (again, a guess). IIRC (and I haven't checked), The default <code>hash(item)</code> returns the address of <code>item</c... | 1 | 2016-10-13T07:17:00Z | [
"python",
"python-2.7",
"hash",
"python-internals"
] |
cx_Freeze - Building exe - Windows 64bit - Invalid Syntex | 39,989,546 | <p>Trying to build a exe file but am having an error I don't understand. I followed a tutorial so unless it had bad instructions I don't see what is wrong. <a href="https://i.stack.imgur.com/NjGai.png" rel="nofollow">cmd print screen</a></p>
<p>-Code-</p>
<pre><code>import cx_Freeze
executables = [cx_Freeze.Executa... | 0 | 2016-10-12T02:24:56Z | 39,993,519 | <p>You are missing a <code>,</code>between keywords - like <code>name='Wedgie la Apple',</code></p>
<p>Example function:</p>
<pre><code>>>> def a(a="abc", b="cef"):
... print(a, b)
</code></pre>
<p>Wrong:</p>
<pre><code>>>> a(a="abcdef" b="feggsef")
File "<stdin>", line 1
a(a="abcd... | 0 | 2016-10-12T08:03:51Z | [
"python",
"python-3.x",
"cx-freeze"
] |
Organize a text file and covert it to CSV | 39,989,583 | <p>I have a text file similar to this:</p>
<p>What is the best way of organizing this txt file so that I can convert it to a CSV file later?
Ideally, I would like to have a table at the end with a row for each sequence and its measurements (each measurement in a separate column)</p>
<p>I am new to python and text ed... | 0 | 2016-10-12T02:30:16Z | 39,989,859 | <p>The quickest way would be to use a regular expression. However, as someone new to Python, please don't get overwhelmed.</p>
<pre><code>import re
matchSequence = []
matchMeasurements = []
for item in AlmostGood:
matchSequence.append(re.match([a], item))
matchMeasurements.append(re.match([s], item))
</code><... | 0 | 2016-10-12T03:04:45Z | [
"python",
"csv"
] |
Reverse of bytes to Hex program to convert Hex to bytes | 39,989,595 | <p>I am trying to write the reverse of the below program to get the bytes from the HEX value that i have. Finding it hard to do it. Any help?</p>
<pre><code>private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char [bytes.length *2];
for (int i=0; i< bytes.length; i++) {
int v = b... | 0 | 2016-10-12T02:32:09Z | 39,991,515 | <p>Thanks for the help everyone. I resolved this by using </p>
<pre><code>import binascii
</code></pre>
<p><code>binascii.hexlify('data')</code></p>
<p>For the JAVA code I found the answer here:
<a href="https://github.com/EverythingMe/inbloom/blob/master/java/src/main/java/me/everything/inbloom/BinAscii.java" rel="... | 0 | 2016-10-12T06:04:52Z | [
"java",
"python",
"hex",
"byte"
] |
Python counting multiple modes in a list | 39,989,608 | <p>This is a simple function but it is giving me a hard time. I'm trying to calculate the mode in a list, and if there are > 1 modes (with the same frequency), then they need to be displayed. </p>
<pre><code>def compute_mode(numbers):
mode = 0
count = 0
maxcount = 0
for number in numbers:
count = numbers.count(num... | -1 | 2016-10-12T02:33:30Z | 39,989,643 | <p>Its repeating those lines, simply because you have 2 of those numbers in your list.</p>
<p>Your function doesn't track if its already seen a number, in order to update a counter for it.</p>
<p>To count things, use the appropriately named <code>Counter</code> from the <code>collections</code> module:</p>
<pre><cod... | 2 | 2016-10-12T02:37:47Z | [
"python",
"list"
] |
Python counting multiple modes in a list | 39,989,608 | <p>This is a simple function but it is giving me a hard time. I'm trying to calculate the mode in a list, and if there are > 1 modes (with the same frequency), then they need to be displayed. </p>
<pre><code>def compute_mode(numbers):
mode = 0
count = 0
maxcount = 0
for number in numbers:
count = numbers.count(num... | -1 | 2016-10-12T02:33:30Z | 39,989,693 | <p>The reason you get the modes twice is that your for-loop loops over every element in the list. Therefore, when it encounters the second instance of a previously seen element, it prints it out again.</p>
<p>In other news, your function will fail for a different reason - try removing the first <code>0</code> and see ... | 2 | 2016-10-12T02:43:18Z | [
"python",
"list"
] |
Steps to integrate Python with Android | 39,989,612 | <p>I need to integrate my python code with my android application.
I am new to this type of integration so please tell me all the steps to do so.
I am currently creating an appliaction that just tells the geological information about the name of place you entered.
My python code takes the place name as input , traverse... | -1 | 2016-10-12T02:33:58Z | 39,989,651 | <p>Have you checked out <a href="http://www.jython.org/archive/21/docs/whatis.html" rel="nofollow">Jython</a>? It generally integrates Python and Java. You could actually do all of this in Java, if you wanted to do that as well.</p>
| 0 | 2016-10-12T02:38:19Z | [
"java",
"android",
"python",
"geolocation"
] |
Pandas time series resampling | 39,989,679 | <p>I have a list of voyages with a start and end date and the earnings for that voyage. I want to calculate the monthly earnings, but I am not sure how I can do that using Pandas:</p>
<pre><code>'2016-02-28 07:30:00', '2016-04-30 00:00:00', '600000'
'2016-05-18 10:30:00', '2016-07-12 02:19:00', '700000'
</code></pre>
... | 2 | 2016-10-12T02:41:43Z | 39,991,788 | <p>You need check how many hours is in each date range - in each row. So use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>DataFrame.apply</code></a> with custom function, where <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Serie... | 2 | 2016-10-12T06:24:08Z | [
"python",
"pandas",
"time-series",
"date-range"
] |
How can I get the google search snippets using Python? | 39,989,680 | <p>I am now trying the python module google which only return the url from the search result. And I want to have the snippets as information as well, how could I do that?(Since the google web search API is deprecated)</p>
| 1 | 2016-10-12T02:41:49Z | 39,989,752 | <p>I think you're going to have to extract your own snippets by opening and reading the url in the search result.</p>
| 0 | 2016-10-12T02:50:13Z | [
"python"
] |
from Flask import Flask ImportError: No module named Flask | 39,989,696 | <p>I am following the tutorial <a href="https://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972" rel="nofollow">here</a>.</p>
<p>My file looks like this:</p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route("/")
def main():
return "Welcome!"
... | -1 | 2016-10-12T02:43:33Z | 39,990,311 | <p>I needed to do the following and the tutorial didn't really go into depth on how to install flask properly.</p>
<p>You must do the following in full.
<a href="http://flask.pocoo.org/docs/0.11/installation/#" rel="nofollow">http://flask.pocoo.org/docs/0.11/installation/#</a></p>
<p>Thanks for the responses.</p>
| 0 | 2016-10-12T04:02:18Z | [
"python",
"flask",
"filepath"
] |
Python2.7: Why isn't python reading any of my paths with open(filename)? | 39,989,717 | <p>So in "Learn python the hard way", at exercise 15, you learn how to make a program open a file. Here's my code, and I typed <code>python ex15.py ex15.txt</code> at the command prompt. I haven't had any other problems with the program so far:</p>
<pre><code>from sys import argv
script, filename = argv
txt = open(e... | -1 | 2016-10-12T02:45:51Z | 39,989,748 | <p>The file needs to be in the same folder you are running your script</p>
<p>If you are running at<code>C:/myscript.py</code>, you file needs to be at <code>C:/</code> as well. </p>
<p>Ex: </p>
<pre><code>>> cd C:
>> dir
ex15.txt myscript.py
>> python myscript.py ex15.txt
Here's your file: 'ex15.... | 1 | 2016-10-12T02:49:53Z | [
"python",
"path"
] |
NoneType error when opening file | 39,989,776 | <p>So I've been trying to figure out why it's giving me this error. If I put this:</p>
<pre><code>def open_file():
fp = open("ABC.txt")
return fp
file = open_file()
count = 1
for line in file:
if count == 9:
line9 = line
if count == 43:
line43 = line
#blahblahblah more programming
</... | 0 | 2016-10-12T02:51:42Z | 39,989,798 | <p>Your <code>open_file</code> function has no <code>return</code> statement, so it returns <code>None</code>. You should try something like</p>
<pre><code>def open_file():
while True:
file = input("Enter a file name: ")
try:
return open(file)
except FileNotFoundError:
... | 2 | 2016-10-12T02:55:13Z | [
"python",
"nonetype"
] |
Sort and group a list of dictionaries | 39,989,777 | <p>How can I sort and group this list of dictionaries into a nested dictionary which I want to return via an API as JSON.</p>
<p>Source Data (list of permissions):</p>
<pre><code>[{
'can_create': True,
'can_read': True,
'module_name': 'ModuleOne',
'module_id': 1,
'role_id': 1,
'end_point_id': ... | 3 | 2016-10-12T02:52:13Z | 39,990,811 | <p>TADA!</p>
<pre><code>from itertools import groupby
def group_by_remove(permissions, id_key, groups_key, name_key=None):
"""
@type permissions: C{list} of C{dict} of C{str} to C{object}
@param id_key: A string that represents the name of the id key, like "role_id" or "module_id"
@param groups_key: A... | 2 | 2016-10-12T04:58:28Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
Sort and group a list of dictionaries | 39,989,777 | <p>How can I sort and group this list of dictionaries into a nested dictionary which I want to return via an API as JSON.</p>
<p>Source Data (list of permissions):</p>
<pre><code>[{
'can_create': True,
'can_read': True,
'module_name': 'ModuleOne',
'module_id': 1,
'role_id': 1,
'end_point_id': ... | 3 | 2016-10-12T02:52:13Z | 39,991,951 | <p>PyFunctional is pretty good at list manipulation.</p>
<pre><code>from pprint import pprint
from functional import seq
input = [...] # taken from your example
output =(
seq(input) # convert regular python list to Sequence object
# group by role_id
.map(lambda e: (e.pop('role_id'), e)).group_by_key()
... | 1 | 2016-10-12T06:35:32Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
I don't know how to through one queryset type to manytomany relations | 39,989,787 | <p>I want to use Django to write a blog system.But the question is I can't get tags queryset from articles queryset.</p>
<p>models:</p>
<pre><code>class Article(models.Model):
...
tags = models.ManyToManyField(Tags,related_name='tags')
author = models.ForeignKey(
User,on_delete=models.CASCADE,to_f... | -1 | 2016-10-12T02:52:51Z | 39,990,118 | <p>You are using <code>related_name</code> wrong. <code>related_name</code> is the name for the reversed relationship. It should be:</p>
<pre><code>tags = models.ManyToManyField(Tags,related_name='articles')
</code></pre>
<p>So the simple answer to your question is use:</p>
<pre><code>[article.tags.all() for article... | 0 | 2016-10-12T03:37:52Z | [
"python",
"django",
"many-to-many",
"django-queryset"
] |
Not matching the output with the correct output | 39,989,837 | <p><a href="https://i.stack.imgur.com/AjdiD.png" rel="nofollow"><img src="https://i.stack.imgur.com/AjdiD.png" alt="enter image description here"></a> </p>
<pre><code>def interpret(result : [None]) -> str:
s = ''
s = s + 'Start state = ' + result[0] +'\n '
for x in result[1:-1]:
s += ' Input = '... | -2 | 2016-10-12T02:59:42Z | 39,992,159 | <p>I've changed the 6th line of the function from <code>x[0]</code> to <code>result[-1][0]</code>, which seems to work:</p>
<pre><code>def interpret(result : [None]) -> str:
s = ''
s = s + 'Start state = ' + result[0] +'\n '
for x in result[1:-1]:
s += ' Input = ' + x[0]+ '; new possible states ... | 0 | 2016-10-12T06:48:47Z | [
"python"
] |
TypeError: 'NoneType' object is not iterable when trying to check for a None value | 39,989,880 | <p>This is the error I receive:</p>
<pre class="lang-none prettyprint-override"><code>line 16, in main
definition, data = get_name ()
TypeError: 'NoneType' object is not iterable
</code></pre>
<p>I check for <code>None</code> type here:</p>
<pre><code>definition = get_word (name, gender)
if definition is None:
... | 0 | 2016-10-12T03:06:50Z | 39,991,520 | <p>You have a double negative in the part that is returning <code>None</code> for the check later. Maybe try this:</p>
<pre><code>if x and new_line:
return new_line, x
else:
return None, None
</code></pre>
<p>Then when checking for <code>None</code> don't actually check for <code>None</code>, check the variab... | 0 | 2016-10-12T06:05:09Z | [
"python",
"typeerror",
"nonetype"
] |
How to set selenium to process the next url when the current one loads more than 30 seconds? | 39,989,894 | <p>I want to know what to put into exception condition. I'm currently using the pass statement, but I'm not sure whether it does exactly what I want it to do. The reason why I want to implement this is because some webpages takes more than 30 seconds to load completely, like: taobao.com. My code is as followed:</p>
<p... | 0 | 2016-10-12T03:08:36Z | 39,990,433 | <p>You do the <code>set_page_load_timeout</code> once, usually shortly after instantiating the driver. You should then wrap the <code>driver.get</code> in the try except, like so:</p>
<pre><code>from __future__ import print_function
from selenium import webdriver
from time import sleep
from selenium.webdriver.support... | 0 | 2016-10-12T04:15:21Z | [
"python",
"selenium"
] |
How to set selenium to process the next url when the current one loads more than 30 seconds? | 39,989,894 | <p>I want to know what to put into exception condition. I'm currently using the pass statement, but I'm not sure whether it does exactly what I want it to do. The reason why I want to implement this is because some webpages takes more than 30 seconds to load completely, like: taobao.com. My code is as followed:</p>
<p... | 0 | 2016-10-12T03:08:36Z | 40,032,310 | <p>Here is the new program that gets the next url if the current one has loaded for more than 30 seconds. It may not look as a typical Python program since I'm used to Java.
from selenium import webdriver
from time import sleep
from selenium.common.exceptions import TimeoutException
import csv</p>
<pre... | 0 | 2016-10-13T22:54:06Z | [
"python",
"selenium"
] |
Cannot find text by xpath (scrapy) | 39,990,035 | <p>I try to use xpath to get the date from the example listed below. </p>
<pre><code><node>
<table>
<td>
<font style="font-size:14px">http://www.aaa.com</font>
&nbsp;&nbsp;2016-10-11 17:14:11
</td>
</table>
</node&g... | 0 | 2016-10-12T03:27:20Z | 39,990,364 | <p>you can try following xpath</p>
<pre><code>response.xpath('/node/table/td/font/following-sibling::text()[1]').extract()
</code></pre>
| 0 | 2016-10-12T04:09:11Z | [
"python",
"html",
"xpath",
"scrapy"
] |
While-loop: UnboundLocalError: local variable referenced before assignment | 39,990,133 | <p>I'm using python 3.5.</p>
<p>So I'm trying to create a function that takes x and y as positive float input, and then computes and returns R = x - N * y, where N is the largest integer, so that x > N * y.</p>
<p>I made this function:</p>
<pre><code>def floatme(x,y):
N = 1
while x <= N * y:
... | 0 | 2016-10-12T03:39:26Z | 39,990,145 | <p><code>R</code> is defined inside the <code>while</code> loop. If the condition of the <code>while</code> loop is not true initially, its body never executes and <code>R</code> is never defined. Then it is an error to try to <code>return R</code>.</p>
<p>To solve the problem, initialize <code>R</code> to something b... | 2 | 2016-10-12T03:41:31Z | [
"python",
"python-3.x"
] |
Python internal frame | 39,990,151 | <p>Is there any tkinter widget or window manager to realize internal frame (something like <a href="http://www.herongyang.com/Swing/JInternalFrame-Test.jpg" rel="nofollow">java internal frame</a>)? Have done some search but couldn't see any discussion on python support of internal frame. </p>
| 0 | 2016-10-12T03:41:54Z | 39,998,402 | <p>No, there is nothing pre-built, but tkinter has all of the fundamental building blocks to implement it. The embedded windows are just frames, and you can place them in a containing frame with <code>place</code>. You can add your own border, and add mouse bindings to allow the user to move the windows around.</p>
<p... | 0 | 2016-10-12T12:16:34Z | [
"python",
"tkinter",
"tk"
] |
Sorting strings with numbers in Python | 39,990,260 | <p>I have this string: </p>
<pre><code>string = '9x3420aAbD8'
</code></pre>
<p>How can I turn string into:</p>
<pre><code>'023489ADabx'
</code></pre>
<p>What function would I use?</p>
| 2 | 2016-10-12T03:55:40Z | 39,990,302 | <p>You can just use the built-in function <a href="https://docs.python.org/3.5/library/functions.html#sorted" rel="nofollow"><code>sorted</code></a> to sort the string lexographically. It takes in an iterable, sorts each element, then returns a sorted list. Per the documentation:</p>
<blockquote>
<p><code>sorted(ite... | 3 | 2016-10-12T04:00:15Z | [
"python",
"string",
"sorting"
] |
Sorting strings with numbers in Python | 39,990,260 | <p>I have this string: </p>
<pre><code>string = '9x3420aAbD8'
</code></pre>
<p>How can I turn string into:</p>
<pre><code>'023489ADabx'
</code></pre>
<p>What function would I use?</p>
| 2 | 2016-10-12T03:55:40Z | 39,990,314 | <p>You can use the <code>sorted()</code> function to sort the string, but this will return a list</p>
<pre><code>sorted(string)
['0', '2', '3', '4', '8', '9', 'A', 'D', 'a', 'b', 'x']
</code></pre>
<p>to turn this back into a string you just have to join it, which is commonly done using <code>''.join()</code></p>
<p... | 1 | 2016-10-12T04:02:43Z | [
"python",
"string",
"sorting"
] |
Too high latency while trying to manipulate sound arrays using sounddevice in python | 39,990,274 | <p>Few days ago, I have installed <a href="http://python-sounddevice.readthedocs.io/en/0.3.5/" rel="nofollow">a sounddevice</a> library in Python 2.7.5. I'm trying to make a sound array and add some effects to it immediately after I push a key on my MIDI controller. But I get a huge delay of 0.1 to 0.2 second which mak... | 0 | 2016-10-12T03:57:16Z | 40,031,816 | <p>You can specify the desired latency with <a href="http://python-sounddevice.readthedocs.io/en/latest/#sounddevice.default.latency" rel="nofollow">sounddevice.default.latency</a>. Note however, that this is a <em>suggested</em> latency, the actual latency may be different, depending on the hardware and probably also ... | 0 | 2016-10-13T22:06:21Z | [
"python",
"numpy",
"low-latency",
"python-sounddevice"
] |
Create custom date range, 22 hours a day python | 39,990,287 | <p>I'm working with pandas and want to create a month-long custom date range where the week starts on Sunday night at 6pm and ends Friday afternoon at 4pm. And each day has 22 hours, so for example Sunday at 6pm to Monday at 4pm, Monday 6pm to Tuesday 4pm, etc. </p>
<p>I tried <code>day_range = pd.date_range(datetime(... | 4 | 2016-10-12T03:58:17Z | 39,990,804 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#custom-business-hour" rel="nofollow"><code>Custom Business Hour</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="nofollow"><code>date_range</code></a>:</p>
<pre><code>cbh = pd.off... | 2 | 2016-10-12T04:58:09Z | [
"python",
"datetime",
"pandas",
"date-range",
"hour"
] |
Where is my below python code failing? | 39,990,370 | <p>if the function call is like: backwardsPrime(9900, 10000) then output should be [9923, 9931, 9941, 9967]. Backwards Read Primes are primes that when read backwards in base 10 (from right to left) are a different prime. It is one of the kata in Codewars and on submitting the below solution, I am getting the following... | 0 | 2016-10-12T04:09:44Z | 39,990,466 | <p>Looks like your code passes the test when run manually. Maybe they range to scan over is set wrong on the test causing it to miss the last one?</p>
<pre><code> backwardsPrime(1095000, 1095405)
[1095047, 1095209, 1095319, 1095403]
</code></pre>
<p>e.g. the second parameter is set to <code>1095400</code> or somethi... | 0 | 2016-10-12T04:20:02Z | [
"python",
"primes"
] |
Python select data return boolean true-false and DELETE value true | 39,990,459 | <p><strong>I made a program transaction.and if error,it should report position error. NOW I want to select value TRUE and DELETE value TRUE</strong></p>
<pre><code>#!/usr/bin/python
import mysql.connector
conn = mysql.connector.connect(host="lll",user="ppp",passwd="ppp",db="ppp")
cursor = conn.cursor()
cursor.execut... | 0 | 2016-10-12T04:18:55Z | 39,990,877 | <p>This error is related to inconsistent indentation. Python relies on indentation to determine when "code blocks" start and stop. <a href="http://www.diveintopython.net/getting_to_know_python/indenting_code.html" rel="nofollow">Take a look at this for more details</a>.</p>
<p>Try something like this:</p>
<pre><code>... | 2 | 2016-10-12T05:06:17Z | [
"python",
"mysql"
] |
Recover Binary Tree | 39,990,483 | <p>For <a href="https://leetcode.com/problems/recover-binary-search-tree/" rel="nofollow" title="this">this</a> question on leet code, this code is passing all the test cases. </p>
<pre><code>class Solution(object):
def recoverTree(self, root):
self.first = None
self.second = None
self.prev = TreeNode(floa... | 0 | 2016-10-12T04:22:14Z | 39,990,584 | <p>The code is different because you still want to run <code>self.second = root</code>. You want to run this line whether <code>self.first</code> was <code>true</code> or <code>false</code> <em>before</em> you started playing with it.</p>
<p>Likely there is a test in which <code>self.first</code> is <code>true</code> ... | 0 | 2016-10-12T04:33:43Z | [
"python",
"if-statement",
"recursion",
"binary-search-tree",
"traversal"
] |
Remake for-loop to numpy broadcast | 39,990,603 | <p>I'm trying to code LSB steganography method via numpy arrays. I got code which makes the bool index mask, wich will give those bits of red channel, which need to xor with 1.</p>
<pre><code>import numpy as np
from scipy.misc import imread
import matplotlib.pyplot as plt
message = 'Hello, World!'
message_bits = np.a... | 0 | 2016-10-12T04:36:08Z | 39,990,747 | <p>If you pad <code>message_bits</code> to have as many elements as pixels in <code>xor_mask</code> then it gets simple:</p>
<pre><code>xor_mask = np.zeros_like(img, dtype=np.bool)
xor_mask[:, :, 0] = np.reshape(message_bits, xor_mask.shape[:2])
</code></pre>
<p>Another way, without padding:</p>
<pre><code>xor_mask[... | 1 | 2016-10-12T04:52:13Z | [
"python",
"numpy",
"optimization",
"scipy",
"steganography"
] |
Function not calling properly | 39,990,604 | <pre><code>def main():
def load():
name=0
count=0
totalpr=0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
... | -2 | 2016-10-12T04:36:11Z | 39,990,636 | <p>yikes.<br>
your first mistake: calling a function in another function. Maybe you meant to do </p>
<pre><code>class Main:
def load(self):
#do a thing
</code></pre>
<p>then you'd have to do </p>
<pre><code>main = Main()
main.load()
</code></pre>
<p>your second mistake was defining a new a print() fun... | 0 | 2016-10-12T04:40:15Z | [
"python",
"function",
"python-3.x",
"calling-convention"
] |
Function not calling properly | 39,990,604 | <pre><code>def main():
def load():
name=0
count=0
totalpr=0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
... | -2 | 2016-10-12T04:36:11Z | 39,990,637 | <p>You are defining <code>load()</code> inside the scope of <code>main()</code>. This means you cannot use the function outside of <code>main()</code>.</p>
<p>The easy solution is that you should put your function defines for load, calc, and print outside of the definition of <code>main()</code> (btw, call it somethin... | 1 | 2016-10-12T04:40:52Z | [
"python",
"function",
"python-3.x",
"calling-convention"
] |
Function not calling properly | 39,990,604 | <pre><code>def main():
def load():
name=0
count=0
totalpr=0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
... | -2 | 2016-10-12T04:36:11Z | 39,991,017 | <p>This is a minimal working example to illustrate how one can solve what you are trying to do.</p>
<pre><code># helper for interpreting input
import ast
#: initial starting values
thing, count, cost, total = 'Nothing', 0, 0, 0
# define all functions at module indentation
def get_user_input():
global thing, count... | 0 | 2016-10-12T05:20:31Z | [
"python",
"function",
"python-3.x",
"calling-convention"
] |
Function not calling properly | 39,990,604 | <pre><code>def main():
def load():
name=0
count=0
totalpr=0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
... | -2 | 2016-10-12T04:36:11Z | 40,010,852 | <pre><code>def load():
global name
global count
global shares
global pp
global sp
global commission
name=input("Enter stock name OR -999 to Quit: ")
count =0
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("... | 0 | 2016-10-13T01:27:49Z | [
"python",
"function",
"python-3.x",
"calling-convention"
] |
Regex match (\w+) to capture single words delimited by ||| - Python | 39,990,657 | <p>I am trying to match if there's singe word followed by <code>\s|||\s</code> and then another single word followed by <code>\s|||\s</code> so I'm using this regex:</p>
<pre><code>single_word_regex = r'(\w+)+\s\|\|\|\s(\w+)\s\|\|\|\s.*'
</code></pre>
<p>And when I tried to match this string, the regex matching hangs... | 3 | 2016-10-12T04:42:41Z | 39,992,585 | <p>Note that by itself, a <code>r'(\w+)+'</code> pattern will not cause the <a href="http://www.regular-expressions.info/catastrophic.html" rel="nofollow">catastrophic backtracking</a>, it will only be "evil" inside a longer expression and especially when it is placed next to the start of the pattern since in case subs... | 3 | 2016-10-12T07:13:03Z | [
"python",
"regex",
"loops",
"hang"
] |
In Django, how do I get a file path for an uploaded file when uploading? | 39,990,659 | <p>I am trying to add some validation for user uploaded files. This requires running through a custom script I made called "sumpin", which only takes a filepath as a variable and sends back JSON data that will verify. Everything inside my script is working independently, putting it together where the error occurs.<br><... | 1 | 2016-10-12T04:42:52Z | 40,048,519 | <p>I've found my own answer, but I'll post it here in case someone runs across this issue in the future.</p>
<p>I was incorrect, a validator wouldn't actually download the file. I need to use a file upload handler, which is shown below.</p>
<pre><code>import os
from django.core.files.storage import default_storage
fr... | 0 | 2016-10-14T17:07:47Z | [
"python",
"django",
"validation"
] |
Hierarchical Clustering using Python on Correlation Coefficient | 39,990,706 | <p>I have the data in 50 by 50 Matrix that represents the 50 Journals with their correlation. Now, I am trying to plot the graph showing on which clusters those 50 Journals fall based on the data. </p>
<p>1) I prefer to use complete-linkage or Ward's method to do the clusters.
2) I am stuck at where to begin the clust... | -2 | 2016-10-12T04:47:27Z | 39,991,533 | <p>Python expects <em>distances</em>, i.e. low values are better.</p>
<p>Ward is designed for squared Euclidean, so while it may work with correlation, the support from theory may be weak. Complete linkage will be supported.</p>
<p>What about negative correlations - how do you want to treat them?</p>
<p>I believe I ... | 0 | 2016-10-12T06:05:59Z | [
"python",
"scikit-learn",
"cluster-analysis",
"correlation",
"hierarchical-clustering"
] |
Storing user values in a Python list using a for loop | 39,990,718 | <p>This is my Code for Asking user to input the number of cities and should allow only that number of cities to enter
Requirement is to use For Loop</p>
<pre><code>global number_of_cities
global city
global li
global container
li = []
number_of_cities = int(raw_input("Enter Number of Cities -->"))
for city in range... | 0 | 2016-10-12T04:48:56Z | 39,991,119 | <p>Assuming you want a list of the cities in <code>li</code> you can do the following:</p>
<pre><code>li = []
number_of_cities = int(raw_input("Enter Number of Cities -->"))
for city in range(number_of_cities):
li.append(raw_input("Enter City Name -->"))
print(li)
</code></pre>
<p>No need for the <code>glob... | 1 | 2016-10-12T05:31:19Z | [
"python"
] |
Storing user values in a Python list using a for loop | 39,990,718 | <p>This is my Code for Asking user to input the number of cities and should allow only that number of cities to enter
Requirement is to use For Loop</p>
<pre><code>global number_of_cities
global city
global li
global container
li = []
number_of_cities = int(raw_input("Enter Number of Cities -->"))
for city in range... | 0 | 2016-10-12T04:48:56Z | 39,991,351 | <p>Instead of </p>
<pre><code>li = city
</code></pre>
<p>Use</p>
<pre><code>li.append(city)
</code></pre>
<p>Hope thi helps.</p>
| 0 | 2016-10-12T05:51:36Z | [
"python"
] |
Efficient algorithm to find the count of numbers that are divisible by a number without a remainder in a range | 39,990,753 | <p>Let's say I have two numbers: 6 and 11 and I am trying to find how many numbers between this range are divisible by 2 (3, in this case).</p>
<p>I have this simple code right now:</p>
<pre><code>def get_count(a, b, m):
count = 0
for i in range(a, b + 1):
if i % m == 0:
count += 1
r... | 0 | 2016-10-12T04:52:55Z | 39,990,818 | <p><code>((b - b%m) - a)//m+1</code> seems to work for me. I doubt it has a name. Another formula that seems to work is <code>(b//m) - ((a-1)//m)</code>.</p>
<p>Sample python3 program:</p>
<pre><code>def get_count(a, b, m):
return (((b - (b % m)) - a) // m) + 1
for i in range(5, 8):
for j in range(10, 13):
... | 1 | 2016-10-12T04:59:26Z | [
"python",
"algorithm",
"performance"
] |
Efficient algorithm to find the count of numbers that are divisible by a number without a remainder in a range | 39,990,753 | <p>Let's say I have two numbers: 6 and 11 and I am trying to find how many numbers between this range are divisible by 2 (3, in this case).</p>
<p>I have this simple code right now:</p>
<pre><code>def get_count(a, b, m):
count = 0
for i in range(a, b + 1):
if i % m == 0:
count += 1
r... | 0 | 2016-10-12T04:52:55Z | 39,990,876 | <p>To find the count of all numbers between 0 and n that are divisible by two. you can use the bitwise operation called right shift;</p>
<pre><code>c = a >> 1;
</code></pre>
<p>10 >> 1 is equivalent to floor(10/2)</p>
<p>You can subtract the two resultant numbers and get numbers between any range.</p>
<p>This... | -1 | 2016-10-12T05:06:16Z | [
"python",
"algorithm",
"performance"
] |
Efficient algorithm to find the count of numbers that are divisible by a number without a remainder in a range | 39,990,753 | <p>Let's say I have two numbers: 6 and 11 and I am trying to find how many numbers between this range are divisible by 2 (3, in this case).</p>
<p>I have this simple code right now:</p>
<pre><code>def get_count(a, b, m):
count = 0
for i in range(a, b + 1):
if i % m == 0:
count += 1
r... | 0 | 2016-10-12T04:52:55Z | 39,991,665 | <p>You are counting even numbers. Let's write <code>o</code> for odd, <code>E</code> for even.</p>
<p>If the sequence has an even count of numbers, it is either <code>oEoE...oE</code> or <code>EoEo...Eo</code>, i.e. one half of numbers is always even. If there is odd count of numbers, you can check the first number (o... | 0 | 2016-10-12T06:15:40Z | [
"python",
"algorithm",
"performance"
] |
gunicorn "configuration cannot be imported" | 39,990,844 | <p>I'm migrating a project that has been on Heroku to a DO droplet. Install went smoothly, and everything is working well when I <code>python manage.py runserver 0.0.0.0:8000</code>.</p>
<p>I'm now setting up gunicorn using these instructions:
<a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-dja... | 3 | 2016-10-12T05:02:48Z | 39,991,082 | <p>Use this link and Set the DJANGO_CONFIGURATION environment variable to the name of the class you just created, e.g. in bash:</p>
<p>export DJANGO_CONFIGURATION=Dev </p>
<p><a href="https://github.com/jazzband/django-configurations" rel="nofollow">Read further here.</a></p>
<p><a href="https://django-configuratio... | 1 | 2016-10-12T05:27:23Z | [
"python",
"django",
"gunicorn"
] |
Not able to execute pip commands even though pip is installed and added to PATH | 39,990,890 | <p>I already have pip installed and added the corresponding path to my path,however I dont seem to be able to execute any pip commands(see below),what am I missing?</p>
<pre><code>C:\Python27\Lib\site-packages\pip>get-pip.py
You are using pip version 6.0.6, however version 8.1.2 is available.
You should consider up... | 0 | 2016-10-12T05:07:51Z | 39,990,930 | <p>You have <code>pip</code> installed but you don't have any command named <code>pip</code>.</p>
<p>try <code>python -m pip</code></p>
| 0 | 2016-10-12T05:12:49Z | [
"python",
"pip"
] |
Debugging python segmentation faults in garbage collection | 39,990,934 | <p>I'm faced with segmentation faults (SIGSEGV) which occur during garbage collection in cPython. I've also had one instance where a process was killed with SIGBUS. My own code is mostly python and a little bit of very high level Cython. I'm most certainly not - deliberately and explicitly - fooling around with pointer... | 1 | 2016-10-12T05:13:02Z | 40,038,616 | <p>I am rather confident that issue I ran across is due to <a href="https://bugs.python.org/issue26617" rel="nofollow">issue 26617</a> in CPython which is fixed in <a href="https://github.com/python/cpython/commit/7bfa6f2bfe1b14eec0e9e036866f7acd52d1c8ee" rel="nofollow">7bfa6f2</a>.</p>
<p>I've check this by reproduci... | 1 | 2016-10-14T08:34:35Z | [
"python",
"c",
"multithreading",
"garbage-collection",
"memory-corruption"
] |
python: ValueError: I/O operation on closed file | 39,990,999 | <p>My code:</p>
<pre><code>with open('pass.txt') as f:
credentials = dict([x.strip().split(':') for x in f.readlines()]) # Created a dictionary with username:password items
name_input = input('Please Enter username: ')
if name_input in credentials: # Check if username is in the credentials d... | 1 | 2016-10-12T05:19:27Z | 39,991,503 | <p>Every file operation in Python is done on a file opened in a certain mode. The mode must be specified as an argument to the open function, and it determines the operations that can be done on the file, and the initial location of the file pointer.</p>
<p>In your code, you have opened the file without any argument o... | 3 | 2016-10-12T06:03:54Z | [
"python",
"python-3.4"
] |
In python, how do you check if a string has both uppercase and lowercase letters | 39,991,064 | <p>I've looked at the other post similar to my question, <a href="http://stackoverflow.com/questions/36380351/password-check-python-3">Password check- Python 3</a>, except my question involves checking if the password contains both uppercase and lower case questions. My code is the following, but when executed it fails... | 1 | 2016-10-12T05:26:03Z | 39,991,194 | <pre><code>import sys
def Valid_password_mixed_case(password):
letters = set(password)
mixed = any(letter.islower() for letter in letters) and any(letter.isupper() for letter in letters)
if not mixed:
print("Invalid password: Mixed case characters not detected", file=sys.stderr)
return mixed
</... | 0 | 2016-10-12T05:36:48Z | [
"python",
"string"
] |
In python, how do you check if a string has both uppercase and lowercase letters | 39,991,064 | <p>I've looked at the other post similar to my question, <a href="http://stackoverflow.com/questions/36380351/password-check-python-3">Password check- Python 3</a>, except my question involves checking if the password contains both uppercase and lower case questions. My code is the following, but when executed it fails... | 1 | 2016-10-12T05:26:03Z | 39,991,240 | <p>Your question is simple to answer. You are returning things of the form <code>return('steps' == True)</code> which is always going to return false. So just replace those with <code>return True</code> or <code>return False</code>.</p>
<p>Assuming you fix the above, your looping is also buggy. You only want to return... | 0 | 2016-10-12T05:40:45Z | [
"python",
"string"
] |
In python, how do you check if a string has both uppercase and lowercase letters | 39,991,064 | <p>I've looked at the other post similar to my question, <a href="http://stackoverflow.com/questions/36380351/password-check-python-3">Password check- Python 3</a>, except my question involves checking if the password contains both uppercase and lower case questions. My code is the following, but when executed it fails... | 1 | 2016-10-12T05:26:03Z | 39,991,634 | <p>You could use regular expression : </p>
<p>i.e. : </p>
<pre><code>def Valid_mixed_password(password):
lower = re.compile(r'.*[a-z]+') # Compile to match lowercase
upper = re.compile(r'.*[A-Z]+') # Compile to match uppercase
if lower.match(password) and upper.match(password): # if the password contains ... | -1 | 2016-10-12T06:13:07Z | [
"python",
"string"
] |
How to do first migration in flask? | 39,991,316 | <p>I am working on an new project which is already developed in Flask and I have no knowledge of Flask. My company gave the project to me because I have Django experience.</p>
<p>This is the structure of the project:</p>
<pre><code>models
-db.py
-model1.py
-model2.py
- ..
static
- ..
templates
- ..
myapp.... | 1 | 2016-10-12T05:48:21Z | 39,991,363 | <p>Use this command :</p>
<pre><code> python manage.py db migrate
</code></pre>
<p>And for database migration settings,Try something like this :</p>
<pre><code> import os
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from app import app, db
app.co... | 1 | 2016-10-12T05:52:18Z | [
"python",
"flask",
"flask-sqlalchemy"
] |
overwrite attribute as function Django | 39,991,320 | <p>I have <code>class A(models.Model)</code> with attr <code>name</code>. I use it in template and view as <code>obj_a.name</code>. I need overwrite <code>name</code> attr as function and when I write <code>obj_a.name</code> I would get response from function <code>getName</code>. How can I do it in <code>Django</code>... | -2 | 2016-10-12T05:48:49Z | 39,991,460 | <p>You can achieve this behavior with <a href="https://docs.python.org/2/library/functions.html#property" rel="nofollow"><code>property</code></a>.</p>
<pre><code>class A(models.Model):
_name = Field()
@property
def name(self):
return self._name
</code></pre>
| 3 | 2016-10-12T05:59:50Z | [
"python",
"django",
"object",
"django-models",
"attributes"
] |
overwrite attribute as function Django | 39,991,320 | <p>I have <code>class A(models.Model)</code> with attr <code>name</code>. I use it in template and view as <code>obj_a.name</code>. I need overwrite <code>name</code> attr as function and when I write <code>obj_a.name</code> I would get response from function <code>getName</code>. How can I do it in <code>Django</code>... | -2 | 2016-10-12T05:48:49Z | 39,992,036 | <p>I found solution ideal for my usage:</p>
<pre><code>def __getattribute__(self, name):
if name == 'name':
return 'xxx'
return super(Item, self).__getattribute__(name)
</code></pre>
| 0 | 2016-10-12T06:40:49Z | [
"python",
"django",
"object",
"django-models",
"attributes"
] |
Subtract a column in pandas dataframe by its first value | 39,991,471 | <p>I need to subtract all elements in one column of pandas dataframe by its first value.</p>
<p>In this code, pandas complains about self.inferred_type, which I guess is the circular referencing.</p>
<pre><code>df.Time = df.Time - df.Time[0]
</code></pre>
<p>And in this code, pandas complains about setting value on ... | 2 | 2016-10-12T06:01:15Z | 39,991,512 | <p>I think you can select first item in column <code>Time</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iloc.html" rel="nofollow"><code>iloc</code></a>:</p>
<pre><code>df.Time = df.Time - df.Time.iloc[0]
</code></pre>
<p>Sample:</p>
<pre><code>start = pd.to_datetime('2015-02-... | 2 | 2016-10-12T06:04:36Z | [
"python",
"datetime",
"pandas",
"time",
"subtraction"
] |
How can i solve this regular expression, Python? | 39,991,485 | <p>I would like to construct a reg expression pattern for the following string, and use Python to extract:</p>
<pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n"
</code></pre>
<p>What I want to do is extract the <strong>independent</strong> number values and add them which should be 278.... | 0 | 2016-10-12T06:02:42Z | 39,991,529 | <p>How about this?</p>
<pre><code>x = re.findall('\s([0-9]+)\s', str)
</code></pre>
| 0 | 2016-10-12T06:05:44Z | [
"python",
"regex"
] |
How can i solve this regular expression, Python? | 39,991,485 | <p>I would like to construct a reg expression pattern for the following string, and use Python to extract:</p>
<pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n"
</code></pre>
<p>What I want to do is extract the <strong>independent</strong> number values and add them which should be 278.... | 0 | 2016-10-12T06:02:42Z | 39,991,556 | <p>To avoid a partial match
use this:
<code>'^[0-9]*$'</code></p>
| 0 | 2016-10-12T06:07:36Z | [
"python",
"regex"
] |
How can i solve this regular expression, Python? | 39,991,485 | <p>I would like to construct a reg expression pattern for the following string, and use Python to extract:</p>
<pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n"
</code></pre>
<p>What I want to do is extract the <strong>independent</strong> number values and add them which should be 278.... | 0 | 2016-10-12T06:02:42Z | 39,991,567 | <pre><code>s = re.findall(r"\s\d+\s", a) # \s matches blank spaces before and after the number.
print (sum(map(int, s))) # print sum of all
</code></pre>
<p><code>\d+</code> matches all digits. This gives the exact expected output.</p>
<pre><code>278
</code></pre>
| 2 | 2016-10-12T06:08:21Z | [
"python",
"regex"
] |
How can i solve this regular expression, Python? | 39,991,485 | <p>I would like to construct a reg expression pattern for the following string, and use Python to extract:</p>
<pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n"
</code></pre>
<p>What I want to do is extract the <strong>independent</strong> number values and add them which should be 278.... | 0 | 2016-10-12T06:02:42Z | 39,991,583 | <p>Why not try something simpler like this?: </p>
<pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n"
print sum([int(s) for s in str.split() if s.isdigit()])
# 278
</code></pre>
| 1 | 2016-10-12T06:09:38Z | [
"python",
"regex"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.