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
How to Create a file at a specific path in python?
39,853,660
<p>I am writing below code which is not working:</p> <pre><code>cwd = os.getcwd() print (cwd) log = path.join(cwd,'log.out') os.chdir(cwd) and Path(log.out).touch() and os.chmod(log.out, 777) </code></pre> <p>how can I create a log.out into cwd ?</p>
0
2016-10-04T13:29:23Z
39,853,849
<p>you can call the usual linux <code>touch</code> command via <code>subprocess</code></p> <pre><code>import subprocess subprocess.call(["touch", cwd+"/log.out"]) </code></pre>
0
2016-10-04T13:38:32Z
[ "python" ]
How to Create a file at a specific path in python?
39,853,660
<p>I am writing below code which is not working:</p> <pre><code>cwd = os.getcwd() print (cwd) log = path.join(cwd,'log.out') os.chdir(cwd) and Path(log.out).touch() and os.chmod(log.out, 777) </code></pre> <p>how can I create a log.out into cwd ?</p>
0
2016-10-04T13:29:23Z
39,853,906
<p>To create an empty file:</p> <pre><code>import os cwd = os.getcwd() os.chdir(cwd) filename = 'log.out' with open(os.path.join(cwd, filename), 'wb') as f: f.write('') os.chmod(filename, 777) </code></pre> <p>This will create an empty file called <code>log.out</code>, which of course will be content-empty, bu...
0
2016-10-04T13:41:44Z
[ "python" ]
Is the index_db method from the SeqIO object in Biopython slow?
39,853,677
<p>I've got this:</p> <pre><code>files = glob.glob(str(dir_path) + "*.fa") index = SeqIO.index_db(index_filename, files, "fasta") seq = index[accession] # Slow index.close() return seq </code></pre> <p>and i'm working on big files (gene sequences) but for some reasons, it takes about 4 secondes to get the sequence ...
0
2016-10-04T13:30:08Z
39,856,519
<p>The first time the database is created it can take some time. The next times, if you don't delete the <code>index_filename</code> created, it should go faster.</p> <p>Lets say you have your 25 files each with some genes. This method creates a SQLite DB that helps locating the sequences among the files, like "Get me...
1
2016-10-04T15:41:17Z
[ "python", "biopython" ]
Setting values in one dataframe from the boolean values in another
39,853,718
<p>I have a MWE that can be reproduced with the following code:</p> <pre><code>import pandas as pd a = pd.DataFrame([[1,2],[3,4]], columns=['A', 'B']) b = pd.DataFrame([[True,False],[False,True]], columns=['A', 'B']) </code></pre> <p>Which creates the following dataframes:</p> <pre><code>In [8]: a Out[8]: A B 0...
1
2016-10-04T13:32:01Z
39,853,737
<p>If need replace <code>False</code> to <code>NaN</code>:</p> <pre><code>print (a[b]) A B 0 1.0 NaN 1 NaN 4.0 </code></pre> <p>or:</p> <pre><code>print (a.where(b)) A B 0 1.0 NaN 1 NaN 4.0 </code></pre> <p>and if need replace <code>True</code> to <code>NaN</code>:</p> <pre><code>print (a[~...
1
2016-10-04T13:32:59Z
[ "python", "pandas", "indexing", "dataframe", "boolean" ]
Python script to check dir not working
39,853,801
<p>I am stuck with my script at a point. The script is this</p> <pre><code>import subprocess import os def Windows(): SW_MINIMIZE = 6 info = subprocess.STARTUPINFO() info.dwFlags = subprocess.STARTF_USESHOWWINDOW info.wShowWindow = SW_MINIMIZE print(os.path.isdir("C:\Program Files (x86)")) whil...
0
2016-10-04T13:36:05Z
39,853,913
<p>for creating the path use the built-ins python functions that won't mess up the path</p> <pre><code>if os.path.exists(os.path.join('C:', os.path.sep(), 'Program Files')): # do your stuff </code></pre>
-1
2016-10-04T13:42:06Z
[ "python", "python-2.7", "subprocess" ]
Python script to check dir not working
39,853,801
<p>I am stuck with my script at a point. The script is this</p> <pre><code>import subprocess import os def Windows(): SW_MINIMIZE = 6 info = subprocess.STARTUPINFO() info.dwFlags = subprocess.STARTF_USESHOWWINDOW info.wShowWindow = SW_MINIMIZE print(os.path.isdir("C:\Program Files (x86)")) whil...
0
2016-10-04T13:36:05Z
39,854,038
<p>You're not actually checking if <code>os.path.isdir("C:\Program Files (x86)")</code>. You're just printing it.</p> <p>Instead of </p> <pre><code>print(os.path.isdir("C:\Program Files (x86)")) while True: </code></pre> <p>You need to do</p> <pre><code>if os.path.isdir(r"C:\Program Files (x86)"): </code></pre> <p...
1
2016-10-04T13:47:30Z
[ "python", "python-2.7", "subprocess" ]
Django Form Error: 'QueryDict' object has no attribute 'method' when POST assigned
39,853,857
<p>I'm having trouble with a specific form that is not permitting me to post data to a function I've defined. I'm very confused as to why this is giving me errors because I use an almost identical form to do another action in the same website.</p> <p>When I post this data, Django throws "'QueryDict' object has no attr...
0
2016-10-04T13:38:51Z
39,854,018
<p>The error is in this line</p> <pre><code>... def cancel(request): if request.method == "POST": form = cancel(request.POST or None) # you call the function, its the same name, you would call your cancelform if form.is_valid(): response = cancel(request.session['token'],form.cleaned_da...
1
2016-10-04T13:46:38Z
[ "python", "django", "forms" ]
how to check if date is in certain interval python?
39,853,900
<p>I'm importing dates from yahoo finance and want to transform them in a format so that I can compare them with today to check if the date is between 3 and 9 months from now.</p> <p>Here is what I have so far:</p> <pre><code>today = time.strftime("%Y-%m-%d") today = datetime.datetime.strptime(today, '%Y-%m-%d') int_...
0
2016-10-04T13:41:21Z
39,854,156
<p>You're using <code>transf_date = datetime.datetime.strptime(opt["Expiry"][1],'%b %d, %Y')</code> instead of <code>transf_date = datetime.datetime.strptime(opt["Expiry"][i],'%b %d, %Y')</code>, meaning that even though you're iterating over the entire <code>opt["Expiry"]</code>, you're always processing the same entr...
1
2016-10-04T13:53:12Z
[ "python", "datetime" ]
Diff commit messages of two branches with gitpython
39,854,111
<p>At work, we have a workflow where each branch is "named" by date. During the week, at least once, the latest branch gets pushed to production. What we require now is the summary/commit messages of the changes between the latest branch in production vs the new branch via gitpython.</p> <p>What I have tried to do:</p...
0
2016-10-04T13:50:54Z
39,856,321
<p>I figured it out:</p> <pre><code>import git g = git.Git(repoPath+repoName) g.pull() commitMessages = g.log('%s..%s' % (oldBranch, newBranch), '--pretty=format:%ad %an - %s', '--abbrev-commit') </code></pre> <p>Reading through the Git documentation I found that I can compare two branches with this syntax <code>B1....
0
2016-10-04T15:30:39Z
[ "python", "git-commit", "git-log", "gitpython" ]
proxy error when using flask as a simple http proxy
39,854,217
<p>There my code:</p> <p>main.py:</p> <pre><code>from flask import Flask, request, Response import requests app = Flask(__name__) @app.before_request def before_request(): url = request.url method = request.method data = request.get_data() headers = dict() for name, value in request.headers: ...
-1
2016-10-04T13:56:10Z
39,866,791
<p>Yes, it fails to connect to the proxy(127.0.0.1:6666)</p>
0
2016-10-05T06:24:59Z
[ "python", "flask", "python-requests" ]
python ObjectListView negate filter
39,854,298
<p>I need some help with negate this filter for the ObjectListView.</p> <pre><code>def addFilter(self, text): # OLV.Filter.Predicate() meter_flt = OLV.Filter.TextSearch(self, text=text) self.SetFilter(meter_flt) </code></pre> <p>This works great, but if i try to filter like "chicken" then it's only show c...
0
2016-10-04T13:59:31Z
39,872,312
<p>You can use <a href="http://objectlistview.sourceforge.net/python/features.html#filtering" rel="nofollow"><code>Filter.Predicate</code></a></p> <blockquote> <p>Filter.Predicate(booleanCallable) Show only the model objects for which the given callable returns true. The callable must accept a single parameter, ...
0
2016-10-05T11:06:54Z
[ "python", "wxpython", "filtering", "objectlistview", "objectlistview-python" ]
select name where id = "in the python list"?
39,854,306
<p>Let's say i have a python list of customer id like this:</p> <pre><code>id = ('12','14','15','11',.......) </code></pre> <p>the array has 1000 values in it, and i need to insert the customer name to a table based on the ids from the list above.</p> <p>my code is like:</p> <pre><code>ids = ",".join(id) sql = "ins...
0
2016-10-04T13:59:53Z
39,854,358
<p>You need to format the string.</p> <pre><code>ids = ",".join(id) sql = "insert into cust_table(name)values(names)where cust_id IN('{ids}')" cursor.execute(sql.format(ids= ids)) </code></pre>
0
2016-10-04T14:02:07Z
[ "python", "mysql" ]
select name where id = "in the python list"?
39,854,306
<p>Let's say i have a python list of customer id like this:</p> <pre><code>id = ('12','14','15','11',.......) </code></pre> <p>the array has 1000 values in it, and i need to insert the customer name to a table based on the ids from the list above.</p> <p>my code is like:</p> <pre><code>ids = ",".join(id) sql = "ins...
0
2016-10-04T13:59:53Z
39,855,021
<p>Simply writing the name of a variable into a string doesn't magically make its contents appear in the string.</p> <pre><code>&gt;&gt;&gt; p = 'some part' &gt;&gt;&gt; s = 'replace p of a string' &gt;&gt;&gt; s 'replace p of a string' &gt;&gt;&gt; s = 'replace %s of a string' % p &gt;&gt;&gt; s 'replace some part of...
0
2016-10-04T14:32:59Z
[ "python", "mysql" ]
Pandas time series comparison with missing data/records
39,854,373
<p>This question is somewhat related to an earlier question from me (<a href="http://stackoverflow.com/questions/38658811/remapping-numpy-array-with-missing-values">Remapping `numpy.array` with missing values</a>), where I was struggling with time series with missing data, and someone suggested <em>"use Pandas!"</em>. ...
2
2016-10-04T14:02:34Z
39,866,299
<p>One method (based on this: <a href="http://stackoverflow.com/a/34985243/3581217">http://stackoverflow.com/a/34985243/3581217</a> answer) which seems to work is to create a <code>Dataframe</code> where the observations from the different sites have different columns, then a <code>dropna()</code> with <code>subset</co...
0
2016-10-05T05:50:01Z
[ "python", "pandas", "time-series" ]
Cannot access elements in a list in Python
39,854,455
<p>I working with bigrams and unigrams. </p> <p>My bigrams are a counter of tuples and my unigrams are a list, where </p> <pre><code> uni['some key']=count </code></pre> <p>I am trying to do the follwing</p> <pre><code> for b,countB in bigrams.most_common() key=b[0] # this is guaranteed to be a key for my uni...
1
2016-10-04T14:06:29Z
39,854,538
<p>You are making the mistake of using a tuple when you perhaps need a dictionary. As the error message state, tuples cannot be indexed by a string key - you are expected to use numeric indices.</p> <p>A dict will let you use string keys as you appear to want to.</p> <pre><code>d = {} d['some key] = 23 </code></pre> ...
3
2016-10-04T14:10:03Z
[ "python", "nlp", "tuples", "n-gram" ]
Cannot access elements in a list in Python
39,854,455
<p>I working with bigrams and unigrams. </p> <p>My bigrams are a counter of tuples and my unigrams are a list, where </p> <pre><code> uni['some key']=count </code></pre> <p>I am trying to do the follwing</p> <pre><code> for b,countB in bigrams.most_common() key=b[0] # this is guaranteed to be a key for my uni...
1
2016-10-04T14:06:29Z
39,855,739
<p>I have executed your code with <code>corpus = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore"</code> since you said the error was a related to <code>uni</code> being a tuple but it actually is a dictionary.</p> <p>The error I got is different, it is a <code>KeyE...
0
2016-10-04T15:03:40Z
[ "python", "nlp", "tuples", "n-gram" ]
Cannot access elements in a list in Python
39,854,455
<p>I working with bigrams and unigrams. </p> <p>My bigrams are a counter of tuples and my unigrams are a list, where </p> <pre><code> uni['some key']=count </code></pre> <p>I am trying to do the follwing</p> <pre><code> for b,countB in bigrams.most_common() key=b[0] # this is guaranteed to be a key for my uni...
1
2016-10-04T14:06:29Z
39,856,117
<p>I tried your code and got a <code>KeyError: ''</code> which happens because your initial bigram has an empty string at position 0 and <code>''</code> is not in your unigrams dictionary. I didn't see a <code>TypeError</code> so that may be from somewhere else in your code. </p> <p>That said, various other comments: ...
1
2016-10-04T15:20:20Z
[ "python", "nlp", "tuples", "n-gram" ]
Python | delimited text file to csv format
39,854,482
<p>I'm new to python but I'm having trouble reading a text file which contains data separated by "|" as the delimiter. How would I separate the file into columns in a CSV format.</p> <pre><code>import csv my_file_name = "NVG.txt" cleaned_file = "cleanNVG.csv" with open(my_file_name, 'r') as infile, open(cleaned_file,...
0
2016-10-04T14:07:35Z
39,854,561
<p>The simplest way with your code would be to replace "|" with "," rather than removing "|"<br /></p> <pre><code>data = data.replace("|", ",") </code></pre>
1
2016-10-04T14:11:17Z
[ "python", "python-3.x" ]
Python | delimited text file to csv format
39,854,482
<p>I'm new to python but I'm having trouble reading a text file which contains data separated by "|" as the delimiter. How would I separate the file into columns in a CSV format.</p> <pre><code>import csv my_file_name = "NVG.txt" cleaned_file = "cleanNVG.csv" with open(my_file_name, 'r') as infile, open(cleaned_file,...
0
2016-10-04T14:07:35Z
39,854,583
<p>You're importing the <code>csv</code> module, but aren't using it. Make use of <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow"><code>csv.reader</code></a></p> <pre><code>with open(my_file_name, 'r') as infile, open(cleaned_file, 'w') as outfile: reader = csv.reader(infile, delimit...
1
2016-10-04T14:12:27Z
[ "python", "python-3.x" ]
Python | delimited text file to csv format
39,854,482
<p>I'm new to python but I'm having trouble reading a text file which contains data separated by "|" as the delimiter. How would I separate the file into columns in a CSV format.</p> <pre><code>import csv my_file_name = "NVG.txt" cleaned_file = "cleanNVG.csv" with open(my_file_name, 'r') as infile, open(cleaned_file,...
0
2016-10-04T14:07:35Z
39,854,585
<p>The <a href="https://docs.python.org/3/library/csv.html#csv.reader" rel="nofollow"><code>csv</code> module</a> allows you to read csv files with practically arbitrary delimiters.</p> <pre><code>with open(my_file_name, 'r', newline='') as infile: for line in csv.reader(infile, delimiter='|'): # do stuff ...
5
2016-10-04T14:12:30Z
[ "python", "python-3.x" ]
Python: write numpy array (int) to binary file without padding
39,854,637
<p>I have a binary file that was created in Fortran consisting of integer values as records. I want to read these into Python, edit them as lists and save them back to binary as np-arrays. For some reason, however, Python inserts an additional "0" after every record in the file. I guess this is what they call "padding"...
0
2016-10-04T14:14:51Z
39,855,050
<p>Check <code>content.dtype</code>. It looks like it is <code>np.int32</code>, which is generally the default integer type on Windows. You are writing 32 bit integers, but then trying to read them back as 16 bit integers. So every other value in the result is 0.</p>
1
2016-10-04T14:34:12Z
[ "python", "python-2.7", "numpy", "io", "binary" ]
peewee DateField property is None with MySQL database
39,854,677
<p>Via <code>pwiz</code> on my MySQL database, I get:</p> <pre><code>class BaseModel(Model): class Meta: database = database class Pub(BaseModel): ... author = TextField(null=True) ... publish_date = DateField(null=True) ... </code></pre> <p>Then, when iterating <code>entry in Pub.sel...
1
2016-10-04T14:16:54Z
39,868,401
<p>This is a <a href="https://github.com/PyMySQL/PyMySQL/issues/520" rel="nofollow">problem/bug in pymysql</a> although it is not clear yet how pymysql should handle it.</p> <p>For now, this monkey-patch-method fixes the problem to some degree; it will return the date as a string if it is not representable as a <code>...
0
2016-10-05T07:57:30Z
[ "python", "mysql", "peewee" ]
Is there any way to generate list exponentially in Python?
39,854,722
<p>I have a dictionary:</p> <p>D = {1:[1,2,3], 2:[4,5], 3: [6,7]}</p> <p>What I wish to do is to find all 3*2*2 combinations,</p> <pre><code> [[1,4,6], [1,4,7], [1,5,6], [1,5,7], [2,4,6], [2,4,6], [2,5,6], [2,5,7], [3,4,6], [3,4,7], [3,5,6], [3,5,7] ] </code></pre> <p>Is there any way, just doing loop like</p>...
0
2016-10-04T14:18:54Z
39,854,776
<p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.product"><strong><code>itertools.product</code></strong></a>:</p> <pre><code>itertools.product(*D.values()) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; D = {1:[1,2,3], 2:[4,5], 3: [6,7]} &gt;&gt;&gt; li...
6
2016-10-04T14:21:47Z
[ "python", "list", "hashtable" ]
Access nested key-values in Python dictionary
39,854,726
<p>I have the following dictionary structure and Iam trying to access the <code>total_payments</code> field. It is like accessing key of keys in Python dictionary:</p> <pre><code>d = {'METTS MARK': {'bonus': 600000, 'deferral_payments': 'NaN', 'deferred_income': 'NaN', 'director_fee...
-3
2016-10-04T14:19:14Z
39,854,812
<p>Hard to read your dictionary, but there's an example:</p> <pre><code>dic = {'abc': {'123': '2'}} print(dic['abc']['123']) #prints 2 </code></pre> <p>and if your dictionary had two sub dictionaries: </p> <pre><code>dic = {'abc': [{'123': '2'}, {'456': '4'}]} print(dic['abc'][1]['456']) # prints 4 </code></pre> <...
1
2016-10-04T14:23:32Z
[ "python", "dictionary" ]
Access nested key-values in Python dictionary
39,854,726
<p>I have the following dictionary structure and Iam trying to access the <code>total_payments</code> field. It is like accessing key of keys in Python dictionary:</p> <pre><code>d = {'METTS MARK': {'bonus': 600000, 'deferral_payments': 'NaN', 'deferred_income': 'NaN', 'director_fee...
-3
2016-10-04T14:19:14Z
39,854,852
<p>It rather seems that values of your dictionay are dict, and not that the keys are dict. So you can just access as follows:</p> <pre><code>your_dict[KEY1]['total_payments'] </code></pre> <p>Please also anonymize the email address in your example.</p>
1
2016-10-04T14:24:59Z
[ "python", "dictionary" ]
find index of equal values in an array
39,854,834
<p>So I have an array that I read from a file with several numbers. I need to find all the indices of the array equal to a certain value, and I do it in a loop (it's different values each time). It works perfect if I do it one by one, but when I do the loop, I get 0 matches in some cases, and I know the answer shouldn'...
-4
2016-10-04T14:24:06Z
39,855,424
<p>Is this what you want, getting all indices of a value from a list through iteration:</p> <pre><code>mg = # some value start = lst.index(mg) # first occurrence of mg print (start) for i in range(lst.count(mg)-1): start += lst[start+1:].index(mg)+1 print (start) </code></pre> <p>This will return all indices of <...
0
2016-10-04T14:50:22Z
[ "python" ]
Does this method returns a url?
39,854,945
<p>Sorry, I'm learning so forgive me if this is a stupid question. I got this method (updated):</p> <pre><code> def get_photo(self, photo_reference): print(self.photourl) print(photo_reference) resp = requests.get( url='{}{}'.format(self.photourl, photo_reference), params={'key': self.ap...
0
2016-10-04T14:29:11Z
39,856,880
<p>Maybe try this (Based on your seemingly preferred approach above of building the URL yourself):</p> <pre><code>def get_photo(self, photo_reference): request_url = (self.place_detail_url + self.ref + photo_reference + '&amp;key=' + self.api_key) output_file = (/path/to/image/here/file.png) with open(outp...
0
2016-10-04T15:58:27Z
[ "python", "json", "url", "request", "google-places-api" ]
Does this method returns a url?
39,854,945
<p>Sorry, I'm learning so forgive me if this is a stupid question. I got this method (updated):</p> <pre><code> def get_photo(self, photo_reference): print(self.photourl) print(photo_reference) resp = requests.get( url='{}{}'.format(self.photourl, photo_reference), params={'key': self.ap...
0
2016-10-04T14:29:11Z
39,868,670
<p>I got my answer, <code>resp</code> is a object and according to HTTP status 200, my URL is good. So I just need to do <code>return resp.url</code> to get the right URL link. It's a small problem but I made it big. Sorry and thank you to all your answer!</p>
0
2016-10-05T08:12:56Z
[ "python", "json", "url", "request", "google-places-api" ]
how i can go in admin panel is it possible when use sqlite
39,854,974
<p>I'm trying to access the sqlite admin at <a href="http://127.0.0.1:8000/admin" rel="nofollow">http://127.0.0.1:8000/admin</a>, but I don't know the user and pass. During <strong>python manage.py migrate</strong>, it did not ask about new user. </p> <p>Config:</p> <pre><code>DATABASES = { 'default': { 'ENGINE'...
0
2016-10-04T14:30:35Z
39,855,151
<p>Run <code>python manage.py createsuperuser</code> and create Django administrator first. Then you will be able to log-in to admin site using this account.</p>
2
2016-10-04T14:38:48Z
[ "python", "django", "sqlite" ]
issue with count variable in Python while loop
39,855,020
<p>I have an array of values:</p> <pre><code>increase_pop = [500, -300, 200, 100] </code></pre> <p>I am trying to find the index of the lowest and highest values. Most of my code works and everything seems to be going well except for one problem. The rest of my code looks like the following:</p> <pre><code>max_value...
0
2016-10-04T14:32:53Z
39,855,084
<p><code>max_year</code> is assigned when the first <code>if</code> conditional is satisfied. But if that never happens, <code>max_year</code> will never be assigned. That situation will occur when <code>increase_pop[0]</code> (and hence the initial value of <code>max_value</code>) is the largest value in <code>incre...
2
2016-10-04T14:35:29Z
[ "python", "loops" ]
issue with count variable in Python while loop
39,855,020
<p>I have an array of values:</p> <pre><code>increase_pop = [500, -300, 200, 100] </code></pre> <p>I am trying to find the index of the lowest and highest values. Most of my code works and everything seems to be going well except for one problem. The rest of my code looks like the following:</p> <pre><code>max_value...
0
2016-10-04T14:32:53Z
39,855,178
<p>You can make your codes more pythonic by using the feature of list:</p> <pre><code>min_value = min(increase_pop) max_value = max(increase_pop) min_value_index = increase_pop.index(min_value) max_value_index = increase_pop.index(max_value) </code></pre>
2
2016-10-04T14:40:07Z
[ "python", "loops" ]
matplotlib selecting wrong font style/weight
39,855,124
<p>I want to change the default font used in matplotlib plots to be Segoe UI under Windows. I can do so by altering <code>rcParams</code> like so</p> <pre><code>import matplotlib matplotlib.rcParams['font.family'] = 'sans-serif' matplotlib.rcParams['font.sans-serif'] = ['Segoe UI'] + matplotlib.rcParams['font.sans-ser...
0
2016-10-04T14:37:00Z
39,858,940
<p>It seems that matplotlib selects out of all the "Segoe UI" fonts the bold one for no reason. I fear that you cannot do much about this on the rcParams level.</p> <p>If someone finds a solution to this issue I'd really appreciate it as well. </p> <p>Until then, here is a workaround using the <code>fontproperties</c...
1
2016-10-04T18:03:28Z
[ "python", "matplotlib", "fonts" ]
Repeating characters results in wrong repetition counts
39,855,170
<p>My function looks like this:</p> <pre><code>def accum(s): a = [] for i in s: b = s.index(i) a.append(i * (b+1)) x = "-".join(a) return x.title() </code></pre> <p>with the expected input of:</p> <pre><code>'abcd' </code></pre> <p>the output should be and is:</p> <pre><code>'A-Bb-C...
0
2016-10-04T14:39:43Z
39,855,231
<p>Don't use <code>str.index()</code>, it'll return the <em>first match</em>. Since <code>c</code> and <code>b</code> and a appear early in the string you get <code>2</code>, <code>1</code> and <code>0</code> back regardless of the position of the <em>current</em> letter.</p> <p>Use the <a href="https://docs.python.or...
2
2016-10-04T14:42:53Z
[ "python" ]
Repeating characters results in wrong repetition counts
39,855,170
<p>My function looks like this:</p> <pre><code>def accum(s): a = [] for i in s: b = s.index(i) a.append(i * (b+1)) x = "-".join(a) return x.title() </code></pre> <p>with the expected input of:</p> <pre><code>'abcd' </code></pre> <p>the output should be and is:</p> <pre><code>'A-Bb-C...
0
2016-10-04T14:39:43Z
39,855,242
<p>This is because <code>s.index(a)</code> returns the first index of the character. You can use <code>enumerate</code> to pair elements to their indices:</p> <p>Here is a Pythonic solution:</p> <pre><code>def accum(s): return "-".join(c*(i+1) for i, c in enumerate(s)).title() </code></pre>
2
2016-10-04T14:43:14Z
[ "python" ]
Repeating characters results in wrong repetition counts
39,855,170
<p>My function looks like this:</p> <pre><code>def accum(s): a = [] for i in s: b = s.index(i) a.append(i * (b+1)) x = "-".join(a) return x.title() </code></pre> <p>with the expected input of:</p> <pre><code>'abcd' </code></pre> <p>the output should be and is:</p> <pre><code>'A-Bb-C...
0
2016-10-04T14:39:43Z
39,855,290
<p>simple:</p> <pre><code>def accum(s): a = [] for i in range(len(s)): a.append(s[i]*(i+1)) x = "-".join(a) return x.title() </code></pre>
0
2016-10-04T14:45:24Z
[ "python" ]
How to implement momentum-based stochastic gradient descent (SGD)
39,855,184
<p>I am using the python code network3.py (<a href="http://neuralnetworksanddeeplearning.com/chap6.html" rel="nofollow">http://neuralnetworksanddeeplearning.com/chap6.html</a>) for developing convolutional neural networks. Now I want to modify the code a little bit by adding a momentum learning rule as follows:</p> <p...
0
2016-10-04T14:40:32Z
39,855,990
<p>I have only ever coded up SDG from scratch (not using theano), but judging from your code you need to </p> <p>1) initiate the <code>velocities</code> with a bunch of zeros (one per gradient),</p> <p>2) include the velocity in your updates; something like </p> <pre><code>updates = [(param, param-eta*grad +momentum...
1
2016-10-04T15:15:14Z
[ "python", "momentum" ]
Looking to emulate the functionality of socat in Python
39,855,187
<p>I need to send a string to a particular port on localhost using python.</p> <p>I can achieve this by using socat on the command line like such:</p> <pre><code>cat &lt;text file containing string to send&gt; | socat stdin tcp-connect:127.0.0.1:55559 </code></pre> <p>I don't want to run the socat command as a subco...
0
2016-10-04T14:40:50Z
39,856,617
<p>According to <a href="https://linux.die.net/man/1/socat" rel="nofollow">the socat man page</a>,</p> <blockquote> <p>When one channel has reached EOF, the write part of the other channel is shut down. Then, socat waits <code>timeout</code> seconds before terminating. Default is 0.5 seconds. </p> </blockquote> <p>...
0
2016-10-04T15:46:12Z
[ "python", "socketserver", "socat" ]
Looking to emulate the functionality of socat in Python
39,855,187
<p>I need to send a string to a particular port on localhost using python.</p> <p>I can achieve this by using socat on the command line like such:</p> <pre><code>cat &lt;text file containing string to send&gt; | socat stdin tcp-connect:127.0.0.1:55559 </code></pre> <p>I don't want to run the socat command as a subco...
0
2016-10-04T14:40:50Z
39,857,096
<p>You shall never close a socket immediately after writing into a socket: the close could swallow still unsent data.</p> <p>The correct workflow is what is called a <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms738547%28v=vs.85%29.aspx" rel="nofollow">graceful shutdown</a>:</p> <ul> <li>the par...
0
2016-10-04T16:09:26Z
[ "python", "socketserver", "socat" ]
Looking to emulate the functionality of socat in Python
39,855,187
<p>I need to send a string to a particular port on localhost using python.</p> <p>I can achieve this by using socat on the command line like such:</p> <pre><code>cat &lt;text file containing string to send&gt; | socat stdin tcp-connect:127.0.0.1:55559 </code></pre> <p>I don't want to run the socat command as a subco...
0
2016-10-04T14:40:50Z
39,875,265
<p>Turned out to be something really simple. The string I was sending using socat (which the server was receiving and processing successfully) had a newline on the end of it. The string I was sending over the python socket didn't have a new line. After adding a new line to the end of the python script the server receiv...
0
2016-10-05T13:26:33Z
[ "python", "socketserver", "socat" ]
Why round(4.5) == 4 and round(5.5) == 6 in Python 3.5?
39,855,258
<p>Looks like both 4.5 and 5.5 have exact float representations in Python 3.5:</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; Decimal(4.5) Decimal('4.5') &gt;&gt;&gt; Decimal(5.5) Decimal('5.5') </code></pre> <p>If this is the case, then why</p> <pre><code>&gt;&gt;&gt; round(4.5) 4 &gt;&gt;&gt;...
0
2016-10-04T14:43:43Z
39,855,303
<p>Python 3 uses Bankers Rounding, which rounds <code>.5</code> values to the closest even number.</p>
3
2016-10-04T14:46:08Z
[ "python", "floating-point", "floating-accuracy" ]
Why round(4.5) == 4 and round(5.5) == 6 in Python 3.5?
39,855,258
<p>Looks like both 4.5 and 5.5 have exact float representations in Python 3.5:</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; Decimal(4.5) Decimal('4.5') &gt;&gt;&gt; Decimal(5.5) Decimal('5.5') </code></pre> <p>If this is the case, then why</p> <pre><code>&gt;&gt;&gt; round(4.5) 4 &gt;&gt;&gt;...
0
2016-10-04T14:43:43Z
39,855,329
<p>In Python 3, exact half way numbers are rounded to the nearest even result. This <a href="https://docs.python.org/3/whatsnew/3.0.html#builtins">behavior changed in Python 3</a></p> <blockquote> <p>The <a href="https://docs.python.org/3/library/functions.html#round"><code>round()</code></a> function rounding strat...
5
2016-10-04T14:46:49Z
[ "python", "floating-point", "floating-accuracy" ]
what's the difference between GTK 3.14 and 3.18 on the css load
39,855,273
<p>I finish a GTK interface with GTK3.18,and it works well,but when i change to GTK3.14 version,the interface turn out to be very bad,the size and the colore of the widgets is changed,and i find there is no enough information about the GTK3.14 version.</p>
0
2016-10-04T14:44:21Z
39,872,085
<p>The CSS 'api' was basically undocumented and unstable before 3.20 so there isn't really any reasonable way to support all versions before it unless you make a separate theme for each version.</p>
1
2016-10-05T10:55:35Z
[ "python", "css", "gtk" ]
access item in JSON result
39,855,294
<p>I am a bit confused as to how access <code>artists</code> <strong>name</strong> in this <code>json</code> result:</p> <pre><code>{ "tracks" : { "href" : "https://api.spotify.com/v1/search?query=karma+police&amp;offset=0&amp;limit=20&amp;type=track&amp;market=BR", "items" : [ { "album" : { "a...
0
2016-10-04T14:45:35Z
39,855,365
<p>You should do <code>items = results['tracks']['items'][0]['artists'][0]['name']</code>(although this is technically hardcoded)</p> <p>As your artist and items object are arrays (with only one, so we reference the first with [0])</p>
0
2016-10-04T14:48:15Z
[ "python", "json" ]
access item in JSON result
39,855,294
<p>I am a bit confused as to how access <code>artists</code> <strong>name</strong> in this <code>json</code> result:</p> <pre><code>{ "tracks" : { "href" : "https://api.spotify.com/v1/search?query=karma+police&amp;offset=0&amp;limit=20&amp;type=track&amp;market=BR", "items" : [ { "album" : { "a...
0
2016-10-04T14:45:35Z
39,855,372
<p><code>artists</code> is a <em>list</em> of dicts, because a track can have many artists. Similarly <code>items</code> is also a list. So for example you can do <code>results['tracks']['items'][0]['artists'][0]['name']</code>, but that will only get you the first artist of the first track.</p>
1
2016-10-04T14:48:39Z
[ "python", "json" ]
access item in JSON result
39,855,294
<p>I am a bit confused as to how access <code>artists</code> <strong>name</strong> in this <code>json</code> result:</p> <pre><code>{ "tracks" : { "href" : "https://api.spotify.com/v1/search?query=karma+police&amp;offset=0&amp;limit=20&amp;type=track&amp;market=BR", "items" : [ { "album" : { "a...
0
2016-10-04T14:45:35Z
39,855,742
<p>Defensively written, this might look something like:</p> <pre><code>artist_names = set() # using a set avoids adding the same name more than once if 'tracks' in results and 'items' in results['tracks']: for item in results['tracks']['items']: for artist in item.get('artists', ()): if 'name' in artist: ...
0
2016-10-04T15:03:43Z
[ "python", "json" ]
How to ask a string again if the wrong answer is entered?
39,855,326
<p>I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.</p> <pre><code>print("Hello there, what is your name?") MyName = input() print ("Nice to meet you " + MyName) print ("What is 2 + 2?") answer = i...
1
2016-10-04T14:46:46Z
39,855,435
<p>There are a couple of things wrong with your code. Firstly, you are only asking for the answer once at the moment. You need to put <code>answer = input()</code> in a <code>while</code> loop. Secondly, you need to use <code>==</code> instead of <code>is</code>:</p> <pre><code>print("Hello there, what is your name?")...
2
2016-10-04T14:50:49Z
[ "python" ]
How to ask a string again if the wrong answer is entered?
39,855,326
<p>I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.</p> <pre><code>print("Hello there, what is your name?") MyName = input() print ("Nice to meet you " + MyName) print ("What is 2 + 2?") answer = i...
1
2016-10-04T14:46:46Z
39,855,464
<p>You only need the wrong-answer check as loop condition and then output the "great job" message when the loop is over (no <code>if</code> is needed):</p> <pre><code>print("Hello there, what is your name?") MyName = input() print ("Nice to meet you " + MyName) print ("What is 2 + 2?") answer = input() while answer !=...
1
2016-10-04T14:51:42Z
[ "python" ]
How to ask a string again if the wrong answer is entered?
39,855,326
<p>I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.</p> <pre><code>print("Hello there, what is your name?") MyName = input() print ("Nice to meet you " + MyName) print ("What is 2 + 2?") answer = i...
1
2016-10-04T14:46:46Z
39,855,483
<pre><code>print('Guess 2 + 2: ') answer = int(input()) while answer != 4: print('try again') answer = int(input()) print('congrats!') </code></pre> <p>I think this is the simplest solution. </p>
1
2016-10-04T14:52:41Z
[ "python" ]
How to ask a string again if the wrong answer is entered?
39,855,326
<p>I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.</p> <pre><code>print("Hello there, what is your name?") MyName = input() print ("Nice to meet you " + MyName) print ("What is 2 + 2?") answer = i...
1
2016-10-04T14:46:46Z
39,855,767
<p>Here is my two cents for python2 : </p> <pre><code>#!/usr/bin/env python MyName = raw_input("Hello there, what is your name ? ") print("Nice to meet you " + MyName) answer = raw_input('What is 2 + 2 ? ') while answer != '4': print("Nope ! Please try again") answer = raw_input('What is 2 + 2 ? ') print(...
0
2016-10-04T15:04:52Z
[ "python" ]
How to ask a string again if the wrong answer is entered?
39,855,326
<p>I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.</p> <pre><code>print("Hello there, what is your name?") MyName = input() print ("Nice to meet you " + MyName) print ("What is 2 + 2?") answer = i...
1
2016-10-04T14:46:46Z
39,855,831
<p>By now you've got more answers than you can handle, but here are another couple of subtleties, with notes:</p> <pre><code>while True: # loop indefinitely until we hit a break... answer = input('What is 2 + 2 ? ') # ...which allows this line of code to be written just once (the DRY principle of programming...
1
2016-10-04T15:07:27Z
[ "python" ]
Python passing variable dates to function
39,855,342
<p>Hello: making progress but still struggling. I have the following json:</p> <pre><code>json = { "emeter": { "get_daystat": { "day_list": [ { "year": 2016, "month": 10, "day": 1, "energy": 0.651000 }, { "year": 2016, "month": 10, "day": 2, "energy": 0.349000 }, { "year": 2016, "mo...
1
2016-10-04T14:47:16Z
39,855,529
<p>There is a simple issue with your script: <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow"><code>strftime</code></a>, according to the docs, will</p> <blockquote> <p>return a string representing the date, controlled by an explicit format string.</p> </blockquote> <p>The keyword here being...
2
2016-10-04T14:54:40Z
[ "python", "function" ]
Is python tuple assignment order fixed?
39,855,410
<p>Will</p> <pre><code>a, a = 2, 1 </code></pre> <p>always result in a equal to 1? In other words, is tuple assignment guaranteed to be left-to-right?</p> <p>The matter becomes relevant when we don't have just a, but a[i], a[j] and i and j may or may not be equal.</p>
2
2016-10-04T14:49:58Z
39,855,581
<p>How it works :</p> <pre><code>a, a = 2, 1 --&gt; a does not exist, create variable a and set value to 2 --&gt; a already exists, value of a changed to 1 </code></pre> <p>When you have different variables, it works exactly the same way :</p> <pre><code>a, b, a = 1, 2, 3 --&gt; a does not exist, create variable a a...
0
2016-10-04T14:56:45Z
[ "python", "tuples", "variable-assignment" ]
Is python tuple assignment order fixed?
39,855,410
<p>Will</p> <pre><code>a, a = 2, 1 </code></pre> <p>always result in a equal to 1? In other words, is tuple assignment guaranteed to be left-to-right?</p> <p>The matter becomes relevant when we don't have just a, but a[i], a[j] and i and j may or may not be equal.</p>
2
2016-10-04T14:49:58Z
39,855,637
<p>Yes, it is part of the python language reference that tuple assignment must take place left to right. </p> <p><a href="https://docs.python.org/2.3/ref/assignment.html">https://docs.python.org/2.3/ref/assignment.html</a></p> <blockquote> <p>An assignment statement evaluates the expression list (remember that th...
7
2016-10-04T14:58:56Z
[ "python", "tuples", "variable-assignment" ]
Django in sub-directory
39,855,488
<p>When i build my django application, i'll use the runserver command in order to test my website, but in deploy, let's say that i'll publish my website under: www.test.com/django.</p> <p>My IIS it's configure with an application under my default website called "django".</p> <p>I'm expecting that everything will work...
1
2016-10-04T14:52:58Z
39,856,091
<p>The preferred method to fix this is to have your webserver pass the <code>SCRIPT_NAME</code> wsgi variable. Django will automatically use this variable as a prefix when constructing urls, without the need to change your url configuration. I'm unfamiliar with IIS, so I can't tell you how to do this. It does have the ...
0
2016-10-04T15:19:15Z
[ "python", "django", "url" ]
Using Select queries in python mysql as parameters for if/else block
39,855,508
<p>Can I use the results of a python SQL select query as parameters for an if/else statement in a function? If I have a DB with one column, and want to append the values of that column to a list for each row in the Select Query...I can't reference those queries in a function. For example:</p> <pre><code>db = MySQLdb...
0
2016-10-04T14:53:41Z
39,855,651
<p>Please see this link: <a href="http://stackoverflow.com/questions/14835852/convert-sql-result-to-list-python">Convert sql result to list python</a></p> <p>Basically, you want something similar to this:</p> <p><code>list(cur.fetchall())</code></p>
0
2016-10-04T14:59:33Z
[ "python", "mysql", "database", "list", "function" ]
List comprehension confusion
39,855,525
<p>I'm slightly confused by a problem that I'm having and wondered if anyone could help (it seems trivial in my mind so I hope that it genuinely is!)</p> <p>Basically, I have filtered by a list via the following list comprehension:</p> <pre><code>depfilt = [s for s in department if 'author' not in s] </code></pre> <...
2
2016-10-04T14:54:25Z
39,855,576
<p>Use <code>enumerate</code> instead of <code>index</code> in case of duplicate values</p> <pre><code>[s for i, s in enumerate(subj) if 'author' not in department[i]] </code></pre>
6
2016-10-04T14:56:37Z
[ "python" ]
List comprehension confusion
39,855,525
<p>I'm slightly confused by a problem that I'm having and wondered if anyone could help (it seems trivial in my mind so I hope that it genuinely is!)</p> <p>Basically, I have filtered by a list via the following list comprehension:</p> <pre><code>depfilt = [s for s in department if 'author' not in s] </code></pre> <...
2
2016-10-04T14:54:25Z
39,855,609
<p>If <code>department</code> and <code>subj</code> are definitely in the same order ie. corresponding elements of each match up, then use <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a> to iterate over both lists simultaneously:</p> <pre><code>[(d, s) for d, s in zip...
0
2016-10-04T14:57:52Z
[ "python" ]
manipulation of a list of strings containing digits to output a list of of digits
39,855,632
<p>I looking for help in manipulating a list of strings where I want to extract the digits such has :</p> <pre><code> x = ['aa bb qq 2 months 60%', 'aa bb qq 3 months 70%', 'aa bb qq 1 month 80%'] </code></pre> <p>I am trying to get to :</p> <pre><code>[[2.0,60.0],[3.0,70.0],[1.0,80.0]] </code></pre> <p>in a ele...
1
2016-10-04T14:58:44Z
39,855,722
<p>Use a <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regular expression</a> to match integers and floats.</p> <pre><code>import re [[float(n) for n in re.findall(r'\d+\.?\d*', s)] for s in x] </code></pre> <p>Explanation for the regex (<code>r'\d+\.?\d*'</code>): </p> <pre><code>r # a raw...
7
2016-10-04T15:02:53Z
[ "python", "string", "list", "python-2.7" ]
Django server killed frequently
39,855,652
<p>I'm developing a Django project and testing it on a dedicated server. The project is running on:</p> <ul> <li>django 1.9.6</li> <li>virtualenv</li> <li>python 2.7</li> <li>cx_Oracle 5.2.1</li> </ul> <hr> <p><strong>Running</strong> </p> <pre><code>python manage.py runserver 192.168.30.17:8080 &amp; </code></pre...
0
2016-10-04T14:59:34Z
39,855,716
<p>From the documentation on the django development server <a href="https://docs.djangoproject.com/en/1.10/ref/django-admin/" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/django-admin/</a></p> <blockquote> <p>DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or p...
1
2016-10-04T15:02:47Z
[ "python", "linux", "django", "virtualenv" ]
Pandas : Apply function on multiple columns
39,855,692
<p>I'm trying to add a new column calculated from first quartile of all columns. something like this:</p> <pre><code>df['Q25']=df[col].apply(lambda x: np.percentile(x, 25) ,axis =1) #col = ['1', '2','3',..'29'] days in one month </code></pre> <p>and this is the error I receive:</p> <pre><code>KeyError: "['1' '2' '3'...
0
2016-10-04T15:01:14Z
39,855,877
<p>Try this out :</p> <pre><code>df['Q25']= [np.percentile(df.loc[i,:], 25) for i in df.index] </code></pre>
1
2016-10-04T15:09:35Z
[ "python", "pandas" ]
Python sum array of objects into objects
39,855,697
<p>I have a list (name=carpet) of objects type mini_carpet. Mini_carpet contains a list of objects called packages. Packages has various properties, the one interesting to me is nr_buys.</p> <p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet. This is what I have done so f...
2
2016-10-04T15:01:38Z
39,855,733
<p>When you've already coded the __len__ method, u dont need to call it by <code>carpet.__len__()</code>. Instead of use <code>len(carpet)</code>.</p>
-1
2016-10-04T15:03:22Z
[ "python" ]
Python sum array of objects into objects
39,855,697
<p>I have a list (name=carpet) of objects type mini_carpet. Mini_carpet contains a list of objects called packages. Packages has various properties, the one interesting to me is nr_buys.</p> <p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet. This is what I have done so f...
2
2016-10-04T15:01:38Z
39,855,760
<pre><code>for d in range(0, len(carpet) - 1, +1): nr_total = sum(carpet[d].packages[i].nr_buys for i, _ in enumerate(carpet[d].packages)) </code></pre> <p>You want to get the <code>indexes</code> of a <code>dict</code>, so use <code>enumerate</code>, which returns a <code>tuple</code>: <code>(index, item)</code>. Als...
0
2016-10-04T15:04:37Z
[ "python" ]
Python sum array of objects into objects
39,855,697
<p>I have a list (name=carpet) of objects type mini_carpet. Mini_carpet contains a list of objects called packages. Packages has various properties, the one interesting to me is nr_buys.</p> <p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet. This is what I have done so f...
2
2016-10-04T15:01:38Z
39,855,917
<p>Another method of doing this, which I feel is more Pythonic, is:</p> <pre><code>nr_total = sum(package.nr_buys for package in carpet[d].packages) </code></pre> <p>The difference, as stated above, is that calling <code>for x in list</code> in python gives you the items of the list, and not their indices. That means...
0
2016-10-04T15:11:46Z
[ "python" ]
Python sum array of objects into objects
39,855,697
<p>I have a list (name=carpet) of objects type mini_carpet. Mini_carpet contains a list of objects called packages. Packages has various properties, the one interesting to me is nr_buys.</p> <p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet. This is what I have done so f...
2
2016-10-04T15:01:38Z
39,855,991
<blockquote> <p>sum the <em>various</em> <code>nr_buys</code> that are within a mini_carpet, within a carpet</p> </blockquote> <p>Asides what others have said about trying to index your list with a non integer object, you're also throwing away the result of previous iterations. </p> <p>You can use a mapping/diction...
0
2016-10-04T15:15:15Z
[ "python" ]
Python sum array of objects into objects
39,855,697
<p>I have a list (name=carpet) of objects type mini_carpet. Mini_carpet contains a list of objects called packages. Packages has various properties, the one interesting to me is nr_buys.</p> <p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet. This is what I have done so f...
2
2016-10-04T15:01:38Z
39,856,029
<p>In Python, it's generally better to loop directly over the items in a list, rather than looping indirectly using indices. It's easier to read, and more efficient not to muck around with indices that you don't really need.</p> <p>To get a total for each <code>mini_carpet</code> you can do this:</p> <pre><code>for m...
2
2016-10-04T15:17:20Z
[ "python" ]
Python - Change variable outside function without return
39,855,732
<p>I just started learning Python and I ran into this problem. I want to set a variable from inside a method, but the variable is outside the method. </p> <p>The method gets activated by a button. Then I want to get the value from that variable that I set when I press another button. The problem is that the value that...
3
2016-10-04T15:03:18Z
39,855,755
<p>Use <code>global</code> to modify a variable outside of the function:</p> <pre><code>def UpdateText(): global currentMovie currentMovie = random.randint(0, 100) print(currentMovie) </code></pre> <p>However, don't use <code>global</code>. It's generally a <a href="https://en.wikipedia.org/wiki/Code_smel...
3
2016-10-04T15:04:22Z
[ "python" ]
Python - Change variable outside function without return
39,855,732
<p>I just started learning Python and I ran into this problem. I want to set a variable from inside a method, but the variable is outside the method. </p> <p>The method gets activated by a button. Then I want to get the value from that variable that I set when I press another button. The problem is that the value that...
3
2016-10-04T15:03:18Z
39,894,555
<p>Here's a simple (python 2.x) example of how to 1 <em>not</em> use globals and 2 use a (simplistic) domain model class. </p> <p>The point is: you should first design your domain model independently from your user interface, then write the user interface code calling on your domain model. In this case your UI is a Tk...
3
2016-10-06T11:16:49Z
[ "python" ]
How to clone a git repo using python?
39,855,775
<p>I am looking for equivalent way to clone a repo in python</p> <pre><code>clone_start=`date +%s%N` &amp;&amp; git clone --quiet ssh://$USER@$host:29418/git_performance_check &gt;&amp; /dev/null &amp;&amp; c lone_end=`date +%s%N` Time_clone=`echo "scale=2;($clone_end - $clone_start) / 1000000000" | bc` </code...
0
2016-10-04T15:05:11Z
39,855,859
<p>You can use <a href="https://pypi.python.org/pypi/GitPython/" rel="nofollow">GitPyhton</a> lib</p> <p>Clone from existing repositories or initialize new empty ones:</p> <pre><code>import git host = 'github' user = 'root' git.Git().clone("ssh://{0}@{1}:29418/git_performance_check".format(user, host)) </code></pre>
2
2016-10-04T15:08:45Z
[ "python", "git" ]
How to clone a git repo using python?
39,855,775
<p>I am looking for equivalent way to clone a repo in python</p> <pre><code>clone_start=`date +%s%N` &amp;&amp; git clone --quiet ssh://$USER@$host:29418/git_performance_check &gt;&amp; /dev/null &amp;&amp; c lone_end=`date +%s%N` Time_clone=`echo "scale=2;($clone_end - $clone_start) / 1000000000" | bc` </code...
0
2016-10-04T15:05:11Z
39,855,898
<p>You could use <a href="https://pypi.python.org/pypi/GitPython/" rel="nofollow"><code>GitPython</code></a>. Something like this:</p> <pre><code> from git import Repo repo = Repo.init('/tmp/git_performance_check') repo.create_remote('origin', url='ssh://user@host:29418/git_performance_check') repo.rem...
0
2016-10-04T15:10:50Z
[ "python", "git" ]
Regex: can't understand the endpos
39,855,791
<p>Could you help me understand why <code>print(truth(prog.match(text, 0, 6)))</code> equals true?</p> <pre><code>import re from operator import truth prog = re.compile(r'&lt;HTML&gt;$') text = "&lt;HTML&gt; " print("Last symbol: {}".format(len('&lt;HTML&gt;')-1)) print(truth(prog.match(text, 0, 6))) print...
0
2016-10-04T15:05:55Z
39,855,924
<p>If you use the <code>match(text, startpos, endpos)</code> method of a compiled regex, it will act as if you've passed <code>match(text[startpos:endpos])</code> (well, <a href="https://docs.python.org/3/library/re.html#re.regex.search" rel="nofollow">not exactly</a>, but for the purposes of <code>$</code>, it is). Th...
1
2016-10-04T15:12:09Z
[ "python", "python-3.x" ]
Replacing Empty Cells with 0 in Python 3
39,855,838
<p>I am using the csv module to read in csv files to do data analysis. </p> <pre><code>data = [] c1 = [] c2 = [] c3 = [] data_file = csv.reader(open('file.csv')) for row in data_file: data.append(row) for i in data: c1.append(data[i][0]) c2.append(data[i][1]) c3.append(data[i][2]) </code></...
0
2016-10-04T15:07:46Z
39,855,909
<p>before appending your data you could do a check similar to what is found here : </p> <p><a href="http://stackoverflow.com/questions/34192705/python-how-to-check-if-cell-in-csv-file-is-empty">Python: How to check if cell in CSV file is empty?</a></p> <p>When the condition is true, simply append 0 to your correspond...
0
2016-10-04T15:11:15Z
[ "python", "csv" ]
Readable Time Format (w/ Good Grammar!)
39,855,889
<p>I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, <code>62</code> s...
1
2016-10-04T15:10:11Z
39,856,175
<p>Your code already works quite nicely, you just have one problem with your <code>return "now"</code> that I fixed in the code below. What else do you want your code to do?</p> <pre><code>def prettyList(human_time): if len(human_time) &gt; 1: return ' '.join([', '.join(human_time[:-1]), "and", human_time[...
2
2016-10-04T15:23:31Z
[ "python", "time", "control-flow" ]
Readable Time Format (w/ Good Grammar!)
39,855,889
<p>I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, <code>62</code> s...
1
2016-10-04T15:10:11Z
39,857,046
<p>Made some tweaks for readability :</p> <pre><code>def pretty_list(human_time): return human_time[0] if len(human_time) == 1 else ' '.join([', '.join(human_time[:-1]), "and", human_time[-1]]) def get_intervals(seconds): m, s = divmod(seconds, 60) h, m = divmod(m, 60) return ( ("hour", h), ...
2
2016-10-04T16:07:26Z
[ "python", "time", "control-flow" ]
Readable Time Format (w/ Good Grammar!)
39,855,889
<p>I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, <code>62</code> s...
1
2016-10-04T15:10:11Z
39,857,391
<p>I found it! I actually needed more intervals - the durations asked for were lengthier than I thought...</p> <pre><code>def prettyList(human_time): if len(human_time) &gt; 1: return ' '.join([', '.join(human_time[:-1]), "and", human_time[-1]]) elif len(human_time) == 1: return human_time[0] ...
0
2016-10-04T16:25:51Z
[ "python", "time", "control-flow" ]
Readable Time Format (w/ Good Grammar!)
39,855,889
<p>I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, <code>62</code> s...
1
2016-10-04T15:10:11Z
39,858,068
<p>You can try to code for each variation:</p> <pre><code>def timestamp(ctime): sec = int(ctime) if sec == 0: return "Now" m, s = divmod(sec, 60) h, m = divmod(m, 60) if h == 1: hr_t = 'Hour' else: hr_t = 'Hours' if m == 1: mn_t = 'Minute' else: mn_t = 'Minutes' if s == 1: s...
1
2016-10-04T17:09:14Z
[ "python", "time", "control-flow" ]
Readable Time Format (w/ Good Grammar!)
39,855,889
<p>I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, <code>62</code> s...
1
2016-10-04T15:10:11Z
39,870,249
<p>I think that I have covered all of the bases here but I'm sure someone will let me know if I have made an error (large or small) :)</p> <pre><code>from dateutil.relativedelta import relativedelta def convertdate(secs): raw_date = relativedelta(seconds=secs) years, days = divmod(raw_date.days, 365) # To crud...
0
2016-10-05T09:28:51Z
[ "python", "time", "control-flow" ]
How to force execution of next function
39,855,968
<p>I am attempting execute multiple functions defined by the twitterbot library. I need the code to execute one function, then the next, and then the next, or in a random order. The function, however, is designed to run in a loop.</p> <p>I rather stay away from editing the actual library, so I am looking for a solutio...
0
2016-10-04T15:14:29Z
39,856,045
<p>You can use the reference to the functions in a list then use <code>random.shuffle</code>. And you can use <code>threading.Thread</code> to run all of your functions. I am using <code>time.sleep</code> and <code>for</code> just as an example to illustrate how each thread is being executed even though the <code>for</...
1
2016-10-04T15:17:56Z
[ "python", "twitter" ]
django 1.10 get individual objects out of query
39,856,025
<p>I have a model set up for subscribers to get on our mailing list. Whenever a new blog post is created I want to email the user. How do I get individual email addresses and first names from the model to use to email, each person individually? I want their first name to be in the email.</p> <p>Here is my models.py:</...
0
2016-10-04T15:17:10Z
39,856,236
<p>You're doing some bizarre unnecessary things in your loop. <code>user</code> is already the relevant instance of EmailSubscriber; it <em>already</em> has <code>first_name</code> and <code>email</code> attributes. You don't need to set them, you just use them.</p>
1
2016-10-04T15:26:06Z
[ "python", "django", "django-email" ]
Different behaviour when operating on equivalent multidimensional lists
39,856,037
<p>When I operate on two, I think equivalent multidimensional lists, I have different outcomes. The only difference between the lists is how they are created. I'm using Python 3.4.3</p> <pre><code>&gt;&gt;&gt; b = [[1,2],[1,2]] &gt;&gt;&gt; b[0][0] += 1 &gt;&gt;&gt; b [[2, 2], [1, 2]] &gt;&gt;&gt; b = [[1,2]] * 2 &gt;...
1
2016-10-04T15:17:45Z
39,856,103
<pre><code>b = [[1,2],[1,2]] print(id(b[0])) # 139948012160968 print(id(b[1])) # 139948011731400 b = [[1,2]]*2 print(id(b[0])) # 139948012161032 print(id(b[1])) # 139948012161032 </code></pre> <p><a href="https://docs.python.org/3/library/functions.html#id" rel="nofollow">`id() shows the object's ID or the memory l...
1
2016-10-04T15:19:48Z
[ "python", "list" ]
Different behaviour when operating on equivalent multidimensional lists
39,856,037
<p>When I operate on two, I think equivalent multidimensional lists, I have different outcomes. The only difference between the lists is how they are created. I'm using Python 3.4.3</p> <pre><code>&gt;&gt;&gt; b = [[1,2],[1,2]] &gt;&gt;&gt; b[0][0] += 1 &gt;&gt;&gt; b [[2, 2], [1, 2]] &gt;&gt;&gt; b = [[1,2]] * 2 &gt;...
1
2016-10-04T15:17:45Z
39,856,142
<p>This is very-well understood behavior in Python.</p> <pre><code>a = [[], []] # two separate references to two separate lists b = [] * 2 # two references to the same list object a[0].append(1) # does not affect a[1] b[0].append(1) # affects b[0] and b[1] </code></pre> <p><a class='doc-link' href="http://stackoverfl...
0
2016-10-04T15:21:34Z
[ "python", "list" ]
Different behaviour when operating on equivalent multidimensional lists
39,856,037
<p>When I operate on two, I think equivalent multidimensional lists, I have different outcomes. The only difference between the lists is how they are created. I'm using Python 3.4.3</p> <pre><code>&gt;&gt;&gt; b = [[1,2],[1,2]] &gt;&gt;&gt; b[0][0] += 1 &gt;&gt;&gt; b [[2, 2], [1, 2]] &gt;&gt;&gt; b = [[1,2]] * 2 &gt;...
1
2016-10-04T15:17:45Z
39,856,158
<p>In the second case you're making what's known as a shallow copy of the <code>[1,2]</code> list. Essentially what that means is that somewhere in memory you have the list <code>[1,2]</code>, and when you write <code>[[1,2]]*2</code> you're saying you want two references to that same list. Thus, when you change one of...
0
2016-10-04T15:22:29Z
[ "python", "list" ]
Python script to parse a big workbook
39,856,092
<p>I have an extra sized excel file and I need to automate a task I do everyday: Add rows to the bottom with the day's date, save a new workbook, crop the old ones and save as a new file with the day's date.</p> <p>An example is today only having rows with date 04-10-2016 and the filename would be <code>[sheetname]041...
0
2016-10-04T15:19:17Z
39,856,346
<p>Based on comments below I am updating my answer. Just do:</p> <pre><code>xls.sheet_names()[0] </code></pre> <p>However, if you want to loop through the sheets, then you may want all sheet names instead of just the first one.</p>
0
2016-10-04T15:32:12Z
[ "python", "excel", "filtering" ]
Does scons customized decider function require to be class member?
39,856,184
<p>I searched from internet on how to write our own decider function in scons, as to how/when a source file should be rebuilt, like this:</p> <pre><code>Program('hello.c') def decide_if_changed(dependency,target,prev_ni): if self.get_timestamp()!=prev_ni.timestamp: dep=str(dependency) tgt=str(target) if specifi...
0
2016-10-04T15:23:47Z
39,873,940
<p>The name <code>self</code> is not defined because there is a typo in the documentation. The second line of the decider should read:</p> <pre><code>if dependency.get_timestamp()!=prev_ni.timestamp: </code></pre> <p>Implementing the <code>specific_part_of_file_has_changed()</code> method (or any similar series of st...
1
2016-10-05T12:26:42Z
[ "python", "class", "member", "scons", "self" ]
Django - Variable not being set properly
39,856,324
<p>So I am trying to run my users input through if elif statements in some arrays I setup. The goal is to have the variable set to a value if the input is found in the array. Right now the values are staying <code>None</code>. I am sure this is something silly that I am missing on my part, but any help would be greatly...
0
2016-10-04T15:30:49Z
39,856,579
<p>You have a few problems here.</p> <p>Firstly, you are using the values directly from <code>request.POST</code>. Those will always be strings. To get the values in the type specified in your form, you should use the <code>form.cleaned_data</code> dict.</p> <p>Secondly, your fields are decimals, but your arrays cont...
1
2016-10-04T15:44:15Z
[ "python", "django" ]
Django - Variable not being set properly
39,856,324
<p>So I am trying to run my users input through if elif statements in some arrays I setup. The goal is to have the variable set to a value if the input is found in the array. Right now the values are staying <code>None</code>. I am sure this is something silly that I am missing on my part, but any help would be greatly...
0
2016-10-04T15:30:49Z
39,856,607
<p>You are setting <code>chest</code> from <code>request.POST</code> which will give you a string value. Convert it to a <code>float</code> and it should work.</p>
0
2016-10-04T15:45:48Z
[ "python", "django" ]
Medium Pandas Panel to hdf5
39,856,341
<p>I'm struggling with stupid problem; until now I was working with pandas panel that fits in to the memory. Now I've to scale up the process and I run out of the memory. The solution proposed on the panda's documentation is to save everything on a hdf5 file. Well it works if your panel is smaller than the memory... ot...
0
2016-10-04T15:32:03Z
39,856,889
<p>I <em>think</em> this should work</p> <p>To write to the file:</p> <pre><code>store = pd.HDFStore(‘test.h5’, ‘w’, append = True) for partofpanel in panelparts: store.append('SP', partofpanel, data_columns = True, index = True) </code></pre> <p>To read from file:</p> <pre><code>x = pd.HDFStore(‘test.h...
0
2016-10-04T15:58:42Z
[ "python", "pandas", "panel", "hdf5" ]
unindent does not match any outer indentation level Coursera assignment
39,856,409
<p>Hi guys i just started with Python (3.5) trying to complete an assignment on Coursera and i keep getting the above error </p> <pre><code>Age = 15 if Age &gt;=15 : print ("Highschool") else if print ("No HighSchool") </code></pre>
0
2016-10-04T15:34:47Z
39,856,556
<p>Python, unlike many programming languages, relies on indentation to dictate scope. In particular, it permits tabs or certain number of spaces to indicate scope. Contiguous lines with the same indentation level are all in the same scope.</p> <p>Your code:</p> <pre><code>Age = 15 if Age &gt;=15 : print ("Highsch...
1
2016-10-04T15:43:15Z
[ "python", "python-3.x" ]
unindent does not match any outer indentation level Coursera assignment
39,856,409
<p>Hi guys i just started with Python (3.5) trying to complete an assignment on Coursera and i keep getting the above error </p> <pre><code>Age = 15 if Age &gt;=15 : print ("Highschool") else if print ("No HighSchool") </code></pre>
0
2016-10-04T15:34:47Z
39,856,568
<p>The problem is that the <code>else</code> matching an <code>if</code> MUST occur at exactly the same indentation level as the <code>if</code>. Also, there's no need for another <code>if</code> following the <code>else</code>. Try</p> <pre><code>Age = 15 if Age &gt;=15: print ("Highschool") else: print ("No ...
0
2016-10-04T15:43:52Z
[ "python", "python-3.x" ]
Execute subprocess sequentially in python
39,856,419
<p>I am trying to the following 2 commands in python one after another.</p> <pre><code>runmqsc &lt;Queuem manager name&gt; Display QL (&lt;queue name&gt;) </code></pre> <p>I can execute the rumqsc command using subprocess. </p> <pre><code>subprocess.call("runmqsc &lt;queue manager name&gt;", shell= True) </code></pr...
0
2016-10-04T15:35:03Z
39,863,043
<p>On Unix, Linux or Windows, you can simply do:</p> <pre><code>runmqsc QMgrName &lt; some_mq_cmds.mqsc &gt; some_mq_cmds.out </code></pre> <p>In the 'some_mq_cmds.mqsc' file, put your MQSC commands like: </p> <pre><code>DISPLAY QL("TEST.Q1") </code></pre>
0
2016-10-04T23:01:44Z
[ "python", "unix", "subprocess", "websphere-mq-fte" ]
Execute subprocess sequentially in python
39,856,419
<p>I am trying to the following 2 commands in python one after another.</p> <pre><code>runmqsc &lt;Queuem manager name&gt; Display QL (&lt;queue name&gt;) </code></pre> <p>I can execute the rumqsc command using subprocess. </p> <pre><code>subprocess.call("runmqsc &lt;queue manager name&gt;", shell= True) </code></pr...
0
2016-10-04T15:35:03Z
39,866,007
<p>You don't want to run to subprocess commands sequentially. When you run <code>runmqsc</code> on the command line, it takes over <code>stdin</code>, executes the commands you enter and then finally exits when you tell it to. From <a href="http://www.ibm.com/support/knowledgecenter/SSFKSJ_9.0.0/com.ibm.mq.ref.adm.doc/...
0
2016-10-05T05:26:12Z
[ "python", "unix", "subprocess", "websphere-mq-fte" ]
SWIG general questions
39,856,524
<p>I'm learning SWIG and I'm trying to understand some c++ possible situations which i haven't been able to figure out after looking the docs&amp;examples, here's my content:</p> <p>usecase1.h</p> <pre><code>#ifndef __USECASE1_H__ #define __USECASE1_H__ namespace foo_namespace { int usecase1_f1( float b, float c...
1
2016-10-04T15:41:23Z
39,868,588
<p>Make sure you're passing -c++ to swig when you run it, C++ support isn't enabled by default. See here for more details on wrapping C++ - <a href="http://www.swig.org/Doc1.3/SWIGPlus.html" rel="nofollow">http://www.swig.org/Doc1.3/SWIGPlus.html</a></p>
0
2016-10-05T08:08:25Z
[ "python", "c++", "namespaces", "inline", "swig" ]
how to compare two objects in class using __cmp__ method in Python?
39,856,601
<pre><code>class Box(object): def __init__(self, ival): self.value = ival def __cmp__(self,other): if self.value &lt; other: return elif self.value &gt; other: return 1 else:return 0 </code></pre> <p>But when I wanna test the program with :</p> <pre><code>Box(2) &lt; Box(2) Box(2) &lt...
-1
2016-10-04T15:45:29Z
39,856,645
<p>You have to compare <code>self.value</code> to <code>other.value</code>:</p> <pre><code>def __cmp__(self,other): if self.value &lt; other.value: return -1 elif self.value &gt; other.value: return 1 else:return 0 </code></pre> <p>otherwise you're comparing an integer to an object</p>
1
2016-10-04T15:47:14Z
[ "python", "python-2.7" ]
how to compare two objects in class using __cmp__ method in Python?
39,856,601
<pre><code>class Box(object): def __init__(self, ival): self.value = ival def __cmp__(self,other): if self.value &lt; other: return elif self.value &gt; other: return 1 else:return 0 </code></pre> <p>But when I wanna test the program with :</p> <pre><code>Box(2) &lt; Box(2) Box(2) &lt...
-1
2016-10-04T15:45:29Z
39,856,674
<p><a href="https://docs.python.org/2/library/functions.html#cmp" rel="nofollow">Doc reference</a> on <code>__cmp__</code>:</p> <blockquote> <p>Should <em>return</em> a <strong>negative integer</strong> if <code>self &lt; other</code>, <strong>zero</strong> if <code>self == other</code>, a <strong>positive integer</...
0
2016-10-04T15:48:27Z
[ "python", "python-2.7" ]
how to compare two objects in class using __cmp__ method in Python?
39,856,601
<pre><code>class Box(object): def __init__(self, ival): self.value = ival def __cmp__(self,other): if self.value &lt; other: return elif self.value &gt; other: return 1 else:return 0 </code></pre> <p>But when I wanna test the program with :</p> <pre><code>Box(2) &lt; Box(2) Box(2) &lt...
-1
2016-10-04T15:45:29Z
39,856,711
<p>Note that the <code>__cmp__</code> method id deprecated now - you should really use the so-called "rich comparison" methods - <code>__eq__</code> and friends.</p> <p>The error is being caused because you are attempting to compare an integer with a <code>Box</code> object, and no such comparison is defined. Perhaps ...
0
2016-10-04T15:50:23Z
[ "python", "python-2.7" ]
how to compare two objects in class using __cmp__ method in Python?
39,856,601
<pre><code>class Box(object): def __init__(self, ival): self.value = ival def __cmp__(self,other): if self.value &lt; other: return elif self.value &gt; other: return 1 else:return 0 </code></pre> <p>But when I wanna test the program with :</p> <pre><code>Box(2) &lt; Box(2) Box(2) &lt...
-1
2016-10-04T15:45:29Z
39,856,728
<p>Python's __cmp__ magic method returns an integer > 0 if greater, 0 if equal, and &lt; 0 if less. You can see that in the <a href="https://docs.python.org/2/reference/datamodel.html#object.__cmp__" rel="nofollow">docs</a>.</p> <p>Your __cmp__ function returns None for the 'less than' comparison.</p> <pre><code>clas...
2
2016-10-04T15:50:58Z
[ "python", "python-2.7" ]
sending the value of HTML checkbox to django view
39,856,699
<p>I have the following HTML page</p> <pre><code>&lt;input type="checkbox" name="checks[]" value="1"&gt;REG_AGREED_SUITE01 &lt;/label&gt; &lt;hr&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" name="checks[]" value="2"&gt;REG_AGREED_SUITE02 &lt;/label&gt; &lt;hr&gt; &lt;label class="checkb...
0
2016-10-04T15:49:49Z
39,857,010
<p>Use Jquery and ajax request to pass data to view:</p> <pre><code> $("checkbox").change(function(){ $.post("path/to/url", { checkBoxValue: $("#CheckboxID").val() } }); </code></pre>
1
2016-10-04T16:05:04Z
[ "python", "html", "django", "jenkins" ]
Why Python's RotatingFileHandler of logging module will rename log file instead of create a new one?
39,856,709
<p>I have read the <code>handlers.py</code>of Python's logging module, and found that the logic of rotating log is unreasonable. The follow picture is its comments: <a href="http://i.stack.imgur.com/0n3Ul.png" rel="nofollow"><img src="http://i.stack.imgur.com/0n3Ul.png" alt="enter image description here"></a></p> <p>I...
-1
2016-10-04T15:50:10Z
39,857,090
<p>This is so that <code>console.log</code> will always be the latest log file, you don't need any extra logic to find the newest log file. This has been standard practice for ages.</p> <p>I know that, at least on Linux/Unix, when a process opens a file, it's filename gets translated to a inode value, and that is use...
1
2016-10-04T16:09:10Z
[ "python", "logging" ]
Why Python's RotatingFileHandler of logging module will rename log file instead of create a new one?
39,856,709
<p>I have read the <code>handlers.py</code>of Python's logging module, and found that the logic of rotating log is unreasonable. The follow picture is its comments: <a href="http://i.stack.imgur.com/0n3Ul.png" rel="nofollow"><img src="http://i.stack.imgur.com/0n3Ul.png" alt="enter image description here"></a></p> <p>I...
-1
2016-10-04T15:50:10Z
39,857,169
<p>The main problem with your proposal is that the actual logging file always will be changing (first will be console.log, later will be console.log.1, after that console.log.2 etc...) so, all the programs that will read the logs, they will have to implement logic to find what is the newer file, the main problem is tha...
1
2016-10-04T16:13:14Z
[ "python", "logging" ]
Python (2.*) Tkinter - Advanced Event Handling Formatting
39,856,795
<p>I'm writing a test program to detect mouse motion within a Tkinter Window using Python 2.*. I can create the necessary widgets and bind the appropriate event handler function to the root widget as needed:</p> <pre><code>import Tkinter as tk class App: def __init__(self, master=None): self.root = master ...
1
2016-10-04T15:53:54Z
39,857,937
<p>for the combined event handling, you can do something like:</p> <pre><code>class App: holding = False def __init__(self, master): self.root = master self.root.bind("&lt;KeyPress&gt;", self.holdkey) self.root.bind("&lt;KeyRelease&gt;", self.releasekey) def holdkey(self, e): if e.char == "r" an...
1
2016-10-04T17:00:36Z
[ "python", "tkinter", "event-handling" ]
How to define class variables using the functions and variables of an instance in Python
39,856,861
<p>Is there a way to define a class variable using the variables and functions of the instance? Thanks</p> <p>The simplified code looks like this:</p> <pre><code>def ClassA(): X = self.func(self.a) def __init__(self, avalue): self.a = avalue def func(self): return self.a + 5 </code></pre...
-3
2016-10-04T15:57:17Z
39,856,921
<p>Firstly, you define a Class using <code>class</code>, not <code>def</code>.</p> <p><code>self</code> only needs to be used inside of the class' function definitions, because they change the scope. Outside of them you don't need it: <code>x = func(a)</code>.</p> <p>But your code wouldn't work anyways because the in...
0
2016-10-04T16:00:25Z
[ "python", "class", "scope" ]