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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How to repeat individual characters in strings in Python | 38,273,353 | <p>I know that </p>
<pre><code>"123abc" * 2
</code></pre>
<p>evaluates as <code>"123abc123abc"</code>, but is there an easy way to repeat individual letters N times, e.g. convert <code>"123abc"</code> to <code>"112233aabbcc"</code> or <code>"111222333aaabbbccc"</code>?</p>
| 4 | 2016-07-08T18:36:47Z | 38,273,684 | <p>And since I use numpy for everything, here we go:</p>
<pre><code>import numpy as np
n = 4
''.join(np.array(list(st*n)).reshape(n, -1).T.ravel())
</code></pre>
| 2 | 2016-07-08T19:00:09Z | [
"python",
"string"
] |
How to repeat individual characters in strings in Python | 38,273,353 | <p>I know that </p>
<pre><code>"123abc" * 2
</code></pre>
<p>evaluates as <code>"123abc123abc"</code>, but is there an easy way to repeat individual letters N times, e.g. convert <code>"123abc"</code> to <code>"112233aabbcc"</code> or <code>"111222333aaabbbccc"</code>?</p>
| 4 | 2016-07-08T18:36:47Z | 38,273,689 | <p>Or another way to do it would be using <code>map</code>: </p>
<pre><code>"".join(map(lambda x: x*7, "map"))
</code></pre>
| 3 | 2016-07-08T19:00:26Z | [
"python",
"string"
] |
Interaction between pathos.ProcessingPool and pickle | 38,273,415 | <p>I have a list of calculations I need to run. I'm parallelizing them using </p>
<pre><code>from pathos.multiprocessing import ProcessingPool
pool = ProcessingPool(nodes=7)
values = pool.map(helperFunction, someArgs)
</code></pre>
<p><code>helperFunction</code> does create a class called <code>Parameters</code>, whi... | 2 | 2016-07-08T18:40:38Z | 38,273,630 | <p>Straight from the Python <a href="https://docs.python.org/3/library/pickle.html" rel="nofollow">docs</a>. </p>
<blockquote>
<p><strong>12.1.4. What can be pickled and unpickled? The following types can be pickled:</strong></p>
<ul>
<li>None, True, and False</li>
<li>integers, floating point numbers, comp... | 3 | 2016-07-08T18:56:50Z | [
"python",
"python-2.7",
"multiprocessing",
"pickle",
"pathos"
] |
Different wx created menus in different modules | 38,273,422 | <p>I have built multiple menus each in its own module.
The menu.py module imports the sub menu then creates an instance displaying the sub menu.</p>
<p>My problem is returning to the main menu (menu.py) from the sub menu.
Heres the main menu code.
menu.py</p>
<pre><code>from gui import *
import wx
from tools import T... | 0 | 2016-07-08T18:41:12Z | 38,280,255 | <p>Fixed the problem by importing into sub menu model the menu.py module</p>
<pre><code>import menu
</code></pre>
<p>then using </p>
<pre><code>def back_click( self, event ):
self.GetParent() # This assigns parent frame to frame.
self.Close() # This then closes frame removing the main menu.
frame = men... | 0 | 2016-07-09T09:17:40Z | [
"python",
"wxpython",
"wx",
"wxformbuilder"
] |
How to count multiple unique occurrences of unique occurrences in Python list? | 38,273,531 | <p>Let's say I have a 2D list in Python: </p>
<pre><code>mylist = [["A", "X"],["A", "X"],["A", "Y"],["B", "X"],["B", "X"],["A", "Y"]]
</code></pre>
<p>In this case my "keys" would be the first element of each array ("A" or "B") and my "values" would be the second element ("X" or "Y"). At the end of my consolidation ... | 3 | 2016-07-08T18:50:29Z | 38,273,595 | <p>I think the easiest way to do this would be with Counter and defaultdict:</p>
<pre><code>from collections import defaultdict, Counter
output = defaultdict(Counter)
for a, b in mylist:
output[a][b] += 1
</code></pre>
| 11 | 2016-07-08T18:54:47Z | [
"python"
] |
How to count multiple unique occurrences of unique occurrences in Python list? | 38,273,531 | <p>Let's say I have a 2D list in Python: </p>
<pre><code>mylist = [["A", "X"],["A", "X"],["A", "Y"],["B", "X"],["B", "X"],["A", "Y"]]
</code></pre>
<p>In this case my "keys" would be the first element of each array ("A" or "B") and my "values" would be the second element ("X" or "Y"). At the end of my consolidation ... | 3 | 2016-07-08T18:50:29Z | 38,273,601 | <p>L3viathan's answer seems to be better. However, this is another approach:</p>
<pre><code>mylist = [["A", "X"],["A", "X"],["A", "Y"],["B", "X"],["B", "X"],["A", "Y"]]
dictionary = {"A": {"X": 0, "Y": 0}, "B": {"X": 0, "Y": 0}}
for x in mylist:
dictionary[x[0]][x[1]] += 1
</code></pre>
| 1 | 2016-07-08T18:54:53Z | [
"python"
] |
Reason for allowing Special Characters in Python Attributes | 38,273,603 | <p>I somewhat accidentally discovered that you can set 'illegal' attributes to an object using <code>setattr</code>. By illegal, I mean attributes with names that can't be retrieve using the <code>__getattr__</code> interface with traditional <code>.</code> operator references. They can only be retrieved via the <code>... | 2 | 2016-07-08T18:54:59Z | 38,273,895 | <p>I think that your assumption that attributes <em>must</em> be "identifiers" is incorrect. As you've noted, python objects support arbitrary attributes (not just identifiers) because for most objects, the attributes are stored in the instance's <code>__dict__</code> (which is a <code>dict</code> and therefore suppor... | 2 | 2016-07-08T19:16:02Z | [
"python",
"least-astonishment"
] |
Reason for allowing Special Characters in Python Attributes | 38,273,603 | <p>I somewhat accidentally discovered that you can set 'illegal' attributes to an object using <code>setattr</code>. By illegal, I mean attributes with names that can't be retrieve using the <code>__getattr__</code> interface with traditional <code>.</code> operator references. They can only be retrieved via the <code>... | 2 | 2016-07-08T18:54:59Z | 39,925,478 | <p>I see that feature of the language as an unintended side-effect of how the language is implemented.</p>
<p>There are several issues which suggest the feature is a side-effect.</p>
<p>First, from the "Zen of Python":</p>
<blockquote>
<p>There should be one-- and preferably only one --obvious way to do it.</p>
</... | 1 | 2016-10-07T20:40:36Z | [
"python",
"least-astonishment"
] |
How to disable autocomplete in Firefox using Selenium with Python? | 38,273,718 | <p>I am building an automated test task with Selenium. When I put the first field on a form, the rest of it is autocompleted based on previous attempts. I can clear the fields to handle this, but it would be easier if I could disable autocomplete at all.<br>
Is there a way to do this in Python Selenium?</p>
<p>Edit: I... | 1 | 2016-07-08T19:02:51Z | 38,273,881 | <p>The best option is to create a profile for Firefox which you use with the selenium webdriver:</p>
<p>Start Firefox with the '-p' option to start the profile manager and create a new custom profile.</p>
<p>In the options you can disable the autocomplete:</p>
<p>Go to 'options' > 'privacy' > 'use custom settings fo... | 2 | 2016-07-08T19:15:14Z | [
"python",
"selenium",
"web-scraping"
] |
How to disable autocomplete in Firefox using Selenium with Python? | 38,273,718 | <p>I am building an automated test task with Selenium. When I put the first field on a form, the rest of it is autocompleted based on previous attempts. I can clear the fields to handle this, but it would be easier if I could disable autocomplete at all.<br>
Is there a way to do this in Python Selenium?</p>
<p>Edit: I... | 1 | 2016-07-08T19:02:51Z | 38,274,130 | <p>You need to set <a href="http://kb.mozillazine.org/About:config_entries#Browser." rel="nofollow"><code>browser.formfill.enable</code></a> firefox profile preference to <code>false</code> to ask Firefox not to remember and autofill form input values: </p>
<pre><code>profile.set_preference("browser.formfill.enable", ... | 1 | 2016-07-08T19:32:46Z | [
"python",
"selenium",
"web-scraping"
] |
How to calculate the similarity of English words that do not appear in WordNet? | 38,273,774 | <p>A particular natural language practice is to calculate the similarity between two words using WordNet. I start my question with the following python code:</p>
<pre><code>from nltk.corpus import wordnet
sport = wordnet.synsets("sport")[0]
badminton = wordnet.synsets("badminton")[0]
print(sport.wup_similarity(badmint... | 5 | 2016-07-08T19:06:55Z | 38,274,153 | <p>You can create a semantic space from cooccurrence matrices using a tool like <strong>Dissect</strong> <a href="http://clic.cimec.unitn.it/composes/toolkit/">(DIStributional SEmantics Composition Toolkit)</a>
and then you are set to measure semantic similarity between words or phrases (if you compose words).</p>
<p>... | 6 | 2016-07-08T19:34:29Z | [
"python",
"nltk",
"similarity"
] |
How to calculate the similarity of English words that do not appear in WordNet? | 38,273,774 | <p>A particular natural language practice is to calculate the similarity between two words using WordNet. I start my question with the following python code:</p>
<pre><code>from nltk.corpus import wordnet
sport = wordnet.synsets("sport")[0]
badminton = wordnet.synsets("badminton")[0]
print(sport.wup_similarity(badmint... | 5 | 2016-07-08T19:06:55Z | 38,521,369 | <p>There are two possible other ways:</p>
<p>CBOW: continuous bag of word</p>
<p>skip gram model: This model is vice versa of CBOW model</p>
<p>look at this: <a href="https://www.quora.com/What-are-the-continuous-bag-of-words-and-skip-gram-architectures-in-laymans-terms" rel="nofollow">https://www.quora.com/What-are... | 4 | 2016-07-22T08:09:16Z | [
"python",
"nltk",
"similarity"
] |
How to calculate the similarity of English words that do not appear in WordNet? | 38,273,774 | <p>A particular natural language practice is to calculate the similarity between two words using WordNet. I start my question with the following python code:</p>
<pre><code>from nltk.corpus import wordnet
sport = wordnet.synsets("sport")[0]
badminton = wordnet.synsets("badminton")[0]
print(sport.wup_similarity(badmint... | 5 | 2016-07-08T19:06:55Z | 38,538,098 | <p>There are different models for measuring similarity, such as word2vec or glove, but you seem to be looking more for a corpus which includes social, informal phrases like 'lol'. </p>
<p>However, I'm going to bring up word2vec because it leads to what I think is an answer to your question.</p>
<p>The foundational c... | 2 | 2016-07-23T04:14:24Z | [
"python",
"nltk",
"similarity"
] |
How to calculate the similarity of English words that do not appear in WordNet? | 38,273,774 | <p>A particular natural language practice is to calculate the similarity between two words using WordNet. I start my question with the following python code:</p>
<pre><code>from nltk.corpus import wordnet
sport = wordnet.synsets("sport")[0]
badminton = wordnet.synsets("badminton")[0]
print(sport.wup_similarity(badmint... | 5 | 2016-07-08T19:06:55Z | 38,594,318 | <p>You can use other frameworks. I was trying also NLTK but finally landed on spacy (spacy.io) very fast and functional framework. There is a method for words called 'similarity' which compers to other words(but it works also for sentences, docs etc). It is implemented using word2vec. Actually I don't know how big is t... | 2 | 2016-07-26T15:39:24Z | [
"python",
"nltk",
"similarity"
] |
Python Alpha Numeric Fails, but Alpha works | 38,273,830 | <p>I am trying to strip a string of all non-numeric characters, and I have read <a href="http://stackoverflow.com/questions/23183868/why-isnt-isnumeric-working">Why isn't isnumeric working?</a>, or that I must have a unicode string. However, since <code>is.alnum()</code> and <code>is.alpha()</code> both don't requ... | 1 | 2016-07-08T19:11:17Z | 38,274,074 | <p>There are characters that are both numeric and alphabetic:</p>
<pre><code>>>> 'ã'.isalnum()
True
>>> 'ã'.isalpha()
True
>>> 'ã'.isnumeric()
True
>>> 'ã'.isalnum() and not 'ã'.isalpha()
False
</code></pre>
<p>Note that you can convert that symbol to a number using <code... | 1 | 2016-07-08T19:28:43Z | [
"python",
"string",
"unicode"
] |
Print comments of files in a zip ordered in lines, Python | 38,273,849 | <p>this is the thing. I have to make a program which will begin by reading a file in a zip, in that file it will find the name of the .txt file to read next, and so it goes on, until it reaches a file without the name of the following one, so it just prints the content.</p>
<p>I did it and works perfectly, however, af... | 1 | 2016-07-08T19:12:56Z | 38,274,026 | <p>the <code>b'...'</code> before the character means that it is a byte string. You need to decode it to produce a string:</p>
<pre><code>>>> b"abcde".decode("utf-8")
'abcde'
</code></pre>
| 0 | 2016-07-08T19:25:16Z | [
"python",
"zip"
] |
tkinter rendering wrong RGB shade in python | 38,273,916 | <p>I am using tkinter in Python (3.5.1). The problem is that actual RGB values are not corresponding to the RGB in tkinter.</p>
<p>For example in this code:</p>
<pre><code>import tkinter
root=tkinter.Tk()
root.configure(bg="white")
root.mainloop()
</code></pre>
<p>It works as expected. However if I replace "white" w... | 2 | 2016-07-08T19:16:57Z | 38,275,141 | <p>The characters in '#rrggbb' (8 bits per pixel) and '#rrrgggbbb' (12 bits per pixel) color strings are interpreted as hexadecimal, not decimal. '#ffffff' and '#fffffffff' are white. 0x255 is 597 while 0xfff is 4095, so '#255255255' turn each pixel on about 15%, so the result appears nearly black.</p>
| 3 | 2016-07-08T20:45:53Z | [
"python",
"python-3.x",
"colors",
"tkinter",
"rgb"
] |
tkinter rendering wrong RGB shade in python | 38,273,916 | <p>I am using tkinter in Python (3.5.1). The problem is that actual RGB values are not corresponding to the RGB in tkinter.</p>
<p>For example in this code:</p>
<pre><code>import tkinter
root=tkinter.Tk()
root.configure(bg="white")
root.mainloop()
</code></pre>
<p>It works as expected. However if I replace "white" w... | 2 | 2016-07-08T19:16:57Z | 38,275,147 | <p>The string <code>"#255255255"</code> is being used as <code>"#RRRGGGBBB"</code>, with each one in <strong>hexadecimal</strong>. The proper RGB string for pure white would be any of:</p>
<ul>
<li><code>#FFF</code></li>
<li><code>#FFFFFF</code></li>
<li><code>#FFFFFFFF</code></li>
<li><code>"white"</code></li>
</ul>
... | 2 | 2016-07-08T20:46:06Z | [
"python",
"python-3.x",
"colors",
"tkinter",
"rgb"
] |
TypeError when using np.savetxt to save a collection of three lists to .csv | 38,273,943 | <p>I am using Python to parse an ascii file and create a .csv with three columns of 'day', 'time' and 'z'</p>
<p>I am able to populate 'day' 'time' and 'z' with values parsed from input.txt using this:</p>
<pre><code>import numpy as np
f = open ('input.txt', 'r')
lines = f.readlines()
f.close()
day=[];time=[];z=[]
f... | 2 | 2016-07-08T19:19:23Z | 38,274,344 | <p>I can replicate your problem with:</p>
<pre><code>x=['one','two','three']
y=['a','b','c']
z=['1','2','3']
zz=list(zip(x,y,z)) # py3
zz
Out[58]: [('one', 'a', '1'), ('two', 'b', '2'), ('three', 'c', '3')]
za=np.array(zz) # make list an array; note the dtype
za
Out[60]:
array([['one', 'a', '1'],
... | 0 | 2016-07-08T19:46:50Z | [
"python",
"numpy"
] |
Why is my matplotlib bar chart compressing the x-axis when I do 'log' | 38,273,946 | <p>I am trying to make a bar chart with matplotlib for python. I can make a normal chart, but when I put it in logarithmic mode so that I can see the data better, the x-axis looks as if it is compressing. What is going on?
Note: all data records have a minimum value of 1.</p>
<pre><code> x = [t[0] for t in data]
... | 2 | 2016-07-08T19:19:26Z | 38,274,095 | <p>If you just want a log scale on the y axis and not the x use:</p>
<pre><code>import matplotlib.pyplot as plt
plt.semilogy(x,y) #plots log on y axis
plt.semilogx(x,y) #plots log on x axis
</code></pre>
<p>Alternatively, you can just set the axis' to log:</p>
<pre><code>ax = plt.subplot(224)
ax.set_xscale("log")... | 3 | 2016-07-08T19:30:39Z | [
"python",
"python-3.x",
"matplotlib",
"logarithm"
] |
Why is my matplotlib bar chart compressing the x-axis when I do 'log' | 38,273,946 | <p>I am trying to make a bar chart with matplotlib for python. I can make a normal chart, but when I put it in logarithmic mode so that I can see the data better, the x-axis looks as if it is compressing. What is going on?
Note: all data records have a minimum value of 1.</p>
<pre><code> x = [t[0] for t in data]
... | 2 | 2016-07-08T19:19:26Z | 38,274,583 | <p>It isn't compressing your x-axis; the minimum value of your second plot's y-axis is 1 (10^0), which it appears is the height of the smallest set of bars. Hence, the rightmost bars are off the <strong>y</strong> scale on your semilog plot.</p>
<p>Try adding, <em>e.g.</em>,</p>
<pre><code>plt.ylim([0.1, 100])
</code... | 1 | 2016-07-08T20:04:33Z | [
"python",
"python-3.x",
"matplotlib",
"logarithm"
] |
Understanding run time with numpy arrays? | 38,273,975 | <p>I was wondering if someone could help me understand why the following two programs run at significantly different speeds (first one takes like 1/10 of a second, second one takes like 3 seconds).</p>
<pre><code>def gaussian(x, h, m, c):
return list(h * exp(-(x-m)**2/(2*c**2)))
x = np.linspace(0, 1000, 1001)
fo... | 1 | 2016-07-08T19:21:14Z | 38,274,646 | <p>MaxU is right that the main reason is the vectorized math in numpy is faster than the scalar math in Python. Its also important to remember however that looping over a numpy array is a performance hit compared to looping over a Python list. It doesn't show up as much as the math in this case, but there are other c... | 1 | 2016-07-08T20:09:25Z | [
"python",
"numpy",
"ipython"
] |
pandas.apply expects output shape (Shape of passed values is (x,), indices imply (x,y)) | 38,274,014 | <p>So I have this pandas.Dataframe</p>
<pre><code>C1 C2 C3 C4 C5 Start End C8
A 1 - - - 1 4 -
A 2 - - - 6 10 -
A 3 - - - 11 14 -
A 4 - - - 15 19 -
</code></pre>
<p>where... | 3 | 2016-07-08T19:23:51Z | 38,293,094 | <p>Method <code>apply(func)</code> loops over rows (or cols) and applies <code>func</code> to every row. The results of <code>func</code> are then put in a new data frame or a series. If <code>func</code> returns a scalar value (as e.g. <code>sum</code> does) then it's a series. If it returns an array, list or series, ... | 0 | 2016-07-10T14:44:01Z | [
"python",
"numpy",
"pandas",
"apply",
"bioinformatics"
] |
ZeroMQ API seems to ignore my PUB's | 38,274,097 | <p>I'm hoping someone might have some more experience with <strong><code>Smart Shooter 3</code></strong> and it's API, <strong><code>ZeroMQ</code></strong>. </p>
<p><code>ZeroMQ</code> seems to be a different version of MQTT, but essentually works in the same way with publishing and subscribing to topics.</p>
<p><cod... | 2 | 2016-07-08T19:30:48Z | 38,277,532 | <h2><code>ZeroMQ</code> API is not to be blamed</h2>
<p>Supposing your statements are supported by a DSLR-under-Test experiments done as reported, the solution goes in this direction:</p>
<ol>
<li>There are several <strong><code>ZeroMQ</code></strong> <strong>F</strong>ormal <strong>C</strong>ommunication <strong>P</... | 0 | 2016-07-09T01:56:03Z | [
"python",
"camera",
"usb",
"zeromq"
] |
Plotting Dataframe column - datetime | 38,274,187 | <p>I have a datetime column with pretty random increments of time, format is:</p>
<pre><code>time
2016-07-08 11:29:30
2016-07-08 11:30:02
</code></pre>
<p>Now I convert it to datetime:</p>
<pre><code>df['time2'] = pd.to_datetime(df['time'])
</code></pre>
<p>Then I want to plot it using matplotlib, but it doesn't wo... | 3 | 2016-07-08T19:36:03Z | 38,274,225 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.html" rel="nofollow"><code>Series.plot</code></a>, so first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> from column <code... | 2 | 2016-07-08T19:38:37Z | [
"python",
"datetime",
"pandas",
"matplotlib",
"dataframe"
] |
Two forms of same class on one page in flask-wtforms | 38,274,193 | <p>In my website, I have a model Experiment that contains many Activities. I have a view where people can add or remove Activities from an Experiment.</p>
<p>I show a table with Activities that are a part of this Experiment, and a table of Activities not a part of this Experiment. Users can check which Activities they... | 1 | 2016-07-08T19:36:30Z | 38,465,126 | <p><a href="https://github.com/wtforms/wtforms/issues/284" rel="nofollow">https://github.com/wtforms/wtforms/issues/284</a></p>
<p>Solution in the above discussion.</p>
| 0 | 2016-07-19T17:40:06Z | [
"python",
"flask",
"flask-wtforms"
] |
How to extract data from Tkinter browse button in a convinient format | 38,274,238 | <p>I'm making a GUI with the <code>Tkinter</code> module in Python. I'm trying to get data from a tab separated file in a convenient format, when opened with a Browse button. I now have the following code, which saves my data in one long string (when called using <code>data.get()</code>), including <code>\t</code>'s an... | 1 | 2016-07-08T19:39:46Z | 38,279,022 | <p>If your data looked like this:</p>
<pre><code>data = """
Average readings / Time between readings = 1 / 0.10
Rel_Time\tX1\tY1(Volts)
0.812\t0.000000E+0\t3.652836E-5
1.130\t1.000000E-5\t8.870999E-3
1.435\t2.000000E-5\t1.785118E-2
"""
</code></pre>
<p>then you could do this:</p>
<pre><code>import pandas as pd
imp... | 0 | 2016-07-09T06:22:48Z | [
"python",
"tkinter"
] |
Pairwise distance python (one base vector against many others) | 38,274,339 | <p>I have a base vector (consisting of 1's and 0's) and I want to find the cosine distance to 50,000 other vectors (also consisting of 1's and 0's). I found many ways to calculate an entire matrix of pairwise distance, but I'm not interested in that. Rather, I'm just interested in getting the 50,000 distances of my bas... | 2 | 2016-07-08T19:46:41Z | 38,274,689 | <p>The vectorized operation is exactly the same as doing them individually, as long as you are careful with the axes. Here I have individual "other" vectors in each row:</p>
<pre><code>others = numpy.random.randint(0,2,(10,10))
base = numpy.random.randint(0,2,(10,1))
d = numpy.inner(base.T, others) / (numpy.linalg.nor... | 1 | 2016-07-08T20:12:12Z | [
"python",
"cosine-similarity"
] |
Removing stopwords using NLTK in python | 38,274,356 | <p>i am using NLTK to remove stopwords from a list element.
Here is my code snippet</p>
<pre><code>dict1 = {}
for ctr,row in enumerate(cur.fetchall()):
list1 = [row[0],row[1],row[2],row[3],row[4]]
dict1[row[0]] = list1
print ctr+1,"\n",dict1[row[0]][2]
list2 = [w for... | 1 | 2016-07-08T19:47:27Z | 38,274,715 | <p>First, make sure that list1 is a list of words, not an array of characters. Here I can give you a code snippet that you can leverage it maybe.</p>
<pre><code>from nltk import word_tokenize
from nltk.corpus import stopwords
english_stopwords = stopwords.words('english') # get english stop words
# test document
... | 1 | 2016-07-08T20:14:09Z | [
"python",
"nltk",
"stop-words"
] |
Removing stopwords using NLTK in python | 38,274,356 | <p>i am using NLTK to remove stopwords from a list element.
Here is my code snippet</p>
<pre><code>dict1 = {}
for ctr,row in enumerate(cur.fetchall()):
list1 = [row[0],row[1],row[2],row[3],row[4]]
dict1[row[0]] = list1
print ctr+1,"\n",dict1[row[0]][2]
list2 = [w for... | 1 | 2016-07-08T19:47:27Z | 38,274,906 | <p>First, your construction of list1 is a little peculiar to me. I think that there's a more pythonic solution:</p>
<pre><code>list1 = row[:5]
</code></pre>
<p>Then, is there a reason you're accessing row[3] with dict1[row[0]][3], rather than row[3] directly? </p>
<p>Finally, assuming that row was a list of strings,... | 0 | 2016-07-08T20:28:41Z | [
"python",
"nltk",
"stop-words"
] |
How can i clone/copy a tr (tr contains td with select and input tag ) without coping value/data? | 38,274,542 | <p>I am trying to clone/copy a <code>tr</code> (containing <code>td</code> with <code>select</code> and <code>input</code> tag) without coping value/data. I am using <code>clone().val("");</code> but its not working.</p>
<p>My code is
HTML-</p>
<pre><code><table class="table" id="new_transportation">
<tr>... | 0 | 2016-07-08T20:02:05Z | 38,274,580 | <p>You are setting value on the cloned node? Select the inputs</p>
<pre><code>new_raw.find(":input").val("");
</code></pre>
| 0 | 2016-07-08T20:04:25Z | [
"javascript",
"jquery",
"python",
"html",
"django"
] |
How to install virtualenvwrapper on El Capitan? | 38,274,551 | <p>I already installed pip and virtualenv on my mac, however I ran into issues when trying to install virtualenvwrapper. When I try to reinstall it, it says:</p>
<pre><code>The directory '/Users/mhcadmin/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. ... | 0 | 2016-07-08T20:02:59Z | 38,297,801 | <p>Figured it out. Here </p>
<p><a href="http://forums.macrumors.com/threads/how-do-you-find-folders-like-usr-local-bin-in-finder.99576/" rel="nofollow">http://forums.macrumors.com/threads/how-do-you-find-folders-like-usr-local-bin-in-finder.99576/</a></p>
<p>I found that I could access usr/local/bin by typing </p>
... | 1 | 2016-07-11T00:57:04Z | [
"python",
"bash",
"osx",
"pip",
"virtualenvwrapper"
] |
Access to private member variables/functions of a C++ class in Cython | 38,274,631 | <p>Say I have a class Foo:</p>
<pre><code>class Foo {
private:
std::string bar;
public:
Foo () {}
Foo (const std::string& bar_) { this->bar = bar_; }
std::string get_bar () { return this->bar; }
};
</code></pre>
<p>and a Foo python wrapper FooWrapper.pyx:</p>
<pre><code>from libcpp.string c... | 0 | 2016-07-08T20:08:34Z | 38,278,999 | <p>If you can't access a private member in C++, then you can't access it in Cython as well.</p>
<p>You could try a trick like this that overwrites the "private" keyword: <a href="http://stackoverflow.com/a/424125">http://stackoverflow.com/a/424125</a></p>
| 1 | 2016-07-09T06:18:28Z | [
"python",
"c++",
"cython"
] |
I met this error when executing a function - TypeError: 'dict' object is not callable | 38,274,695 | <p>Can anybody help me with this? I'm a beginner in python and programming. Thanks very much.
I got this TypeError: 'dict' object is not callable when I execute this function.</p>
<pre><code>def goodVsEvil(good, evil):
GoodTeam = {'Hobbits':1, 'Men':2, 'Elves':3, 'Dwarves':3, 'Eagles':4, 'Wizards':10}
EvilTeam = {'Or... | -1 | 2016-07-08T20:12:33Z | 38,274,722 | <p>Those parenthesis are unnecessary. You intend to use <code>.items()</code> which allows you to iterate on the keys and values of your dictionary:</p>
<pre><code>for k, val in GoodTeam.items():
# your code
</code></pre>
<p>You should replicate this change for <code>EvilTeam</code> also.</p>
| 4 | 2016-07-08T20:14:39Z | [
"python"
] |
I met this error when executing a function - TypeError: 'dict' object is not callable | 38,274,695 | <p>Can anybody help me with this? I'm a beginner in python and programming. Thanks very much.
I got this TypeError: 'dict' object is not callable when I execute this function.</p>
<pre><code>def goodVsEvil(good, evil):
GoodTeam = {'Hobbits':1, 'Men':2, 'Elves':3, 'Dwarves':3, 'Eagles':4, 'Wizards':10}
EvilTeam = {'Or... | -1 | 2016-07-08T20:12:33Z | 38,274,726 | <p>Like the error says, <code>GoodTeam</code> is a dict, but you're trying to call it. I think you mean to call its <code>items</code> method:</p>
<pre><code>for k, val in GoodTeam.items():
</code></pre>
<p>The same is true for BadTeam.</p>
<p>Note you have other errors; you're using the string format method but hav... | 2 | 2016-07-08T20:14:50Z | [
"python"
] |
Log python on Openshift | 38,274,732 | <p>I have configured my Django project on Openshift with success.</p>
<p>But somewhere in my site I launch a command tool installed by <strong>pip</strong> and I think the command failed.
But I don't find python log with</p>
<pre><code>rhc tail -a project
</code></pre>
<p>Or when I got to <strong>/var/lib/openshift/... | 0 | 2016-07-08T20:15:08Z | 38,327,207 | <p>Your log files are at the directory specified by <code>OPENSHIFT_LOG_DIR</code> environment variable. If you want to have custom log files, you should also write them there.</p>
<p>You can find more information on the log files here: <a href="https://developers.openshift.com/managing-your-applications/log-files.htm... | 0 | 2016-07-12T11:11:05Z | [
"python",
"python-2.7",
"logging",
"openshift",
"openshift-client-tools"
] |
how to turn pygame.key.get_pressed() into a key | 38,274,734 | <p>Doing <code>print pygame.key.get_pressed()</code> prints me lots of <code>0</code>'s, but is there any way that I can print those <code>0</code>'s out as a letter and then sign that letter to a variable?</p>
<p>This is what I mean:</p>
<pre><code>import pygame
pygame.init()
import time
while True:
pressed = py... | 1 | 2016-07-08T20:15:27Z | 38,277,390 | <p>You can get a list of pressed keys as strings with this piece of code: </p>
<pre><code>pressed = pygame.key.get_pressed() # already familiar with that
buttons = [pygame.key.name(k) for k,v in enumerate(pressed) if v]
print(buttons) # print list to console
</code></pre>
<p><code>pygame.key.name()</code> takes the i... | 1 | 2016-07-09T01:27:23Z | [
"python",
"pygame"
] |
What is the opposite of LoginRequiredMixin, How deny the access to a logged in user? | 38,274,769 | <p>For example, if I don't want to give access to the "Register" view if the user is already logged in?</p>
<p>I use this at the top of each view, and it works fine:</p>
<pre><code>def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
... | 1 | 2016-07-08T20:17:56Z | 38,274,865 | <p>You could create a custom '<code>LogoutRequiredMixin</code>':</p>
<pre><code>class LogoutRequiredMixin(View):
def dispatch(self, *args, **kwargs):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
return super(LogoutRequiredMixin, self).dispatch(*args, **kwargs)
<... | 0 | 2016-07-08T20:24:46Z | [
"python",
"django"
] |
What is the opposite of LoginRequiredMixin, How deny the access to a logged in user? | 38,274,769 | <p>For example, if I don't want to give access to the "Register" view if the user is already logged in?</p>
<p>I use this at the top of each view, and it works fine:</p>
<pre><code>def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
... | 1 | 2016-07-08T20:17:56Z | 38,274,988 | <p>Django has a <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.decorators.user_passes_test%60" rel="nofollow"><code>user_passes_test</code></a> decorator which I think is what you need. The decorator takes a function (with other optional ones) as argument. </p>
<p>You can write... | 3 | 2016-07-08T20:35:15Z | [
"python",
"django"
] |
What is the opposite of LoginRequiredMixin, How deny the access to a logged in user? | 38,274,769 | <p>For example, if I don't want to give access to the "Register" view if the user is already logged in?</p>
<p>I use this at the top of each view, and it works fine:</p>
<pre><code>def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
... | 1 | 2016-07-08T20:17:56Z | 38,313,561 | <p>I'm using class based views, so, I had to used a mixin:</p>
<pre><code>class NotLoggedAllow(UserPassesTestMixin):
login_url = '/profile/'
def test_func(self):
return not self.request.user.is_authenticated()
class Register_vw(NotLoggedAllow, FormView):
</code></pre>
<p>This way I just have to add ... | 0 | 2016-07-11T18:15:15Z | [
"python",
"django"
] |
Nested dictionary of namedtuples to pandas dataframe | 38,274,817 | <p>I have namedtuples defined as follows:</p>
<pre><code>In[37]: from collections import namedtuple
Point = namedtuple('Point', 'x y')
</code></pre>
<p>The nested dictionary has the following format:</p>
<pre><code>In[38]: d
Out[38]:
{1: {None: {1: Point(x=1.0, y=5.0), 2: Point(x=4.0, y=8.0)}},
2: {None: {1... | 4 | 2016-07-08T20:21:38Z | 38,282,555 | <p>There are already several answers to similar questions on SO (<a href="http://stackoverflow.com/questions/13575090/construct-pandas-dataframe-from-items-in-nested-dictionary">here</a>, <a href="http://stackoverflow.com/questions/24988131/nested-dictionary-to-multiindex-dataframe-where-dictionary-keys-are-column-labe... | 1 | 2016-07-09T13:55:04Z | [
"python",
"pandas",
"dictionary",
"dataframe",
"namedtuple"
] |
Nested dictionary of namedtuples to pandas dataframe | 38,274,817 | <p>I have namedtuples defined as follows:</p>
<pre><code>In[37]: from collections import namedtuple
Point = namedtuple('Point', 'x y')
</code></pre>
<p>The nested dictionary has the following format:</p>
<pre><code>In[38]: d
Out[38]:
{1: {None: {1: Point(x=1.0, y=5.0), 2: Point(x=4.0, y=8.0)}},
2: {None: {1... | 4 | 2016-07-08T20:21:38Z | 38,398,983 | <p>I decided to flatten the keys into a tuple (tested using pandas 0.18.1):</p>
<pre><code>In [5]: from collections import namedtuple
In [6]: Point = namedtuple('Point', 'x y')
In [11]: from collections import OrderedDict
In [14]: d=OrderedDict()
In [15]: d[(1,None,1)]=Point(x=1.0, y=5.0)
In [16]: d[(1,None,2)]=P... | 0 | 2016-07-15T14:43:35Z | [
"python",
"pandas",
"dictionary",
"dataframe",
"namedtuple"
] |
Python script stopping after changes to computer security | 38,274,935 | <p>I have a python script I use at work that checks the contents of a webpage and reports to me the changes. It used to run fine checking the site every 5 minutes and then our company switched some security software. The script will still run but will stop after an hour or so. Its not consistent, it will sometimes be... | 0 | 2016-07-08T20:31:04Z | 38,275,476 | <p>What you want is for your program to run as a daemon[1]: a background process that no longer responds to ordinary SIGKILL or even SIGHUP. You also want this daemon to restart itself on termination - effectively making it run forever. </p>
<p>Rather than write your own daemon script, it's far easier to do one of the... | 0 | 2016-07-08T21:13:47Z | [
"python"
] |
How to compare two lists with a while loop | 38,274,955 | <p>I'm trying to make a script that takes in an answer and appends it to a new list, then checks to see if the new list is the same as the other list. When these lists are the same, the while loop should break.</p>
<p><strong>NOTE</strong>: Each question should not repeat.</p>
<p>Here's my <strong>code</strong>:</p>
... | 0 | 2016-07-08T20:32:36Z | 38,275,044 | <p>I think what you really want to do is only append to your new list if the element to be added isn't already in there, so add a check for that.</p>
<pre><code>while len(answered_q) < len(questions):
question = random.choice(questions)
if question not in answered_q:
answered_q.append(question)
... | 1 | 2016-07-08T20:38:24Z | [
"python",
"list",
"while-loop",
"break",
"raw-input"
] |
How to compare two lists with a while loop | 38,274,955 | <p>I'm trying to make a script that takes in an answer and appends it to a new list, then checks to see if the new list is the same as the other list. When these lists are the same, the while loop should break.</p>
<p><strong>NOTE</strong>: Each question should not repeat.</p>
<p>Here's my <strong>code</strong>:</p>
... | 0 | 2016-07-08T20:32:36Z | 38,275,048 | <p>For one, you're getting random questions (and thus orderings), but you are comparing to a set ordering <code>[a,b,c,d]</code>.</p>
<p>To solve that with your current implementation, use a set - <code>{ "a", "b", "c", "d" }</code></p>
<p>Though personally, I would just <code>pop</code> things from one list to the o... | 1 | 2016-07-08T20:38:48Z | [
"python",
"list",
"while-loop",
"break",
"raw-input"
] |
Issue setting matplot points color and shape | 38,275,004 | <p>Whenever I run the <code>display_data</code> function (when there is data to be run after successfully answering at least one <code>calculation_game</code> question) I get an error that says:</p>
<pre><code>"ValueError: to_rgba: Invalid rgba arg "o"
to_rgb: Invalid rgb arg "o"
could not convert string to float: 'o'... | 1 | 2016-07-08T20:36:07Z | 38,275,376 | <p>Got it, just had to remove the c= part from <code>plt.scatter(x, y, c="bo")</code></p>
| 1 | 2016-07-08T21:05:16Z | [
"python",
"python-3.x"
] |
Basic Django staticfile deployment on heroku | 38,275,025 | <p><a href="http://i.stack.imgur.com/E3aVL.png" rel="nofollow"><img src="http://i.stack.imgur.com/E3aVL.png" alt="enter image description here"></a></p>
<p>I'm trying to deploy a django project to heroku (previously on openshift), but cannot get the static files right. The project structure is above. In firebug I'm ge... | 1 | 2016-07-08T20:37:26Z | 38,285,140 | <p>I had a similar problem. Changing STATIC_ROOT to BASE_DIR (from PROJECT_ROOT) seemed to help. </p>
<pre><code>STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
</code></pre>
| 1 | 2016-07-09T18:44:59Z | [
"python",
"django",
"heroku"
] |
What does list() in python? | 38,275,120 | <p>I'm learning python and have a question about the code presented below:</p>
<pre><code>nums = { 1, 2, 3, 5, 6 }
nums = { 0, 1, 2, 3 } & nums # nums = { 1, 2, 3 }
nums = filter(lambda x: x > 1, nums) # nums = { 2, 3 }
print(len(list(nums)))
</code></pre>
<p>The result of this code must be <cod... | -1 | 2016-07-08T20:44:33Z | 38,275,162 | <pre><code>nums = { 1, 2, 3, 4, 5, 6 }
</code></pre>
<p>The set containing 1 - 6.</p>
<pre><code>nums = { 0, 1, 2, 3 } & nums
</code></pre>
<p>The <a href="https://docs.python.org/3/library/stdtypes.html#set.intersection" rel="nofollow">intersection</a> of the set containing 0 - 3 and the previous set, thus { 1,... | 4 | 2016-07-08T20:47:49Z | [
"python",
"list"
] |
What does list() in python? | 38,275,120 | <p>I'm learning python and have a question about the code presented below:</p>
<pre><code>nums = { 1, 2, 3, 5, 6 }
nums = { 0, 1, 2, 3 } & nums # nums = { 1, 2, 3 }
nums = filter(lambda x: x > 1, nums) # nums = { 2, 3 }
print(len(list(nums)))
</code></pre>
<p>The result of this code must be <cod... | -1 | 2016-07-08T20:44:33Z | 38,275,183 | <p>Questions like this is where the <a href="https://docs.python.org/3/tutorial/interpreter.html" rel="nofollow">REPL</a> can come in handy:</p>
<pre><code>>>> nums = { 1, 2, 3, 5, 6 }
>>> nums
{1, 2, 3, 5, 6}
>>> nums = { 0, 1, 2, 3 } & nums
>>> nums
{1, 2, 3}
>>> nums... | 3 | 2016-07-08T20:48:55Z | [
"python",
"list"
] |
What does list() in python? | 38,275,120 | <p>I'm learning python and have a question about the code presented below:</p>
<pre><code>nums = { 1, 2, 3, 5, 6 }
nums = { 0, 1, 2, 3 } & nums # nums = { 1, 2, 3 }
nums = filter(lambda x: x > 1, nums) # nums = { 2, 3 }
print(len(list(nums)))
</code></pre>
<p>The result of this code must be <cod... | -1 | 2016-07-08T20:44:33Z | 38,275,214 | <p><code>&</code> gives the intersection of two sets. That is, </p>
<pre><code>{ 1, 2, 3, 4, 5, 6 } & { 0, 1, 2, 3 } == { 1, 2, 3 }
</code></pre>
<p><code>lambda</code> is an anonymous function. It is similar to the code</p>
<pre><code>def func(x):
return x > 1
filter(func, nums)
</code></pre>
<p><c... | 2 | 2016-07-08T20:51:18Z | [
"python",
"list"
] |
Python subclass that doesn't inherit attributes | 38,275,148 | <p>I'd like to create an Python class that superficially appears to be a subclass of another class, but doesn't actually inherit its attributes.</p>
<p>For instance, if my class is named <code>B</code>, I'd like <code>isinstance(B(), A)</code> to return <code>True</code>, as well as <code>issubclass(B, A)</code>, but ... | 3 | 2016-07-08T20:46:29Z | 38,275,187 | <p>As long as you're defining attributes in the <code>__init__</code> method and you override that method, <code>B</code> will not run the code from <code>A</code>'s <code>__init__</code> and will thus not define attributes et al. Removing methods would be harder, but seem beyond the scope of the question.</p>
| 0 | 2016-07-08T20:49:09Z | [
"python",
"class",
"oop",
"inheritance"
] |
Python subclass that doesn't inherit attributes | 38,275,148 | <p>I'd like to create an Python class that superficially appears to be a subclass of another class, but doesn't actually inherit its attributes.</p>
<p>For instance, if my class is named <code>B</code>, I'd like <code>isinstance(B(), A)</code> to return <code>True</code>, as well as <code>issubclass(B, A)</code>, but ... | 3 | 2016-07-08T20:46:29Z | 38,275,281 | <p>In Python3, override the special method <code>__getattribute__</code>. This gives you almost complete control over attribute lookups. There are a few corner cases so check the docs carefully (it's section 3.3.2 of the Language Reference Manual).</p>
| 2 | 2016-07-08T20:55:46Z | [
"python",
"class",
"oop",
"inheritance"
] |
Python subclass that doesn't inherit attributes | 38,275,148 | <p>I'd like to create an Python class that superficially appears to be a subclass of another class, but doesn't actually inherit its attributes.</p>
<p>For instance, if my class is named <code>B</code>, I'd like <code>isinstance(B(), A)</code> to return <code>True</code>, as well as <code>issubclass(B, A)</code>, but ... | 3 | 2016-07-08T20:46:29Z | 38,275,321 | <p>Use <a href="https://docs.python.org/3/library/abc.html" rel="nofollow">abstract base classes</a> to make a semingly unrelated class <code>B</code> a subclass of <code>A</code> without inheriting from it:</p>
<pre><code>from abc import ABCMeta
class A (metaclass=ABCMeta):
def foo (self):
print('foo')
c... | 3 | 2016-07-08T20:59:32Z | [
"python",
"class",
"oop",
"inheritance"
] |
Python subclass that doesn't inherit attributes | 38,275,148 | <p>I'd like to create an Python class that superficially appears to be a subclass of another class, but doesn't actually inherit its attributes.</p>
<p>For instance, if my class is named <code>B</code>, I'd like <code>isinstance(B(), A)</code> to return <code>True</code>, as well as <code>issubclass(B, A)</code>, but ... | 3 | 2016-07-08T20:46:29Z | 38,275,353 | <p>You could implement <code>__getattribute__</code> to raise AttributeErrors for the attributes that are not in B:</p>
<pre><code>class A(object):
def __init__(self):
self.foo = 1
def bar(self):
pass
class B(A):
def __init__(self):
self.baz = 42
def __getattribute__(self, at... | 2 | 2016-07-08T21:02:37Z | [
"python",
"class",
"oop",
"inheritance"
] |
Python subclass that doesn't inherit attributes | 38,275,148 | <p>I'd like to create an Python class that superficially appears to be a subclass of another class, but doesn't actually inherit its attributes.</p>
<p>For instance, if my class is named <code>B</code>, I'd like <code>isinstance(B(), A)</code> to return <code>True</code>, as well as <code>issubclass(B, A)</code>, but ... | 3 | 2016-07-08T20:46:29Z | 38,275,742 | <p>I hope this satisfies you (I think it's a bit <em>dirty</em> hack):</p>
<pre><code>class A:
attribute = "Hello"
pass
class B(A):
def __getattribute__(self, name):
if name == "__dict__":
return super().__getattribute__(name)
if name in type(self).__dict__:
return ... | 1 | 2016-07-08T21:37:42Z | [
"python",
"class",
"oop",
"inheritance"
] |
Python Linked List Query | 38,275,181 | <p>Here is the code I am having some issues with:</p>
<pre><code>class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class Solution(object):
def insert(self, head, data):
if head == None:
head = Node(data)
else:
current = head... | 2 | 2016-07-08T20:48:44Z | 38,275,253 | <p>No, a new current object is not being created, but rather the variable current is being reassigned until it hits the last element in the list, and only then is a new Node object created and assigned to the end of the list.</p>
| 1 | 2016-07-08T20:53:54Z | [
"python",
"object",
"linked-list"
] |
Python Linked List Query | 38,275,181 | <p>Here is the code I am having some issues with:</p>
<pre><code>class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class Solution(object):
def insert(self, head, data):
if head == None:
head = Node(data)
else:
current = head... | 2 | 2016-07-08T20:48:44Z | 38,275,274 | <p>Current is a local variable that <em>points</em> to a Node object. Overwriting current doesn't destroy the Node, it just makes current point to something else. As long as you have a reference to what current used to point to, you're fine. In this case, because you keep a hold of <em>head</em>, you're always able to ... | 1 | 2016-07-08T20:55:00Z | [
"python",
"object",
"linked-list"
] |
convert unicode ucs4 into utf8 | 38,275,191 | <p>I have a value like u'\U00000958' being returned back from a database and I want to convert this string to <code>utf8</code>. I try something like this:</p>
<pre><code>cp = u'\\U00000958'
value = cp.decode('unicode-escape').encode('utf-8')
print 'Value: " + value
</code></pre>
<p>I get this error:</p>
<blockquot... | 0 | 2016-07-08T20:49:23Z | 38,275,666 | <p>For unicode issues, it often helps to specify python 2 versus python 3, and also how one came to get a particular representation.</p>
<p>It is not clear from the first sentence what the actual value is, as opposed to how it is displayed. It is unclear if the <code>value like u'\\U00000958'</code> is a 1 char unico... | 0 | 2016-07-08T21:30:34Z | [
"python",
"unicode",
"encoding",
"utf-8"
] |
Python How to Initialize Reader Object in Class Definition | 38,275,242 | <p>I want to make a singleton class that gathers data from a csv file, and in order to do that, it needs to have a data member of type DictReader; but I am not sure how I would initialize this member in the class definition, as it can only be initialized like so:</p>
<pre><code>with open('sourceFile.csv') as source:
... | 4 | 2016-07-08T20:53:26Z | 38,275,411 | <p>Are you looking for something like:</p>
<pre><code>class MySingleton(object):
def __init__(self, source):
self.my_reader = DictReader(source)
if __name__ == '__main__':
singleton = MySingleton(sourcefile)
for row in singleton.my_reader:
# do stuff
</code></pre>
| 1 | 2016-07-08T21:07:52Z | [
"python",
"class"
] |
PyCharm File Number Denotation | 38,275,243 | <p>I noticed a number inside a square that looks like [9] next to a file that I have in Pycharm Community Edition on the dock on the left side that I do not understand. I am unable to click on it or read any more information about it. I couldn't find anything on Pycharm's website or any of their documentation. I am sli... | 4 | 2016-07-08T20:53:28Z | 38,285,332 | <p>That's a numbered bookmark. You can remove it by selecting the file in Project view and pressing Ctrl-Shift-9.</p>
| 1 | 2016-07-09T19:04:08Z | [
"python",
"pycharm"
] |
Pygame Raycasting for line of sight | 38,275,310 | <p>I am making a 2d top-down shooter game and ideally I would like the enemies to only shoot at the player when they see him/her (so the player could hide behind a crate etc.)</p>
<p>I have done research and I think the best way to do this would be raycasting. I have not been able to find a good example of raycasting ... | 0 | 2016-07-08T20:58:21Z | 38,292,987 | <p>I am assuming the variables 'player' and 'person' are the positions of the player and enemy? If so, the code you have added will check if either the two objects: </p>
<ul>
<li>are in the same x position (person[0] == player[0])</li>
<li>are in the same y position (person[1] == player[1]) </li>
<li>have equal x and ... | 0 | 2016-07-10T14:32:27Z | [
"python",
"pygame",
"raycasting"
] |
How to make a loop with functions outside a class | 38,275,352 | <p>I'm kinda new to programming and I'm stuck at this problem:</p>
<p>I want to make a loop of functions outside their parent class, until the life value reaches 0, then I want the program to end.</p>
<pre><code>class Enemy():
def __init__(self, name, life):
self.name = name
self.life = life
... | 2 | 2016-07-08T21:02:34Z | 38,275,448 | <p>Use a while loop in your main function. In order to call those two functions you have defined until the self.life is 0 a while loop would work as it checks the condition until it is true unlike an if statement which will only check once. I am assuming you also are defining an int value for life. </p>
<p>Try this in... | 3 | 2016-07-08T21:10:41Z | [
"python",
"python-3.x"
] |
How to get the first and last values from the dataframe column using a function | 38,275,373 | <p>I need to get the first value and last values for the following using a function similar to the way I'm getting the <code>max()</code> and <code>min()</code> values from a Pandas DF column. So this part of my code works perfectly to give me the max and min:</p>
<pre><code>day_high = day_session['High'].rolling(win... | 1 | 2016-07-08T21:04:44Z | 38,275,600 | <p>Have you tried to resample using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.ohlc.html#pandas.core.groupby.GroupBy.ohlc" rel="nofollow"><code>ohlc</code></a>?</p>
<pre><code>df = pd.DataFrame(
{'price': [100, 101, 102, 103]},
index=pd.to_datetime(['2016-07-08 1... | 1 | 2016-07-08T21:24:12Z | [
"python",
"pandas"
] |
How to parse the following input in Python | 38,275,388 | <p>How to parse the following python dictionary as key value pair?</p>
<pre><code>{'restiming[0][rt_dur]': '9.490000000000009',
'restiming[1][rt_fet_st]': '116.625',
'restiming[0][rt_st]': '116.625',
'restiming[0][rt_name]': 'http://localhost:63342/Beacon/boomerang/boomerang.js',
'restiming[1][rt_in_type]': '... | -1 | 2016-07-08T21:06:22Z | 38,275,523 | <p>Try regular expression <code>re</code>,</p>
<pre><code>In [36]: import re
In [37]: {re.sub('restiming\[\d+\]\[(.*)\]', r'\1', k):v for k,v in data.iteritems()}
Out[37]:
{'rt_dur': '9.490000000000009',
'rt_fet_st': '116.625',
'rt_in_type': 'script',
'rt_name': 'http://localhost:63342/Beacon/boomerang/boomerang.js... | 1 | 2016-07-08T21:17:27Z | [
"python"
] |
Python 2.7 QT Designer, take the data from a line edit when a button is pressed, and set the text in a read only line edit? | 38,275,466 | <p>Sorry for the long title, I'm just pretty lost. So I'm making a script to encrypt a message and give a key to decrypt it. The next tab on the program would be you give it an encrypted message and a decryption key and it will decrypt. So I have all of the encryption figured out, I just need to know how to set text bo... | 1 | 2016-07-08T21:13:04Z | 38,275,507 | <p>You can use the signals that QLineEdit emits when changed or edited, <code>textChanged() and textEdited()</code> and connect these signals to slots that would encrypt the message, if I'm understanding your problem correctly. After pressing the submit button, you can change the QLineEdit to be read only by the method... | 0 | 2016-07-08T21:16:13Z | [
"python",
"qt",
"encryption"
] |
Send table as an email body (not attachment ) in Python | 38,275,467 | <p>My input file is a CSV file and by running some python script which consists of the python Tabulate module, I have created a table that looks like this below:-</p>
<p><a href="http://i.stack.imgur.com/Lmjt1.png" rel="nofollow">tabulate_output</a>
or </p>
<pre><code>| Attenuation | Avg Ping RTT in ms | TCP U... | 0 | 2016-07-08T21:13:11Z | 38,276,251 | <p>This code sends the message in the typical plain text plus html multipart/alternative format. If your correspondent reads this in an html-aware mail reader, he's see the HTML table. If he reads it plain-text reader, he'll see the plain text version.</p>
<p>In either case, he will see the data included in the body o... | 1 | 2016-07-08T22:30:59Z | [
"python",
"email",
"html-email"
] |
sci-kit learn agglomerative clustering error | 38,275,541 | <p>I am trying to do agglomerative clustering using sklearn. In the fitting step, I get this error. The error doesn't show up all the time, if I change the number of datapoints then I may not get the error and the agglomerative clustering. I'm not too sure how to debug this. I've ensured that there is no NaN values in ... | 1 | 2016-07-08T21:19:17Z | 38,276,818 | <p>This is an overflowing problem, note that 4999850001 - 2**32 = 704882705 (last line of your output). Something is too big to fit in a 32-bit integer. You should try using fewer data points.</p>
| 1 | 2016-07-08T23:40:28Z | [
"python",
"scikit-learn",
"hierarchical-clustering"
] |
Adding Color to new style ipython (v5) prompt | 38,275,585 | <p>Update to the newly release ipython5 today. Started up the interactive prompt and received:</p>
<pre><code>/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py:440: UserWarning: As of IPython 5.0 `PromptManager` config will have no effect and has been replaced by TerminalInteractiveShell.prompts_... | 6 | 2016-07-08T21:22:59Z | 38,277,813 | <pre><code>from IPython.terminal.prompts import Prompts, Token
import os
class MyPrompt(Prompts):
def in_prompt_tokens(self, cli=None): # default
return [
(Token.Prompt, 'In ['),
(Token.PromptNum, str(self.shell.execution_count)),
(Token.Prompt, ']: '),
]
... | 2 | 2016-07-09T02:55:03Z | [
"python",
"python-3.x",
"ipython"
] |
Why do decorators have to be declared before they're called, but functions don't? | 38,275,604 | <p>I have the following example in Python 2.7:</p>
<pre><code>import time
@timing
def my_test_function():
return 5+5
def timing(f):
def wrap(*args):
time1 = time.time()
ret = f(*args)
time2 = time.time()
print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
... | 2 | 2016-07-08T21:24:28Z | 38,275,647 | <p>Functions <em>do</em> have to be declared before they are called. The only difference is that decorators are usually called earlier than other functions.</p>
<p>In your example, the decorator is called when <code>my_test_function</code> is created (likely import time) whereas <code>b</code> doesn't get called unti... | 6 | 2016-07-08T21:28:44Z | [
"python",
"decorator"
] |
Python - Accumulated Value of Annual Investment | 38,275,625 | <p>I have a program (futval.py) that will calculate the value of an investment after 10 years. I want to modify the program so that instead of calculating the value of a one time investment after 10 years, it will calculate the value of an annual investment after 10 years. I want to do this without using an accumulat... | 1 | 2016-07-08T21:26:56Z | 38,275,821 | <p>Okay, if you try doing some math you will see the solution yourself. For the first year we have:</p>
<pre><code>new_value = investment*(1 + apr)
</code></pre>
<p>For the second:</p>
<pre><code>new_second_value = (new_value + investment)*(1+apr)
</code></pre>
<p>or</p>
<pre><code>new_second_value = (investment*(... | 1 | 2016-07-08T21:45:46Z | [
"python",
"python-2.3"
] |
Python - Accumulated Value of Annual Investment | 38,275,625 | <p>I have a program (futval.py) that will calculate the value of an investment after 10 years. I want to modify the program so that instead of calculating the value of a one time investment after 10 years, it will calculate the value of an annual investment after 10 years. I want to do this without using an accumulat... | 1 | 2016-07-08T21:26:56Z | 38,276,645 | <p>Well, you don't need an accumulator, but you still need a temporary variable to hold the original value of the periodic investment:</p>
<pre><code>def main():
print "This program calculates the future value",
print "of a 10-year investment."
investment = input("Enter the initial investment: ")
apr ... | 0 | 2016-07-08T23:18:04Z | [
"python",
"python-2.3"
] |
In Python OOP When Calling Class Variable Should self or Class Name be used? | 38,275,636 | <p>I am very rusty on OOP. Now my question is, how exactly would I go about calling a class variable?</p>
<p>I know to call an <code>__init__</code> variable you would do the following:</p>
<pre><code>class HelloWorld:
def __init__(self):
self.hello = "Hello"
def world(self):
print self.hell... | 1 | 2016-07-08T21:28:07Z | 38,275,686 | <p>Generally, you'll want to use <code>self</code> here. This allows for a few nice "tricks" to be played. e.g. You can override <code>hello</code> in a subclass:</p>
<pre><code>class GreetWorld(HelloWorld):
hello = "Greetings"
</code></pre>
<p>Or you can re-set the attribute on a per-instance basis:</p>
<pre>... | 1 | 2016-07-08T21:32:36Z | [
"python",
"oop"
] |
In Python OOP When Calling Class Variable Should self or Class Name be used? | 38,275,636 | <p>I am very rusty on OOP. Now my question is, how exactly would I go about calling a class variable?</p>
<p>I know to call an <code>__init__</code> variable you would do the following:</p>
<pre><code>class HelloWorld:
def __init__(self):
self.hello = "Hello"
def world(self):
print self.hell... | 1 | 2016-07-08T21:28:07Z | 38,275,692 | <p>You can use both, the results are well defined and in that case they will do the same.</p>
<p>Note however that this changes when you have derived classes:</p>
<pre><code>class Base:
hello = 'A'
def greet(self):
print(self.hello)
def greet2(self):
print(Base.hello)
class Derived(Bas... | 0 | 2016-07-08T21:33:01Z | [
"python",
"oop"
] |
In Python OOP When Calling Class Variable Should self or Class Name be used? | 38,275,636 | <p>I am very rusty on OOP. Now my question is, how exactly would I go about calling a class variable?</p>
<p>I know to call an <code>__init__</code> variable you would do the following:</p>
<pre><code>class HelloWorld:
def __init__(self):
self.hello = "Hello"
def world(self):
print self.hell... | 1 | 2016-07-08T21:28:07Z | 38,275,731 | <p><code>HelloWorld.hello</code> does not require an instance of <code>HelloWorld</code> to be used. This might be used in a case where a value should be common among all instances of <code>HelloWorld</code>. <code>self.hello</code> belongs to the instance and could be different across instances of <code>HelloWorld</co... | 3 | 2016-07-08T21:36:53Z | [
"python",
"oop"
] |
In Python OOP When Calling Class Variable Should self or Class Name be used? | 38,275,636 | <p>I am very rusty on OOP. Now my question is, how exactly would I go about calling a class variable?</p>
<p>I know to call an <code>__init__</code> variable you would do the following:</p>
<pre><code>class HelloWorld:
def __init__(self):
self.hello = "Hello"
def world(self):
print self.hell... | 1 | 2016-07-08T21:28:07Z | 38,275,790 | <p>Both of them will work. When you have <code>self</code> passed in to the method <code>self == HelloWorld</code></p>
<pre><code>class HelloWorld:
hello = "hello"
def world(self):
print self.hello + "World"
</code></pre>
<p>But when self is not passed in to method i.e, static method then use </p>
<p... | 0 | 2016-07-08T21:42:04Z | [
"python",
"oop"
] |
Swift Equivant to Python's - hash.digest().encode('base64').strip()? | 38,275,717 | <p>Basically I'm trying to convert my Python code to Swift, and can't seem to find an equivalent/alternative for this line of code (md5 Hash Digest to base64):</p>
<pre><code>return hash.digest().encode('base64').strip()
</code></pre>
<p>Source: <a href="http://stackoverflow.com/a/32041572/3697446">http://stackoverf... | 1 | 2016-07-08T21:35:27Z | 38,276,358 | <p>As you are saying yourself, your <code>md5(string:)</code> is an equivalent to <code>hexdigest</code>, not <code>digest</code>.
The result of md5 digest is a byte sequence, and you'd better hold it in <code>NSData</code> in Swift.</p>
<p>With defining this:</p>
<pre><code>func md5Data(string string: String) -> ... | 1 | 2016-07-08T22:43:36Z | [
"python",
"ios",
"swift",
"base64",
"md5"
] |
csv file not downloading upon http response | 38,275,798 | <p>I am trying to convert a dictionary to csv and then download the csv file on the fly. When i return the response, I see the rows in the httpresponse. But I want it to download the content into a csv file in my local machine.</p>
<pre><code>def export_csv_from_dict(data):
response = HttpResponse(content_type='te... | 0 | 2016-07-08T21:42:47Z | 38,276,298 | <p>There is a sloppy error I have spotted in the base your code:</p>
<blockquote>
<p><code># rows is a list of dictionary [{'name': 'a'}, {'name': 'b'}]</code></p>
</blockquote>
<p>This seems to be a fatal construction.</p>
<ul>
<li><p>If you have many dictionaries with the same key, why don't you use a list which... | 0 | 2016-07-08T22:35:07Z | [
"python",
"django",
"httpresponse",
"export-to-csv"
] |
csv file not downloading upon http response | 38,275,798 | <p>I am trying to convert a dictionary to csv and then download the csv file on the fly. When i return the response, I see the rows in the httpresponse. But I want it to download the content into a csv file in my local machine.</p>
<pre><code>def export_csv_from_dict(data):
response = HttpResponse(content_type='te... | 0 | 2016-07-08T21:42:47Z | 38,276,439 | <p>Have you tried using simple hard coded rows data? Following code based on your example should work fine. If it works, then there must be problem in populating rows data on the fly, which would need some extra information from you on how your get_rows_data function is working.</p>
<pre><code>def export_csv_from_dict... | 1 | 2016-07-08T22:51:18Z | [
"python",
"django",
"httpresponse",
"export-to-csv"
] |
Timegrouper of Timegrouper | 38,275,802 | <p>Hi I have the following Timegrouper dataframe where the maximum value is calculated for every quarter of an hour from data that was separated per minute:</p>
<pre><code>in:
newdf2 = newdf.groupby(pd.TimeGrouper(freq='15T')).max().fillna(0)
Out:
Count
time
2016-04-20 05... | 1 | 2016-07-08T21:43:01Z | 38,275,836 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.resample.Resampler.ffill.html" rel="nofollow"><code>ffill</code></a>:</p>
<pre><... | 2 | 2016-07-08T21:47:31Z | [
"python",
"python-2.7",
"pandas"
] |
how to declare a list element as REGEX | 38,275,849 | <p>I want to declare a regex as r'tata.xnl.*-dev.1.0' in the list element and it should match <code>tata.xnl.1.0-dev.1.0</code>,how to solve this problem?.</p>
<pre><code>productline = '8.H.5'
pl_component_dict = {'8.H.5': [r'tata.xnl.*-dev.1.0','tan.xnl.1.0-dev.1.0'],
'8.H.7':['']
... | 1 | 2016-07-08T21:49:00Z | 38,275,927 | <p>Make the dictionary value(s) compiled <code>re</code> that can match your string:</p>
<pre><code>import re
productline = '8.H.5'
pattern = re.compile(r'tata.xnl.\d\.\d-dev.1.0')
pl_component_dict = {'8.H.5': pattern}
component_branch = "tata.xnl.1.0-dev.1.0"
if pl_component_dict[productline].match(component_bra... | 0 | 2016-07-08T21:57:21Z | [
"python"
] |
how to declare a list element as REGEX | 38,275,849 | <p>I want to declare a regex as r'tata.xnl.*-dev.1.0' in the list element and it should match <code>tata.xnl.1.0-dev.1.0</code>,how to solve this problem?.</p>
<pre><code>productline = '8.H.5'
pl_component_dict = {'8.H.5': [r'tata.xnl.*-dev.1.0','tan.xnl.1.0-dev.1.0'],
'8.H.7':['']
... | 1 | 2016-07-08T21:49:00Z | 38,275,956 | <p>Prepending <code>r</code> to a string does not make it a regular expression - it makes it a <a href="http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l">raw string literal</a>. </p>
<p>You need to <em>compile</em> it into a regular expression using... | 0 | 2016-07-08T22:00:30Z | [
"python"
] |
how to declare a list element as REGEX | 38,275,849 | <p>I want to declare a regex as r'tata.xnl.*-dev.1.0' in the list element and it should match <code>tata.xnl.1.0-dev.1.0</code>,how to solve this problem?.</p>
<pre><code>productline = '8.H.5'
pl_component_dict = {'8.H.5': [r'tata.xnl.*-dev.1.0','tan.xnl.1.0-dev.1.0'],
'8.H.7':['']
... | 1 | 2016-07-08T21:49:00Z | 38,276,175 | <p>Here is one way using <a href="https://docs.python.org/2/library/re.html#re.search" rel="nofollow"><code>re.search</code></a>:</p>
<pre><code>import re
class ReList:
def __init__(self, thinglist):
self.list = thinglist
def contains(self, thing):
re_list = map( lambda x: re.search( x, thing)... | 0 | 2016-07-08T22:22:33Z | [
"python"
] |
Sound duration isn't accurate enough with Pygame.mixer.sound | 38,275,859 | <p>I want to generate a series of audio cues at specific frequency and duration for my neuroscience research. After some googling, I find a Python module called Pygame that seems able to get the job done. </p>
<pre><code>sound = pygame.sndarray.make_sound(sample_array) #sample_array is a one-second sine wave I creat... | 2 | 2016-07-08T21:50:14Z | 38,358,225 | <p>It looks like this question doesn't attract much attention :(</p>
<p>I'm posting my workaround here in case someone wants to know. If I use<code>sound.play(maxtime = 100)</code>, or<code>sound.play(-1)</code>then<code>time.delay(100)</code>, the actual duration of the sound is never precisely 100ms. My workaround i... | 0 | 2016-07-13T17:30:28Z | [
"python",
"audio",
"pygame"
] |
Do threads in python need to be joined to avoid leakage? | 38,275,944 | <p>I understand the purpose of joining a thread, I'm asking about resource use. My specific use-case here is that I have a long-running process that needs to spawn many threads, and during operation, checks if they have terminated and then cleans them up. The main thread waits on inotify events and spawns threads bas... | 2 | 2016-07-08T21:59:33Z | 38,276,146 | <p>TLDR: No.</p>
<p><code>Thread.join</code> merely waits for the thread to end, it does not perform cleanup. Basically, each <code>Thread</code> has a lock that is released when the thread is cleaned up. <code>Thread.join</code> just waits for the lock to be released.</p>
<p>There is some minor cleanup done, namely ... | 0 | 2016-07-08T22:18:43Z | [
"python",
"multithreading",
"python-multithreading"
] |
Fitting piecewise function: running into NaN problems due to boolean array indexing | 38,275,980 | <p>So I've been trying to fit to an exponentially modified gaussian function (if interested, <a href="https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution" rel="nofollow">https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution</a>)</p>
<pre><code>import numpy as np
import scipy... | 0 | 2016-07-08T22:02:23Z | 38,276,182 | <p>One thing you could do is create a mask and reuse it so it wouldn't need to be evaluated twice. Another idea is to use the nan_to_num only once at the end</p>
<pre><code>mask = (z<0)
y += (k1 * np.exp(n1) * sps.erfc(z)) * (mask)
y += (k2 * np.exp(n2) * sps.erfcx(z)) * (~mask)
y = numpy.nan_yo_num(y)
</code></pre... | 0 | 2016-07-08T22:23:13Z | [
"python",
"numpy",
"scipy",
"ipython"
] |
Fitting piecewise function: running into NaN problems due to boolean array indexing | 38,275,980 | <p>So I've been trying to fit to an exponentially modified gaussian function (if interested, <a href="https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution" rel="nofollow">https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution</a>)</p>
<pre><code>import numpy as np
import scipy... | 0 | 2016-07-08T22:02:23Z | 38,276,212 | <p>How about using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">numpy.where</a> with something like: <code>np.where(z >= 0, sps.erfcx(z), sps.erfc(z))</code>. I'm no numpy expert, so don't know if it's efficient. Looks elegant at least!</p>
| 3 | 2016-07-08T22:25:55Z | [
"python",
"numpy",
"scipy",
"ipython"
] |
Trying to move a sprite in pygame | 38,275,988 | <p>I'm trying to make a bullet move in Pygame. Apologies if it has a simple fix, I just can't think at the moment.</p>
<p>This is what I run when I detect that the "1" button is pressed.</p>
<pre><code> if pygame.event.get().type == KEYDOWN and e.key == K_1:
bullet = Bullet()
bullet.rect.x = player.rect.x
... | 0 | 2016-07-08T22:03:13Z | 38,276,493 | <p>You need to update all bullets on every game tick, not just when a player presses a button.</p>
<p>So, you'll want something like this as your event loop:</p>
<pre><code>clock = pygame.time.Clock()
while True:
clock.tick(60)
for event in pygame.event.get():
if event == KEYDOWN and event.key == K_1:... | 1 | 2016-07-08T22:58:24Z | [
"python",
"pygame",
"sprite"
] |
import statement is not working when running python script from the command line | 38,276,027 | <p>I need to run a python script from the command line (OS = Debian wheezy, python -version 3.5).</p>
<p>I used PyCharm (community edition) to write the script and it is working from inside the IDE.</p>
<p>I used <code>sys.path.append</code> command to add the directory containing the package I want, then followed it... | -1 | 2016-07-08T22:06:13Z | 38,343,147 | <p>I found the answer for my question above, and the problem was much easier than I thought.</p>
<p><strong>Addressing the Problem</strong></p>
<ul>
<li>having many python packages in different directories</li>
<li>your script needs some/all packages, that are not in the standard lib-directory for your python install... | 0 | 2016-07-13T05:15:13Z | [
"python",
"shell",
"command-line",
"python-import"
] |
Unpack a Python tuple from left to right? | 38,276,068 | <p>Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right? </p>
<p>For example for </p>
<pre><code>j = 1,2,3,4,5,6,7
(1,2,3,4,5,6,7)
v,b,n = j[4:7]
</code></pre>
<p>Can I modify the slice notation so that <code>v = j[6], b=j[5], n=j[4]</code> ? </p>
<p>I realise I can ju... | 18 | 2016-07-08T22:10:02Z | 38,276,095 | <p>This should do:</p>
<pre><code>v,b,n = j[6:3:-1]
</code></pre>
<p>A step value of <code>-1</code> starting at <code>6</code></p>
| 45 | 2016-07-08T22:12:42Z | [
"python",
"python-3.x",
"tuples",
"iterable-unpacking"
] |
Unpack a Python tuple from left to right? | 38,276,068 | <p>Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right? </p>
<p>For example for </p>
<pre><code>j = 1,2,3,4,5,6,7
(1,2,3,4,5,6,7)
v,b,n = j[4:7]
</code></pre>
<p>Can I modify the slice notation so that <code>v = j[6], b=j[5], n=j[4]</code> ? </p>
<p>I realise I can ju... | 18 | 2016-07-08T22:10:02Z | 38,276,235 | <pre><code> n,b,v=j[4:7]
</code></pre>
<p>will also work. You can just change the order or the returned unpacked values</p>
| 10 | 2016-07-08T22:28:51Z | [
"python",
"python-3.x",
"tuples",
"iterable-unpacking"
] |
Unpack a Python tuple from left to right? | 38,276,068 | <p>Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right? </p>
<p>For example for </p>
<pre><code>j = 1,2,3,4,5,6,7
(1,2,3,4,5,6,7)
v,b,n = j[4:7]
</code></pre>
<p>Can I modify the slice notation so that <code>v = j[6], b=j[5], n=j[4]</code> ? </p>
<p>I realise I can ju... | 18 | 2016-07-08T22:10:02Z | 38,276,396 | <p>You could ignore the first after reversing and use <a href="https://www.python.org/dev/peps/pep-3132/">extended iterable unpacking</a>:</p>
<pre><code>j = 1, 2, 3, 4, 5, 6, 7
_, v, b, n, *_ = reversed(j)
print(v, b, n)
</code></pre>
<p>Which would give you:</p>
<pre><code>6 5 4
</code></pre>
<p>Or if you want... | 9 | 2016-07-08T22:46:47Z | [
"python",
"python-3.x",
"tuples",
"iterable-unpacking"
] |
Unpack a Python tuple from left to right? | 38,276,068 | <p>Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right? </p>
<p>For example for </p>
<pre><code>j = 1,2,3,4,5,6,7
(1,2,3,4,5,6,7)
v,b,n = j[4:7]
</code></pre>
<p>Can I modify the slice notation so that <code>v = j[6], b=j[5], n=j[4]</code> ? </p>
<p>I realise I can ju... | 18 | 2016-07-08T22:10:02Z | 38,276,534 | <p>In case you want to keep the original indices (i.e. don't want to bother with changing 4 and 7 to 6 and 3) you can also use:</p>
<pre><code>v, b, n = (j[4:7][::-1])
</code></pre>
| 11 | 2016-07-08T23:04:10Z | [
"python",
"python-3.x",
"tuples",
"iterable-unpacking"
] |
Python Adding one hour to time.time() | 38,276,130 | <p>Hi i want to add one hour to Python time.time().</p>
<p>My current way of doing it is :</p>
<pre><code>t = int(time.time())
expiration_time = t + 3600
</code></pre>
<p>Is this considered bad for any reasons?
If so is there a better way of doing this easily.</p>
| 1 | 2016-07-08T22:16:55Z | 38,276,288 | <p>It's not considered bad for any reason . I do it this way many times . Here is an example :</p>
<pre><code>import time
t0 = time.time()
print time.strftime("%I %M %p",time.localtime(t0))
03 31 PM
t1 = t0 + 60*60
print time.strftime("%I %M %p",time.localtime(t1))
04 31 PM
</code></pre>
<p>Here are other ways of doi... | 3 | 2016-07-08T22:34:35Z | [
"python",
"python-2.7"
] |
Python Adding one hour to time.time() | 38,276,130 | <p>Hi i want to add one hour to Python time.time().</p>
<p>My current way of doing it is :</p>
<pre><code>t = int(time.time())
expiration_time = t + 3600
</code></pre>
<p>Is this considered bad for any reasons?
If so is there a better way of doing this easily.</p>
| 1 | 2016-07-08T22:16:55Z | 38,276,303 | <p>This depends entirely on what you use this for.</p>
<p>If you wish to add a plain hour, as in 60*60 seconds, <code>t + 3600</code> is fine. For readability, <code>t + 60*60</code> may be preferable. It doesn't make a difference to the interpreter, which precompiles constants.</p>
<p>If you wish to add an hour on t... | -2 | 2016-07-08T22:35:43Z | [
"python",
"python-2.7"
] |
How to sort a dict by one of its values in Python? | 38,276,152 | <p>I have a dict like this:
key is a string,
value is a list of strings</p>
<pre><code> my_dict = {
'key1': [value11, value12, value13],
'key2': [value21, value22, value23],
'key3': [value31, value32, value33],
'key4': [value41, value42, value43]
}
</code></pre>
<p>e.g.</p>
<pre><code>dict_0 = {
'... | 0 | 2016-07-08T22:19:27Z | 38,276,199 | <p>Dictionaries are not ordered data structures, if you want a sorted one you can use <code>OrderedDict()</code> function from <code>collections</code> module.</p>
<pre><code>>>> dict_0 = {
... 'key1' : ['lv', 2, 'abc'],
... 'key2' : ['ab', 4, 'abc'],
... 'key3' : ['xj', 1, 'abc'],
... 'key4' : ['om', 3, 'abc... | 5 | 2016-07-08T22:25:04Z | [
"python",
"dictionary"
] |
How to sort a dict by one of its values in Python? | 38,276,152 | <p>I have a dict like this:
key is a string,
value is a list of strings</p>
<pre><code> my_dict = {
'key1': [value11, value12, value13],
'key2': [value21, value22, value23],
'key3': [value31, value32, value33],
'key4': [value41, value42, value43]
}
</code></pre>
<p>e.g.</p>
<pre><code>dict_0 = {
'... | 0 | 2016-07-08T22:19:27Z | 39,987,855 | <p>You could use:</p>
<pre><code>sorted(d.items(), key=lambda x: x[1])
</code></pre>
<p>This will sort the dictionary by the values of each entry within the dictionary from smallest to largest.</p>
| 1 | 2016-10-11T22:37:56Z | [
"python",
"dictionary"
] |
Python Ctypes register callback functions | 38,276,180 | <p>I ran into something very strange using Python and ctypes. I'm using Python 3.4.3. First, some background into the project:</p>
<p>I have compiled a custom dll from C code. I'm using ctypes to interface with the dll. The C library is interfacing with some custom hardware. Sometimes the hardware generates an interru... | 0 | 2016-07-08T22:22:55Z | 38,276,608 | <p>Your <code>cb_ptr</code> is being garbage collected. From the <a href="https://docs.python.org/2/library/ctypes.html#callback-functions" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>Make sure you keep references to CFUNCTYPE() objects as long as they
are used from C code. ctypes doesnât, and if you d... | 2 | 2016-07-08T23:13:01Z | [
"python",
"callback",
"ctypes"
] |
Python Pandas - How to limit row amount and automatically start new column | 38,276,186 | <p>Go easy! I am a Python student! :)</p>
<p>I have a python program that simulates coin flips. The end result is that each coin flip is placed into a CSV as either -1 (tails) or 1 (heads). I need Pandas to limit the amount of rows per column to 1 million and to automatically continue to the next column after each 1 m... | 0 | 2016-07-08T22:23:42Z | 38,276,408 | <p>I think this will work for you:</p>
<pre><code>#create the data
samples = np.random.choice([-1, 1], size = flipcount)
# calculate the numbers of columns
n_columns = flipcount//10**6
if flipcount % 10**6 !=0:
n_columns+=1
# create the DataFrame
mybreak = 1e6
mylist = [samples[(i-1)*mybreak:i*mybreak] for i in ... | 1 | 2016-07-08T22:48:38Z | [
"python",
"csv",
"numpy",
"pandas"
] |
Python Pandas - How to limit row amount and automatically start new column | 38,276,186 | <p>Go easy! I am a Python student! :)</p>
<p>I have a python program that simulates coin flips. The end result is that each coin flip is placed into a CSV as either -1 (tails) or 1 (heads). I need Pandas to limit the amount of rows per column to 1 million and to automatically continue to the next column after each 1 m... | 0 | 2016-07-08T22:23:42Z | 38,701,207 | <p>I think an approach like the following is easiest</p>
<pre><code>flipcount = 2000001
my_break = 1000000
samples = np.random.choice([1, -1], size=flipcount)
if flipcount > my_break:
n_empty = my_break - flipcount % my_break
samples = np.append(samples, [np.nan] * n_empty).reshape((-1, my_break)).T
(pd.... | 1 | 2016-08-01T14:18:10Z | [
"python",
"csv",
"numpy",
"pandas"
] |
Python SQLite avoid overcrowding by deleting the last item | 38,276,220 | <p>I use sqlite with python, when insert a new row I want to delete one of the end</p>
<pre><code>conn.execute("INSERT INTO ORDERS (ORD_ID, TYPE) VALUES (?, ?)", [ord_id, type_n]);
conn.commit()
</code></pre>
<blockquote>
<p>ID ID_ORD TYPE</p>
<hr>
<p>3 136984714 0 <strong><--(-1)</strong><... | 0 | 2016-07-08T22:27:19Z | 38,276,275 | <p>If your <code>ord_id</code> is always guaranteed to auto-increment you could do:</p>
<pre><code>import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('create table orders (ord_id, type);')
conn.execute('insert into orders (ord_id, type) values (?,?);',(3,136984714))
conn.execute('insert into orders (ord_i... | 1 | 2016-07-08T22:33:11Z | [
"python",
"sqlite"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.