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 can I stop my program from generating the same key? | 38,639,395 | <p>I writing a password generator and I ran into this annoying issue, and it is the repeating a a number or letter on the same line. The user gives the program a format on how they want their password to be generated ex "C@@d%%%"
where @ is only letters and where % is only numbers, and the user also inputs the numbers ... | 1 | 2016-07-28T14:32:19Z | 38,639,695 | <p>Create a list of all chars and a list with all nums, then just pick one by using list.pop(randint(0, len(list) - 1), you will always pick a different letter / number like this but you will also be limited to 10 digits (0-9) and 20-something letters.</p>
| 0 | 2016-07-28T14:44:03Z | [
"python",
"passwords",
"generator"
] |
Understanding results of CRC8 SAE J1850 (normal) vs. "Zero" | 38,639,423 | <p>I need a verification of CRC8-SAE-J1850 messages and therefore wrote a script, that reads logs and needs to calculate CRC8 (non ZERO) from there to match them with the CRC8 values in the log and then check which step in the tool chain caused the hassle.</p>
<p>Anyway, I spent some time looking into documentation, S... | 2 | 2016-07-28T14:33:50Z | 38,649,324 | <p>That CRC is normally defined with these parameters:</p>
<pre><code>width=8 poly=0x1d init=0xff refin=false refout=false xorout=0xff check=0x4b name="CRC-8/SAE-J1850"
</code></pre>
<p><a href="http://github.com/madler/crcany/" rel="nofollow">crcgen</a> will take that and produce C code to compute the CRC. You can e... | 0 | 2016-07-29T01:53:50Z | [
"python",
"binary",
"xor",
"crc"
] |
Understanding results of CRC8 SAE J1850 (normal) vs. "Zero" | 38,639,423 | <p>I need a verification of CRC8-SAE-J1850 messages and therefore wrote a script, that reads logs and needs to calculate CRC8 (non ZERO) from there to match them with the CRC8 values in the log and then check which step in the tool chain caused the hassle.</p>
<p>Anyway, I spent some time looking into documentation, S... | 2 | 2016-07-28T14:33:50Z | 38,889,829 | <p>I solved it. </p>
<p>It is never mentioned that for the SAE J1850 the input is XORed with 0xFF. Even though the C-code Mark Adler provided states precisely that in <code>crc ^= 0xff;</code> however it didn't help me understand what my problem was. </p>
<p>It was not a bug, my code worked correctly but it was the p... | 0 | 2016-08-11T07:22:09Z | [
"python",
"binary",
"xor",
"crc"
] |
What am I doing wrong here? IF and Else statement | 38,639,517 | <p>My goal here is to read through a bunch of rows which are now in records. If the second column of any record (row[1]) is equal to 133 in this example it prints out the first and second column.</p>
<p>I am running into this issue though:</p>
<p>line 11 - else: issue</p>
<pre><code>import sqlite3
conn = sqlite3.co... | -1 | 2016-07-28T14:37:12Z | 38,640,217 | <p>I've managed to fix it with some help from you guys. thank you!</p>
<pre><code>import sqlite3
conn = sqlite3.connect('db.sqlite')
print "Opened database successfully";
cur = conn.execute("SELECT * FROM sightings WHERE column = 133")
row = cur.fetchone()
while row is not None:
print row[0], row[1], row[2... | -1 | 2016-07-28T15:07:24Z | [
"python",
"sql",
"sqlite3"
] |
What am I doing wrong here? IF and Else statement | 38,639,517 | <p>My goal here is to read through a bunch of rows which are now in records. If the second column of any record (row[1]) is equal to 133 in this example it prints out the first and second column.</p>
<p>I am running into this issue though:</p>
<p>line 11 - else: issue</p>
<pre><code>import sqlite3
conn = sqlite3.co... | -1 | 2016-07-28T14:37:12Z | 38,640,482 | <p>You have an extra colon at the end of a statement that you do not need</p>
<pre><code>if row[1] == 133:
print row[0], row[1]
else:
row = cur.fetchone(): <----
</code></pre>
<p>Should be..</p>
<pre><code>if row[1] == 133:
print row[0], row[1]
else:
row = cur.fetchone()
</code></pre>
| 1 | 2016-07-28T15:18:34Z | [
"python",
"sql",
"sqlite3"
] |
Comparing user input to a randomly selected list item - Python | 38,639,528 | <p>I am creating a Rock, Paper, Scissors game for a class. as part of the game I need to have a weapon menu display to the screen for the user to select from. Then the computer will randomly select a weapon from a list. The problem I am facing (I believe) is that the list items range from [0,2] where my menu items list... | 0 | 2016-07-28T14:37:49Z | 38,639,750 | <p>In the if statements, it seems like you are comparing the variable <code>computer</code>, which is a string, to an integer. You assign <code>computer = WEAPON[randint(0,2)]</code>, so computer is one of the following: <code>["Rock", "Paper", "Scissors"]</code>. However, in your if statements, you are saying: <code>i... | 1 | 2016-07-28T14:46:25Z | [
"python"
] |
Comparing user input to a randomly selected list item - Python | 38,639,528 | <p>I am creating a Rock, Paper, Scissors game for a class. as part of the game I need to have a weapon menu display to the screen for the user to select from. Then the computer will randomly select a weapon from a list. The problem I am facing (I believe) is that the list items range from [0,2] where my menu items list... | 0 | 2016-07-28T14:37:49Z | 38,639,821 | <p>You need to be careful with the contents of your variables:</p>
<pre><code># this is storing a string
computer = WEAPON[randint(0,2)]
# this expects an integer
elif player == 1:
# computer == paper
if computer == 1:
</code></pre>
<p>That would be the root of some of the problems that you are ... | 3 | 2016-07-28T14:49:23Z | [
"python"
] |
Comparing user input to a randomly selected list item - Python | 38,639,528 | <p>I am creating a Rock, Paper, Scissors game for a class. as part of the game I need to have a weapon menu display to the screen for the user to select from. Then the computer will randomly select a weapon from a list. The problem I am facing (I believe) is that the list items range from [0,2] where my menu items list... | 0 | 2016-07-28T14:37:49Z | 38,639,859 | <p>Compare to the strings, not to the numbers, like this</p>
<pre><code> if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 'Rock':
# computer == paper
if computer == 'P... | 1 | 2016-07-28T14:51:22Z | [
"python"
] |
Comparing user input to a randomly selected list item - Python | 38,639,528 | <p>I am creating a Rock, Paper, Scissors game for a class. as part of the game I need to have a weapon menu display to the screen for the user to select from. Then the computer will randomly select a weapon from a list. The problem I am facing (I believe) is that the list items range from [0,2] where my menu items list... | 0 | 2016-07-28T14:37:49Z | 38,640,037 | <p>I have condensed a majority of your code by implementing a small dict_map. It could be condensed further but why bother.</p>
<pre><code># random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
MAPP = {"Rock":{"Win":'Scissors', "Loss":"Paper", "Adj":"Smashes"},
"P... | 0 | 2016-07-28T14:59:29Z | [
"python"
] |
How to stop tab from selecting text on Tkinter EntryBox | 38,639,573 | <p>I'm using this code avaliable on <a href="http://tkinter.unpythonic.net/wiki/AutocompleteEntry" rel="nofollow">AutocompleteEntry</a>, to create a subclass for the Entry widget that ships with Tkinter.</p>
<p>At line 57, the handle_keyrelease() function seems to handle how te AutocompleteEntry reacts to certain keyp... | 0 | 2016-07-28T14:39:52Z | 38,647,445 | <p>For further reference, based on <a href="http://stackoverflow.com/questions/4090683/overriding-default-tab-behaviour-in-python-tkinter">this question</a>, I managed to get it working by simply adding a <code>bind</code> to tab calling a function that <code>return</code>s <code>break</code>, like so:</p>
<pre><code>... | 0 | 2016-07-28T22:00:26Z | [
"python",
"python-3.x",
"tkinter",
"tk"
] |
Python: np.where with multiple condition | 38,639,577 | <p>I have df and I try create new column, where numbers from one column is some phrase.
I use </p>
<pre><code>df["Family"] = np.where(df["Qfamilystatus"] == 1, "Ðе замÑжем / Ðе женаÑ", "ÐамÑжем / Ð¶ÐµÐ½Ð°Ñ / Ð¶Ð¸Ð²Ñ Ð² гÑажданÑком бÑаке", "Разведен/ живем поÑоÐ... | 4 | 2016-07-28T14:40:02Z | 38,639,612 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> function by <code>dictionary</code>.</p>
<p>Sample:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Qfamilystatus':[1,2,3,4]})
print (df)
Qfamilystatus
0 ... | 3 | 2016-07-28T14:41:18Z | [
"python",
"numpy",
"pandas"
] |
How to include VCS information in setuptools packages | 38,639,603 | <p>I'm (trying) to use setuptools to build a package. I was trying to use a version number <code>major.minor.mercurial_revision</code> but it complains that:</p>
<pre><code>The version specified ('1.0.7ae7970a82c1') is an invalid version, this may
not work as expected with newer versions of setuptools, pip, and PyPI.
... | 1 | 2016-07-28T14:40:58Z | 38,639,916 | <p>What about just including it as an attribute in your Python code?</p>
<pre><code>echo '__revision__ = $HG_HASH' > mypackage/revision.py
</code></pre>
<p>Once installed, you can:</p>
<pre><code>from mypackage.revision import __revision__
print 'build from', __revision__
</code></pre>
<p>Or you could write it t... | 0 | 2016-07-28T14:53:59Z | [
"python",
"setuptools"
] |
How to include VCS information in setuptools packages | 38,639,603 | <p>I'm (trying) to use setuptools to build a package. I was trying to use a version number <code>major.minor.mercurial_revision</code> but it complains that:</p>
<pre><code>The version specified ('1.0.7ae7970a82c1') is an invalid version, this may
not work as expected with newer versions of setuptools, pip, and PyPI.
... | 1 | 2016-07-28T14:40:58Z | 38,639,931 | <p>You can use a <a href="https://www.python.org/dev/peps/pep-0440/#local-version-identifiers" rel="nofollow">local version identifier</a> to accomplish this.</p>
<blockquote>
<p>Local version identifiers MUST comply with the following scheme:</p>
<p><code><public version identifier>[+<local version la... | 0 | 2016-07-28T14:54:57Z | [
"python",
"setuptools"
] |
ImportError: No module named _markerlib when trying to install via pip | 38,639,630 | <p>Did somebody experienced the same problem? I tried to run a solution from SO:</p>
<pre><code>pip install --upgrade distribute
</code></pre>
<p>and </p>
<pre><code>pip install --upgrade setuptools
</code></pre>
<p>And I got the same result, every time:</p>
<pre><code>Traceback (most recent call last):
File... | 0 | 2016-07-28T14:41:53Z | 38,879,182 | <p>I fixed it this way, I think.</p>
<pre><code>pip uninstall setuptools
download https://bitbucket.org/pypa/setuptools/raw/0.7.3/ez_setup.py
</code></pre>
<p>Run that,then</p>
<pre><code>pip install %HOME%\Downloads\wheel-0.25.0.tar.gz
pip install Distribute
</code></pre>
<p>I did this so this would work</p>
<p... | 0 | 2016-08-10T16:43:43Z | [
"python",
"django",
"heroku",
"pip"
] |
Convert a gps coordinate to an lat lng format? | 38,639,633 | <p>This <a href="https://stackoverflow.com/questions/24427828/calculate-point-based-on-distance-and-direction">SO question</a> has returned a coordinate like this: <code>48 52m 0.0s N, 2 21m 0.0s E</code>.</p>
<p>But I want it something like <code>37.783333, -122.416667</code>.</p>
<p>ie:</p>
<pre><code>import geopy... | 0 | 2016-07-28T14:41:57Z | 38,640,236 | <p>I am sorry for not being able to provide you with the correct terminology :[ However, here is a possible solution for the code:</p>
<pre><code>x = d.destination(point=start, bearing=0)
print(x.latitude, x.longitude)
</code></pre>
| 0 | 2016-07-28T15:08:04Z | [
"python",
"python-2.7",
"gps",
"coordinates",
"geopy"
] |
Built-in all() function not returning True on a list of negative numbers | 38,639,693 | <p>Why? Shouldn't this be True?</p>
<pre><code>>>> sub = [-1,-2,-3,-4,-5,-6]
>>> print all(sub) < 0
False
>>>
</code></pre>
| 1 | 2016-07-28T14:43:49Z | 38,639,748 | <p><a href="https://docs.python.org/2/library/functions.html#all" rel="nofollow"><code>all(sub)</code></a> returns <code>True</code> because all the elements of <code>sub</code> are nonzero.<br>
<code>True</code> is not less than zero.<br>
Therefore <code>all(sub) < 0</code> is false.</p>
<p>If you want to test if ... | 6 | 2016-07-28T14:46:20Z | [
"python",
"builtin"
] |
Built-in all() function not returning True on a list of negative numbers | 38,639,693 | <p>Why? Shouldn't this be True?</p>
<pre><code>>>> sub = [-1,-2,-3,-4,-5,-6]
>>> print all(sub) < 0
False
>>>
</code></pre>
| 1 | 2016-07-28T14:43:49Z | 38,639,784 | <p>@khelwood's answer is correct. However, you could also use numpy for what you want.</p>
<pre><code>sub = np.asarray(sub)
np.all(sub<0)
</code></pre>
| 2 | 2016-07-28T14:47:54Z | [
"python",
"builtin"
] |
Read XML characters as strings into ElementTree | 38,639,703 | <p>I'm using ElementTree to compare a CSV file to an XML document. The script should update the tags if the tag matches the first cell in the CSV. The tag needs to have a non-breaking space to prevent the text from wrapping when I import the XML into a different program (InDesign).</p>
<p>XML Input:</p>
<pre><code>... | 0 | 2016-07-28T14:44:28Z | 38,641,396 | <p>Here is what happens.</p>
<p>You read this XML into ElementTree:</p>
<pre><code><Table_title>fatal crashes by&#160;time of day</Table_title>
</code></pre>
<p>ElementTree parses it and turns it into this DOM:</p>
<ul>
<li>element node, name <code>Table_title</code>
<ul>
<li>text node, string valu... | 1 | 2016-07-28T15:59:57Z | [
"python",
"xml",
"csv",
"elementtree"
] |
Tensorflow image segmentation via linear regression | 38,639,713 | <p>Previously I built a network that implemented a binary image segmentation -- foreground & background. I did this by having two classifications. Now instead of a binary classification, I want to do a linear regression of each pixel. </p>
<p>Say there is a 3D surface within the image view, I want to segment the e... | 0 | 2016-07-28T14:44:55Z | 38,641,661 | <p>As said in the comments, a good weight initialization is key to the success of a model:</p>
<ul>
<li>too high: the model will not learn and may produce NaN values</li>
<li>too low: the model will learn very very slowly, because the gradient will be too small (see vanishing gradients)</li>
</ul>
<p>There are good i... | 2 | 2016-07-28T16:13:13Z | [
"python",
"machine-learning",
"neural-network",
"artificial-intelligence",
"tensorflow"
] |
I can't find elements by Id inside html source page Selenium | 38,639,803 | <p>I am trying to get a list at the <a href="http://www.bmfbovespa.com.br/pt_br/produtos/listados-a-vista-e-derivativos/renda-variavel/empresas-listadas.htm" rel="nofollow">website</a>, clicking on a button ('Todas'). The <code>Todas</code> button Id <strong>at the browser html source</strong> and my python code are:</... | 0 | 2016-07-28T14:49:01Z | 38,639,933 | <p>As I'm seeing in your provided <a href="http://www.bmfbovespa.com.br/pt_br/produtos/listados-a-vista-e-derivativos/renda-variavel/empresas-listadas.htm" rel="nofollow">website</a> this <code>TODAS</code> button is inside an <code>iframe</code> with id <code>bvmf_iframe</code>, You need to switch that frame before fi... | 0 | 2016-07-28T14:55:04Z | [
"python",
"selenium",
"web-scraping"
] |
I can't find elements by Id inside html source page Selenium | 38,639,803 | <p>I am trying to get a list at the <a href="http://www.bmfbovespa.com.br/pt_br/produtos/listados-a-vista-e-derivativos/renda-variavel/empresas-listadas.htm" rel="nofollow">website</a>, clicking on a button ('Todas'). The <code>Todas</code> button Id <strong>at the browser html source</strong> and my python code are:</... | 0 | 2016-07-28T14:49:01Z | 38,640,000 | <p>Reason is because this page is using an iFrame, you will need to swicth to the iframe before attempting to find your element:</p>
<pre><code>iframe = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to_default_content()
driver.switch_to_frame(iframe)
driver.find_element_by_id("ctl00_contentPlaceHolderCo... | 0 | 2016-07-28T14:58:07Z | [
"python",
"selenium",
"web-scraping"
] |
install 'pip' package for specific version of Python on Windows | 38,639,942 | <p>I have on my machine (windows 10) two versions of python: 3.5 2.7<br>
I need to install a package using <strong><em>pip</em></strong> but I want the package on both. </p>
<p>My default version is 3.5. </p>
<p>I try to do this: <code>pip2 install scikit-learn</code> to install it on python 2.7 and I get this er... | 0 | 2016-07-28T14:55:21Z | 38,640,145 | <p>The safest and least frustrating way to go about this is to load independent copies of scikit learn into two virtual environments.</p>
<p>Install by:</p>
<pre><code>$ pip install virtualenv
$ pip install virtualenvwrapper
</code></pre>
<p>Then</p>
<pre><code>$ mkvirtualenv --python=<path to python> <na... | 1 | 2016-07-28T15:03:51Z | [
"python",
"python-2.7",
"module"
] |
install 'pip' package for specific version of Python on Windows | 38,639,942 | <p>I have on my machine (windows 10) two versions of python: 3.5 2.7<br>
I need to install a package using <strong><em>pip</em></strong> but I want the package on both. </p>
<p>My default version is 3.5. </p>
<p>I try to do this: <code>pip2 install scikit-learn</code> to install it on python 2.7 and I get this er... | 0 | 2016-07-28T14:55:21Z | 38,640,630 | <p>On Windows you can use</p>
<p>for python2.x <code>py -2</code>
for python3.x <code>py -3</code></p>
<p>so it would be </p>
<pre><code>py -2 -m pip install scikit-learn
py -3 -m pip install scikit-learn
</code></pre>
<p>just try <code>py --help</code> for more info</p>
| 0 | 2016-07-28T15:25:00Z | [
"python",
"python-2.7",
"module"
] |
install 'pip' package for specific version of Python on Windows | 38,639,942 | <p>I have on my machine (windows 10) two versions of python: 3.5 2.7<br>
I need to install a package using <strong><em>pip</em></strong> but I want the package on both. </p>
<p>My default version is 3.5. </p>
<p>I try to do this: <code>pip2 install scikit-learn</code> to install it on python 2.7 and I get this er... | 0 | 2016-07-28T14:55:21Z | 38,642,770 | <p>Thanks allot for the answers,
after some try&fail I find 2 different ways to figure it.<br>
<strong>1.</strong> <code><PATH-FOR-PYTHON>\scripts\pip.exe install <package name></code> </p>
<p><strong>2.</strong> <code>
py -2 -E-m pip install scikit-learn for v3.5
py -3... | 0 | 2016-07-28T17:12:13Z | [
"python",
"python-2.7",
"module"
] |
SQLAlchemy get attribute name from table and column name | 38,639,948 | <p>Is there any way in SQLAlchemy by reflection or any other means to get the name that a column has in the corresponding model? For example i have the person table with a column group_id. In my Person class this attribute is refered to as 'group' is there a way to dynamically and generically getting this without impor... | 0 | 2016-07-28T14:55:40Z | 38,652,751 | <p>Unfortunately it is most likely not possible...</p>
| 0 | 2016-07-29T07:18:33Z | [
"python",
"sqlalchemy"
] |
Matching letters with specific intervals in Python 2.7 | 38,640,045 | <p>I was wondering if there was a simple method in Python2.7 to have a string of letters (such as MVMGLGVLLLVFVLGLGLTPPTLAQDNSRYTHFLTQHYDAKPQGRDDRYCESIMRRRGLT) and to determine if in it there ocurred certain letters with x strings between (i.e. an "M" and a "V" with 3 other letters (any other letters) between them. Thi... | -2 | 2016-07-28T14:59:43Z | 38,640,289 | <p>As the comment says, regex is your friend.
Here's a sample to find any blocks or M then any three letters then V</p>
<p><code>M[A-Z]{3}V</code> looks for <code>'M'</code> then any of 'A' up to 'Z' (<code>[A-Z]</code>) three times (<code>{3}</code>) followed by <code>'V</code>' so this will find the specific thing y... | 3 | 2016-07-28T15:10:15Z | [
"python",
"python-2.7"
] |
How do you install a package binary into a virtual environment | 38,640,283 | <p>So you can install packages in the form of binaries such as <a href="https://sourceforge.net/projects/pywin32/files/pywin32/Build%20217/" rel="nofollow">these</a>. But if you just double click it would presumably install it in the global environment. If you wanted to install it a virtualenv, how would you do it?</p>... | 0 | 2016-07-28T15:09:52Z | 38,640,410 | <p>Normally you would use <a href="https://pip.pypa.io/en/stable/" rel="nofollow">pip</a> in a virtualenv - most packages can be installed that way and <a href="https://pypi.python.org/pypi/pypiwin32/219" rel="nofollow">pypiwin32</a> seems to be an alias for pip-installable pywin32 so with pip you would install this.</... | 0 | 2016-07-28T15:15:46Z | [
"python",
"windows",
"virtualenv"
] |
How do I convert dictionary list values to integers? | 38,640,365 | <p>I'm working in Python 3.5. I've uploaded a CSV file and made it into a dictionary. However, the list of multiple values for each key is a string and not an integer. How can I convert the values for each key into an integer?</p>
<p>Furthermore, is there a way for future CSV importation to automatically make dictiona... | 0 | 2016-07-28T15:13:35Z | 38,640,408 | <p>if row is the list containing the integers under string format :</p>
<pre><code>dictname[key] = [int(elt) for elt in row[1:] if elt.isdigit()]
</code></pre>
<p>should do the trick</p>
| 0 | 2016-07-28T15:15:37Z | [
"python",
"string",
"dictionary",
"integer",
"python-3.5"
] |
How do I convert dictionary list values to integers? | 38,640,365 | <p>I'm working in Python 3.5. I've uploaded a CSV file and made it into a dictionary. However, the list of multiple values for each key is a string and not an integer. How can I convert the values for each key into an integer?</p>
<p>Furthermore, is there a way for future CSV importation to automatically make dictiona... | 0 | 2016-07-28T15:13:35Z | 38,640,435 | <p>You can use <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> and specify converter functions. In fact you may not even need to do that as it is intelligently parsing CSV files.</p>
<pre><code>import pandas as pd
df = pd.read_csv('filename.csv')
</code></pre>
<p>If you need converter functions:</p>
<... | 0 | 2016-07-28T15:16:44Z | [
"python",
"string",
"dictionary",
"integer",
"python-3.5"
] |
How do I convert dictionary list values to integers? | 38,640,365 | <p>I'm working in Python 3.5. I've uploaded a CSV file and made it into a dictionary. However, the list of multiple values for each key is a string and not an integer. How can I convert the values for each key into an integer?</p>
<p>Furthermore, is there a way for future CSV importation to automatically make dictiona... | 0 | 2016-07-28T15:13:35Z | 38,640,913 | <p>I used a function to first check if the value is a string/unicode. If so, it then tries to convert it to a float, e.g. "1,234.45" -> 1234.45. If this fails or the value is not a string/float, the function returns it unchanged.</p>
<p>This function is then used in a list comprehension to population the dictionary.<... | 0 | 2016-07-28T15:37:19Z | [
"python",
"string",
"dictionary",
"integer",
"python-3.5"
] |
Pyopengl tessellating polygons | 38,640,395 | <p>I have polygons in the form:</p>
<p>[(1,2), (2,4), (3,4), (5,6)]</p>
<p>I need tessellation to draw them, but glutess is too complicated. Opengl cannot handle convex polygons.</p>
<p>I think I need something like:</p>
<p><a href="http://www.math.uiuc.edu/~gfrancis/illimath/windows/aszgard_mini/pylibs/OpenGLConte... | 0 | 2016-07-28T15:15:03Z | 38,810,954 | <p>I am actually working on the same thing for rendering vector graphics in python! While putting this sample code together, I found <a href="http://www.songho.ca/opengl/gl_tessellation.html" rel="nofollow">this resource</a> useful for understanding the gluTesselator (although that link does not use python). Below is t... | 0 | 2016-08-07T04:47:27Z | [
"python",
"pyopengl"
] |
django: create user profile for existing users automatically | 38,640,446 | <p>I added a new UserProfile Model to my project today.</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
...
def __unicode__(self):
return u'Profile of user: %s' % (self.user.username)
class Meta:
managed = True
def create_user_profile(sender, instanc... | 0 | 2016-07-28T15:17:00Z | 38,640,853 | <p>In response to your code I'll say to put a get_or_create also in a post_init listener for User.</p>
<p>If this "all fields null is ok" profile is just a fast example I'd put a middleware redirecting all users with no profile to the settings page asking them to fill additional data. ( probably you want to do this a... | -1 | 2016-07-28T15:34:52Z | [
"python",
"django",
"django-1.7"
] |
django: create user profile for existing users automatically | 38,640,446 | <p>I added a new UserProfile Model to my project today.</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
...
def __unicode__(self):
return u'Profile of user: %s' % (self.user.username)
class Meta:
managed = True
def create_user_profile(sender, instanc... | 0 | 2016-07-28T15:17:00Z | 38,640,910 | <p>For existing users, it checks whether such an instance already exists, and creates one if it doesn't.</p>
<pre><code>def post_save_create_or_update_profile(sender,**kwargs):
from user_profiles.utils import create_profile_for_new_user
if sender==User and kwargs['instance'].is_authenticate():
profile=... | 0 | 2016-07-28T15:37:15Z | [
"python",
"django",
"django-1.7"
] |
django: create user profile for existing users automatically | 38,640,446 | <p>I added a new UserProfile Model to my project today.</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
...
def __unicode__(self):
return u'Profile of user: %s' % (self.user.username)
class Meta:
managed = True
def create_user_profile(sender, instanc... | 0 | 2016-07-28T15:17:00Z | 38,640,970 | <p>You can loop through the existing users, and call <code>get_or_create()</code>:</p>
<pre><code>for user in User.objects.all():
UserProfile.objects.get_or_create(user=user)
</code></pre>
<p>You could put this in a <a href="https://docs.djangoproject.com/en/1.9/topics/migrations/#data-migrations" rel="nofollow">... | 2 | 2016-07-28T15:39:57Z | [
"python",
"django",
"django-1.7"
] |
Getting twitter user id from tweet id without json object | 38,640,619 | <p>Currently I am working on twitter data. I need to fetch twitter data with the <em>tweet id</em> and <em>user id</em> of the tweet. Unfortunately, I am able to fetch the tweet with <em>tweet id</em> only. But along with that I want to get the <em>user id</em> too. I am fetching the tweets by giving the query of the s... | 0 | 2016-07-28T15:20:51Z | 38,673,072 | <p>Yes, it is very simple.</p>
<p>You look up the Tweet using <a href="https://dev.twitter.com/rest/reference/get/statuses/show/%3Aid" rel="nofollow"><code>statuses/show</code></a>. That will return the Tweet object as JSON.</p>
<p>Inside that JSON you will find the user object.</p>
<p>Here is a shortened example:<... | 0 | 2016-07-30T10:52:34Z | [
"python",
"twitter"
] |
Initialize a Pandas DataFrame with a fill value other than NaN | 38,640,664 | <p>Suppose I initialize an 'empty' DataFrame as follows:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(index=list('AB'), columns=list('CD'))
</code></pre>
<p>The resulting <code>df</code> has the form</p>
<pre><code> C D
A NaN NaN
B NaN NaN
</code></pre>
<p>Is there a pythonic w... | 2 | 2016-07-28T15:26:24Z | 38,640,700 | <p>pass scalar value as <code>data</code> param, this will set all elements to the same value:</p>
<pre><code>In [181]:
df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=-np.inf)
df
Out[181]:
C D
A -inf -inf
B -inf -inf
</code></pre>
<p>The <a href="http://pandas.pydata.org/pandas-docs/stable/gene... | 3 | 2016-07-28T15:28:15Z | [
"python",
"pandas"
] |
Convert List to Rows | 38,640,719 | <p>What is an efficient way to convert a list into separate elements in python?</p>
<p>I have a dataset that looks like this;</p>
<pre><code>['StudentA','80','94','93']
['StudentB','93','94']
</code></pre>
<p>I would like to reshape the data so that each student/score has its own row;</p>
<pre><code>['StudentA','80... | 2 | 2016-07-28T15:28:57Z | 38,640,812 | <pre><code> c=['StudentA','80','94','93']
d=[[c[0], p] for p in c[1:]]
</code></pre>
| 1 | 2016-07-28T15:32:29Z | [
"python",
"list"
] |
Convert List to Rows | 38,640,719 | <p>What is an efficient way to convert a list into separate elements in python?</p>
<p>I have a dataset that looks like this;</p>
<pre><code>['StudentA','80','94','93']
['StudentB','93','94']
</code></pre>
<p>I would like to reshape the data so that each student/score has its own row;</p>
<pre><code>['StudentA','80... | 2 | 2016-07-28T15:28:57Z | 38,640,817 | <p>You could use a list comprehension, like this:</p>
<pre><code>data = ['StudentA','80','94','93']
res = [[data[0], x] for x in data[1:]]
</code></pre>
<p>This sets <code>res</code> to <code>[['StudentA', '80'], ['StudentA', '94'], ['StudentA', '93']]</code>.</p>
| 3 | 2016-07-28T15:32:40Z | [
"python",
"list"
] |
Convert List to Rows | 38,640,719 | <p>What is an efficient way to convert a list into separate elements in python?</p>
<p>I have a dataset that looks like this;</p>
<pre><code>['StudentA','80','94','93']
['StudentB','93','94']
</code></pre>
<p>I would like to reshape the data so that each student/score has its own row;</p>
<pre><code>['StudentA','80... | 2 | 2016-07-28T15:28:57Z | 38,640,838 | <p>If it were a list (<code>all_students</code>) containing each of these lines, you could do what you want, by doing :</p>
<pre><code>result = []
for student in all_students:
student_name = student[0]
result.extend([[student_name, value] for value in student[1:]]
print(result)
</code></pre>
| 0 | 2016-07-28T15:33:54Z | [
"python",
"list"
] |
Convert List to Rows | 38,640,719 | <p>What is an efficient way to convert a list into separate elements in python?</p>
<p>I have a dataset that looks like this;</p>
<pre><code>['StudentA','80','94','93']
['StudentB','93','94']
</code></pre>
<p>I would like to reshape the data so that each student/score has its own row;</p>
<pre><code>['StudentA','80... | 2 | 2016-07-28T15:28:57Z | 38,640,916 | <p>Couple <strong>student</strong> with it's respective <strong>data</strong> using a <code>dictionary</code>.</p>
<pre><code>def to_dict(l):
d = {}
for i in l:
key = i[0]
value = i[1:]
d[key] = value
return d
</code></pre>
<p><strong>Sample output:</strong></p>
<pre><code>l =... | 1 | 2016-07-28T15:37:27Z | [
"python",
"list"
] |
Convert List to Rows | 38,640,719 | <p>What is an efficient way to convert a list into separate elements in python?</p>
<p>I have a dataset that looks like this;</p>
<pre><code>['StudentA','80','94','93']
['StudentB','93','94']
</code></pre>
<p>I would like to reshape the data so that each student/score has its own row;</p>
<pre><code>['StudentA','80... | 2 | 2016-07-28T15:28:57Z | 38,641,333 | <p>This dict comprehension will group you data by student name:</p>
<pre><code>d = {x[0]: x[1:] for x in dataset}
</code></pre>
<p>i.e.:</p>
<pre><code>>>> d
{'StudentA': ['80', '94', '93'], 'StudentB': ['93', '94']}
</code></pre>
<p>from which you can extract individual pairs with a nested for loop or lis... | 0 | 2016-07-28T15:56:53Z | [
"python",
"list"
] |
list all class names in a package in python | 38,640,742 | <p>I have a package structure like this:</p>
<pre><code>A/__init__.py
|
--B/__init__.py
|
--C/__init__.py
</code></pre>
<p>In each package and sub packages, it contains a few classes, e.g. <code>A/__init__.py</code> contains class A1 and A2, <code>B/__init__.py</code> contains class B1 and B2, <code>C/__init__.py</... | 0 | 2016-07-28T15:29:52Z | 38,640,965 | <pre><code>print(os.path.dirname(os.path.abspath(A.__file__)))
</code></pre>
<p>Or did you have something different in mind?</p>
<p><strong>Update</strong>:</p>
<blockquote>
<p>if package A has not been imported, how can I refer it using <code>A.__file__</code>?</p>
</blockquote>
<p>Arguably, there's no <em>easy<... | 2 | 2016-07-28T15:39:46Z | [
"python"
] |
list all class names in a package in python | 38,640,742 | <p>I have a package structure like this:</p>
<pre><code>A/__init__.py
|
--B/__init__.py
|
--C/__init__.py
</code></pre>
<p>In each package and sub packages, it contains a few classes, e.g. <code>A/__init__.py</code> contains class A1 and A2, <code>B/__init__.py</code> contains class B1 and B2, <code>C/__init__.py</... | 0 | 2016-07-28T15:29:52Z | 38,676,122 | <p>I will try to dig some code out, but in general : </p>
<ol>
<li>Walk through the package folders and files using 'os.walk'</li>
<li>For every Python file you find use importlib to import it. </li>
<li>For every imported module use the functions in the 'inspect' standard library module to identify the classes within... | 0 | 2016-07-30T16:32:45Z | [
"python"
] |
Remove spaces between numbers in a string in python | 38,640,791 | <p>I want to remove all the whitespace between the numbers in a string in python. For example, if I have</p>
<pre><code>my_string = "my phone number is 12 345 6789"
</code></pre>
<p>I want it to become</p>
<pre><code>my_string = "my phone number is 123456789"
</code></pre>
<p>I thought I could do this for every num... | 0 | 2016-07-28T15:31:40Z | 38,640,850 | <p>Just use regex! Now with support for variable number of spaces.</p>
<pre><code>import re
my_string = "my phone number is 12 345 6789"
my_string = re.sub(r'(\d)\s+(\d)', r'\1\2', my_string)
</code></pre>
| 9 | 2016-07-28T15:34:47Z | [
"python",
"string"
] |
Remove spaces between numbers in a string in python | 38,640,791 | <p>I want to remove all the whitespace between the numbers in a string in python. For example, if I have</p>
<pre><code>my_string = "my phone number is 12 345 6789"
</code></pre>
<p>I want it to become</p>
<pre><code>my_string = "my phone number is 123456789"
</code></pre>
<p>I thought I could do this for every num... | 0 | 2016-07-28T15:31:40Z | 38,641,031 | <p>Just another regex way, using look-behind/ahead and directly just remove the space instead of also taking out the digits and putting them back in:</p>
<pre><code>>>> re.sub('(?<=\d) (?=\d)', '', my_string)
'my phone number is 123456789'
</code></pre>
<p>I like it, but have to admit it's a bit longer an... | 1 | 2016-07-28T15:43:28Z | [
"python",
"string"
] |
Python running out of memory | 38,640,815 | <p>I have the following program. While I run it, I received <code>Memory Error</code>, specifically in <code>Fpred = F.predict(A)</code> (please see below)</p>
<pre><code>import json
data = []
with open('yelp_data.json') as f:
for line in f:
data.append(json.loads(line))
star = []
for i in range(len(data))... | 1 | 2016-07-28T15:32:37Z | 38,641,154 | <p>Not performance/memory related but you could replace:</p>
<pre><code>for i in range(len(data)):
star.append(data[i].values()[10])
</code></pre>
<p>by:</p>
<pre><code>for item in data:
star.append(item.values()[10])
</code></pre>
<p><code>data</code> being a <code>list</code>, it is iterable. <a href="htt... | 0 | 2016-07-28T15:48:49Z | [
"python",
"memory",
"scikit-learn"
] |
PyQt: How do I change the customContextMenu trigger? | 38,640,903 | <p>I'd like to change how a custom contextMenu is triggered on a widget, but I haven't found a solution. I'm adding a contextMenu to a QListWidget in a standard way:</p>
<pre><code>self.shotsList = QtGui.QListWidget()
self.shotsList.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.shotsList.customContextMenuReq... | 0 | 2016-07-28T15:36:59Z | 38,667,426 | <pre><code>#customContextMenu trigger
#This is the example code for customContextMenu trigger
#If your are not expecting this answer, sorry.
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class Window (QtGui.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(par... | 0 | 2016-07-29T21:00:56Z | [
"python",
"qt",
"pyqt",
"pyside"
] |
Regex multiline syntax help (python) | 38,640,954 | <p>I'm struggling to do multiline regex with multiple matches.</p>
<p>I have data separated by newline/linebreaks like below. My pattern matches each of these lines if i test it separately. How can i match all the occurrences (specifically numbers?</p>
<p>I've read that i could/should use DOTALL somehow (possibly wit... | 2 | 2016-07-28T15:39:10Z | 38,641,147 | <p><code>/</code> has no special meaning so you do not have to escape it (and in not-raw strings you would have to escape every <code>\</code>)</p>
<p>try this</p>
<pre><code>regPattern = r'^\s*(?:https?://)?(?:www\.)?(?:store\.steampowered\.com/app/)?([0-9]+)/?\s*$'
</code></pre>
| 1 | 2016-07-28T15:48:21Z | [
"python",
"regex",
"python-3.x"
] |
Regex multiline syntax help (python) | 38,640,954 | <p>I'm struggling to do multiline regex with multiple matches.</p>
<p>I have data separated by newline/linebreaks like below. My pattern matches each of these lines if i test it separately. How can i match all the occurrences (specifically numbers?</p>
<p>I've read that i could/should use DOTALL somehow (possibly wit... | 2 | 2016-07-28T15:39:10Z | 38,641,151 | <pre><code>import re
p = re.compile(ur'^\s*(?:https?:\/\/)?(?:www\.)?(?:store\.steampowered\.com\/app\/)?([0-9]+)\/?\s*$', re.MULTILINE)
test_str = u"http://store.steampowered.com/app/254060/\nhttp://www.store.steampowered.com/app/254061/\nhttps://www.store.steampowered.com/app/254062\nstore.steampowered.com/app/254063... | 3 | 2016-07-28T15:48:31Z | [
"python",
"regex",
"python-3.x"
] |
Regex multiline syntax help (python) | 38,640,954 | <p>I'm struggling to do multiline regex with multiple matches.</p>
<p>I have data separated by newline/linebreaks like below. My pattern matches each of these lines if i test it separately. How can i match all the occurrences (specifically numbers?</p>
<p>I've read that i could/should use DOTALL somehow (possibly wit... | 2 | 2016-07-28T15:39:10Z | 38,641,352 | <p><code>re.search</code> stop at the first occurrence</p>
<p>You should use this intead</p>
<p><code>re.findall(regPattern, data, re.MULTILINE)
['254060', '254061', '254062', '254063', '254064']
</code></p>
<p>Note: Search was not working for me (python 2.7.9). It just return the first line of data</p>
| 1 | 2016-07-28T15:57:52Z | [
"python",
"regex",
"python-3.x"
] |
Rasperry pi uart and custom rs485 based protocol | 38,641,048 | <p>I'm trying to read data coming off of the primary uart /dev/ttyAMA0 on a raspberry pi which is sent from Arduino Nano.</p>
<p>Library on the arduino side <a href="https://gitlab.com/creator-makerspace/rs485-nodeproto" rel="nofollow">https://gitlab.com/creator-makerspace/rs485-nodeproto</a></p>
<p>So I use a simple... | 0 | 2016-07-28T15:44:15Z | 38,675,120 | <p>try connect the boards directly uart to uart.it will give you indication if it uart configuration issue or rs485 issue.</p>
<p>also consider HW problem such as missing GND connection between the boards.</p>
<p>what is the length of cable between the boards?</p>
| 0 | 2016-07-30T14:41:22Z | [
"python",
"arduino",
"raspberry-pi",
"raspberry-pi2",
"rs485"
] |
Serve a profile picture whose path is stored in database with Flask Python | 38,641,052 | <p>I am trying to serve a profile picture whose path is stored in the sqlalchemy database. </p>
<p>The snippet code is :</p>
<pre><code>@employees.route('/upload-picture/<full_name>', methods=['GET', 'POST'])
@login_required
def upload(full_name):
if not current_user.is_employee:
abort(403)
borr... | 1 | 2016-07-28T15:44:23Z | 38,641,819 | <p>The <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage.save" rel="nofollow">save</a> function is used to save the file permanently to your filesystem,it does not create the path. You need to create the path to a specific image and save it as an attribute <code>self.prof... | 0 | 2016-07-28T16:20:50Z | [
"python",
"flask",
"jinja2"
] |
Sklearn PCA returning an array with only one value, when given an array of hundreds | 38,641,162 | <p>I wrote a program intended to classify an image by similarity: </p>
<pre><code>for i in g:
fulFi = i
tiva = []
tivb = []
a = cv2.imread(i)
b = cv2.resize(a, (500, 500))
img2 = flatten_image(b)
tivb.append(img2)
cb = np.array(tivb)
iab = trueArray(cb)
print "Image: ... | 2 | 2016-07-28T15:49:02Z | 38,641,594 | <p>If <code>n_components=2</code>, <code>RandomizedPCA</code> will only keep a maximum of 2 components (see the documentation <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.RandomizedPCA.html" rel="nofollow">here</a>). Try increasing this to allow more components to be selected; this sh... | 2 | 2016-07-28T16:09:15Z | [
"python",
"numpy",
"scikit-learn",
"transform",
"pca"
] |
Sklearn PCA returning an array with only one value, when given an array of hundreds | 38,641,162 | <p>I wrote a program intended to classify an image by similarity: </p>
<pre><code>for i in g:
fulFi = i
tiva = []
tivb = []
a = cv2.imread(i)
b = cv2.resize(a, (500, 500))
img2 = flatten_image(b)
tivb.append(img2)
cb = np.array(tivb)
iab = trueArray(cb)
print "Image: ... | 2 | 2016-07-28T15:49:02Z | 38,647,449 | <p>What you are doing with <code>X = pca.fit_transform(iab)</code> and <code>Xy = pca.transform(X)</code> is wrong. </p>
<ol>
<li>You are loosing the <code>iab</code> variable for the two images. You need the
flattened array of both images, outside of your for loop. However,
after your first iteration, your second ite... | 1 | 2016-07-28T22:00:34Z | [
"python",
"numpy",
"scikit-learn",
"transform",
"pca"
] |
How to plot multiple rows on Pandas? | 38,641,177 | <p>Say I have the following <code>pandas</code> dataframe:</p>
<pre><code>In[114]: df
Out[114]:
0-10% 11-20% 21-30% 31-40% 41-50% 51-60% 61-70% 71-80% 81-90% \
f 0.186 3.268 3.793 4.554 6.421 6.345 7.383 8.476 8.968
l 1.752 2.205 2.508 2.866 3.132 3.157 3.724 4.073... | 3 | 2016-07-28T15:49:36Z | 38,641,255 | <p>you can <code>plot.bar</code> on the transpose:</p>
<pre><code>df.T.plot.bar()
</code></pre>
<p><a href="http://i.stack.imgur.com/DHOB7.png" rel="nofollow"><img src="http://i.stack.imgur.com/DHOB7.png" alt="enter image description here"></a></p>
| 3 | 2016-07-28T15:53:22Z | [
"python",
"pandas",
"bar-chart",
"categories"
] |
In Django can I set descendants of a Model class to use different defaults? | 38,641,216 | <p>In django (v1.9) is there a way to set a field that is defined in the base
class to use a different default value in the different descendant classes? </p>
<pre><code>class Base(models.Model):
OBJ_TYPES = (
('type_a', 'Type A'),
('type_b', 'Type B'),
('type_c', 'Type C'),
('type_... | 1 | 2016-07-28T15:51:08Z | 38,645,848 | <p>Yes, it can be overriden, but probably not in a way that you would expect. Your modified code that will work:</p>
<pre><code>class Base(models.Model):
OBJ_TYPES = (
('type_a', 'Type A'),
('type_b', 'Type B'),
('type_c', 'Type C'),
('type_d', 'Type D'),
)
obj_type = models... | 0 | 2016-07-28T20:10:06Z | [
"python",
"django",
"django-models"
] |
Python subprocess sudo returns error: ERROR: ['sudo: sorry, you must have a tty to run sudo\n'] | 38,641,224 | <p>Here is my code: </p>
<pre><code>import subprocess
HOST = 'host_name'
PORT = '111'
USER = 'user_name'
CMD = 'sudo su - ec2-user; ls'
process = subprocess.Popen(['ssh','{}@{}'.format(USER, HOST),
'-p', PORT, CMD],
shell=False,
stdout=subprocess.... | 0 | 2016-07-28T15:51:31Z | 38,641,856 | <p><code>sudo</code> is prompting you for a password, but it needs a terminal to do that. Passing <code>-t</code> or <code>-tt</code> provides a terminal for the remote command to run in, but now it is waiting for you to enter a password.</p>
<pre><code>process = subprocess.Popen(['ssh','-tt', '{}@{}'.format(USER, HOS... | 1 | 2016-07-28T16:22:28Z | [
"python",
"bash",
"ssh",
"subprocess",
"sudo"
] |
Python subprocess sudo returns error: ERROR: ['sudo: sorry, you must have a tty to run sudo\n'] | 38,641,224 | <p>Here is my code: </p>
<pre><code>import subprocess
HOST = 'host_name'
PORT = '111'
USER = 'user_name'
CMD = 'sudo su - ec2-user; ls'
process = subprocess.Popen(['ssh','{}@{}'.format(USER, HOST),
'-p', PORT, CMD],
shell=False,
stdout=subprocess.... | 0 | 2016-07-28T15:51:31Z | 38,644,907 | <p>You can tell <code>sudo</code> to work without requiring a password. Just add this to <code>/etc/sudoers</code> on the remote server <code>host_name</code>.</p>
<pre><code>user ALL = (ec2-user) NOPASSWD: ls
</code></pre>
<p>This allows the user named <code>user</code> to execute the command <code>ls</code> as <cod... | 0 | 2016-07-28T19:12:39Z | [
"python",
"bash",
"ssh",
"subprocess",
"sudo"
] |
Upsample data and interpolate | 38,641,235 | <p>I have the following dataframe:</p>
<pre><code>Month Col_1 Col_2
1 0,121 0,123
2 0,231 0,356
3 0,150 0,156
4 0,264 0,426
...
</code></pre>
<p>I need to resample this to weekly resolution and to interpolate between the points. The latter part, the interpolation is straight-... | 2 | 2016-07-28T15:51:56Z | 38,641,505 | <p>I have to assume a start date, I chose <code>2009-12-31</code>.</p>
<p>To get <code>resample</code> to work, you need a <code>pd.DateTimeIndex</code>.</p>
<pre><code>start_date = pd.to_datetime('2009-12-31')
df.Month = df.Month.apply(lambda x: start_date + pd.offsets.MonthEnd(x))
df = df.set_index('Month')
df.res... | 2 | 2016-07-28T16:05:03Z | [
"python",
"pandas",
"interpolation"
] |
Can metaclass be any callable? | 38,641,300 | <p>To catch your eyes:</p>
<h1>I think the documentation might be wrong!</h1>
<p>According to Python 2.7.12 documentation, <strong>3.4.3. Customizing class creation¶</strong>:</p>
<blockquote>
<p><code>__metaclass__</code> This variable can be <strong>any callable</strong> accepting
arguments for name, bases, a... | 5 | 2016-07-28T15:55:31Z | 38,641,403 | <p>No, any callable will do. In your case the <code>type.__new__()</code> method has a restriction you are violating; this has nothing to do with what you assign to <code>__metaclass__</code>.</p>
<p>A function is a callable:</p>
<pre><code>def metaclass_function(name, bases, body):
return type(name, bases, body)... | 5 | 2016-07-28T16:00:28Z | [
"python",
"python-2.7",
"class",
"types",
"metaclass"
] |
Multithreading Python For DB Insert | 38,641,314 | <p>Hi guys currently i am trying to migrate current db to another and that process unfortunately involves python. I was able to do it single threaded, but it's incredibly slow took hours to finish 1M data. Is there similar method in python like Java executor and futures? </p>
<p>note that user_list is a chunk of 1000/... | 0 | 2016-07-28T15:56:00Z | 38,670,094 | <p>Since you say in the comments that you are using orientdb, have a look
at the <a href="http://orientdb.com/docs/2.1/SQL-batch.html" rel="nofollow">SQL Batch</a> capability.</p>
<p>Using SQL BATCH does not insert rows in parallel, but it will avoid the round-trip for each command.</p>
<p>You can also use SQL BATCH ... | 1 | 2016-07-30T03:31:52Z | [
"python",
"multithreading",
"orientdb"
] |
Leaving dictionary field empty if no value is there | 38,641,336 | <p>My last value variable will contain an empty string if there is no "Type2" value, if this occurs i want the dictionary for that KEY not to contain a "Type2" key:value.</p>
<p>How would i go about that?</p>
<pre><code>pokemon_name = json['Items'][i]['Pokemon']['UniqueId'][14:]
pokemon_type_one = json['Items'][... | -1 | 2016-07-28T15:56:56Z | 38,641,391 | <p>Enclosing that portion in an <code>if</code> should work for you.</p>
<pre><code>pokemon_name = json['Items'][i]['Pokemon']['UniqueId'][14:]
pokemon_type_one = json['Items'][i]['Pokemon']['Type1'][13:]
if 'Type2' in json['Items'][i]['Pokemon']:
pokemon_type_two = json['Items'][i]['Pokemon']['Type2'][13:]
... | 0 | 2016-07-28T15:59:49Z | [
"python",
"json",
"python-2.7",
"dictionary"
] |
Linear regression using Sklearn prediction not working. data not fit properly | 38,641,342 | <p>I am trying to perform a linear regression on following data.</p>
<pre><code>X = [[ 1 26]
[ 2 26]
[ 3 26]
[ 4 26]
[ 5 26]
[ 6 26]
[ 7 26]
[ 8 26]
[ 9 26]
[10 26]
[11 26]
[12 26]
[13 26]
[14 26]
[15 26]
[16 26]
[17 26]
[18 26]
[19 26]
[20 26]
[21 26]
[22 26]
[23 26]
[24 26]
[25 26]
[26 26]
... | 3 | 2016-07-28T15:57:15Z | 38,641,623 | <p>As SAMO said in his comment, it's not clear what your data structures are. Assuming you have two features in X and a target Y, if you convert X and Y to numpy arrays your code works as expected.</p>
<pre><code>import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
x1 = range(1, 70)
x2 ... | 2 | 2016-07-28T16:11:18Z | [
"python",
"machine-learning",
"scikit-learn",
"linear-regression"
] |
Linear regression using Sklearn prediction not working. data not fit properly | 38,641,342 | <p>I am trying to perform a linear regression on following data.</p>
<pre><code>X = [[ 1 26]
[ 2 26]
[ 3 26]
[ 4 26]
[ 5 26]
[ 6 26]
[ 7 26]
[ 8 26]
[ 9 26]
[10 26]
[11 26]
[12 26]
[13 26]
[14 26]
[15 26]
[16 26]
[17 26]
[18 26]
[19 26]
[20 26]
[21 26]
[22 26]
[23 26]
[24 26]
[25 26]
[26 26]
... | 3 | 2016-07-28T15:57:15Z | 38,641,981 | <p>You are probably messing with the input arrays before the plot. Given by the information in your question, the regression indeed returns a result close to your expected answer of 625170. </p>
<pre><code>from sklearn import linear_model
# your input arrays
x = [[a, 26] for a in range(1, 70, 1)]
y = [192770, 1481799... | 1 | 2016-07-28T16:29:18Z | [
"python",
"machine-learning",
"scikit-learn",
"linear-regression"
] |
How to update an existing Python Flask web page based on form input? | 38,641,484 | <p>I am trying to build a prediction web application with Flask. The app should take in user input, process it through a python trained model, then display the results as a chart beside the input form. </p>
<p>My code looks like this:</p>
<p><strong>HTML Form:</strong></p>
<pre><code><form class = "prediction-opt... | 0 | 2016-07-28T16:04:01Z | 38,649,777 | <p>You can use a <code>session</code> for this, before the last line in your <code>predict</code> route, store the prediction with</p>
<pre><code>session['prediction'] = prediction
</code></pre>
<p>and then you can access in any other route in your application, for example you can have this for <code>/</code></p>
<p... | 0 | 2016-07-29T02:48:31Z | [
"python",
"html",
"forms",
"flask"
] |
class not functioning methods properly | 38,641,494 | <p>I defined a class to handle blocks of tweets so I could manage them a little easier </p>
<pre><code>class twitter_block(object):
def __init__(self):
self.tweets = []
self.df = pd.DataFrame()
self.tag = ''
def load(self, data):
self.tweets = [x for x in data]
</code></pre>
<p>then defined a metho... | -1 | 2016-07-28T16:04:30Z | 38,641,602 | <p>I believe the problem is that you are using re.match() instead of re.search()</p>
<p>Where you want to find the tweets that contain a smiley anywhere in the tweet, re.match() searches only from the beginning of the string. </p>
<p>See <a href="http://stackoverflow.com/questions/3346076/python-re-match-vs-re-searc... | 0 | 2016-07-28T16:09:54Z | [
"python",
"regex",
"class",
"methods"
] |
Extend data frame with missing dates by group and interpolate | 38,641,596 | <p>I have a data frame like this:</p>
<pre><code>df = pd.DataFrame({"ID":["A", "A", "A" ,"B", "B"], "date":["06/24/2014","06/26/2014","06/29/2014","07/02/1999","07/04/1999"], "value": ["4","6","9","2","4"] })
ID date value
0 A 06/24/2014 4
1 A 06/26/2014 6
2 A 06/29/2014 9
3 B 07/02/1999 ... | 2 | 2016-07-28T16:09:22Z | 38,642,960 | <p>I'd do it this way:</p>
<pre><code>In [6]: df.groupby('ID').apply(lambda x: x.set_index('date').resample('D').pad())
Out[6]:
ID value
ID date
A 2014-06-24 A 4
2014-06-25 A 4
2014-06-26 A 6
2014-06-27 A 6
2014-06-28 A 6
2014-06-29 A 9
B 1999-07-02 B 2... | 0 | 2016-07-28T17:23:55Z | [
"python",
"pandas"
] |
Extend data frame with missing dates by group and interpolate | 38,641,596 | <p>I have a data frame like this:</p>
<pre><code>df = pd.DataFrame({"ID":["A", "A", "A" ,"B", "B"], "date":["06/24/2014","06/26/2014","06/29/2014","07/02/1999","07/04/1999"], "value": ["4","6","9","2","4"] })
ID date value
0 A 06/24/2014 4
1 A 06/26/2014 6
2 A 06/29/2014 9
3 B 07/02/1999 ... | 2 | 2016-07-28T16:09:22Z | 38,642,978 | <p>I had to do some initial conditioning to ensure proper dtypes</p>
<h3>Setup</h3>
<pre><code>df = pd.DataFrame({"ID":["A", "A", "A" ,"B", "B"],
"date":["06/24/2014","06/26/2014","06/29/2014","07/02/1999","07/04/1999"],
"value": ["4","6","9","2","4"] })
df.date = pd.to_datetim... | 4 | 2016-07-28T17:25:26Z | [
"python",
"pandas"
] |
EC2 Spot Instance Termination & Python 2.7 | 38,641,619 | <p>I know that the termination notice is made available via the meta-data url and that I can do something similar to</p>
<pre><code>if requests.get("http://169.254.169.254/latest/meta-data/spot/termination-time").status_code == 200
</code></pre>
<p>in order to determine if the notice has been posted. I run a Python s... | 0 | 2016-07-28T16:10:51Z | 38,877,800 | <p>I wrote this code to demonstrate how a thread can be used to poll for the Spot instance termination. It first starts up a polling thread, which would be responsible for checking the http endpoint.</p>
<p>Then we create pool of fake workers <em>(mimicking real work to be done)</em> and starts running the pool. Event... | 0 | 2016-08-10T15:32:16Z | [
"python",
"multithreading",
"python-2.7",
"amazon-ec2"
] |
Library not loaded: libboost_python.dylib | 38,641,643 | <p>when I import modules, error occurs :</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/zhangshirui/pynaoqi-python2.7-2.1.4.13-mac64/naoqi.py", line 7, in <module>
import qi
File "/Users/zhangshirui/pynaoqi-python2.7-2.1.4.13-mac64/qi/__in... | 0 | 2016-07-28T16:12:28Z | 39,579,626 | <p>Same thing happened to me when I updated my OSX. I always have system integrity protection disabled on my laptop and when I updated OSX, my preference got overridden and it got enabled again.</p>
<p>Looking at the permissions issue it seemed related to it. So I ran
<code> csrutil disable </code>
in recovery mode.... | 0 | 2016-09-19T18:15:32Z | [
"python"
] |
Read stresses 'S' of Abaqus results with python | 38,641,683 | <p>Good evening,</p>
<p>i have done a script for getting a model and to generate results. I've tried to write in the same script a way for getting to read the values of stresses but python says :</p>
<pre><code>" File "C:/Users/TFG", line 250, in <module> RegionTen=odb.rootAssembly.noseSets['Set-1'] KeyErr... | 0 | 2016-07-28T16:14:08Z | 38,644,140 | <p>You are now trying to get an assembly level node set. Yet, you are defining your node set inside a part. Inside the Odb, you need to access this node set through an instance.</p>
<p>Figure out the instance name from the part name. Most likely it's just 'PART-1-1'. After you do this, get the region like this:</p>
<... | 1 | 2016-07-28T18:28:34Z | [
"python",
"keyerror",
"abaqus",
"stress",
"odb"
] |
Weighted correlation coefficient with pandas | 38,641,691 | <p>Is there any way to compute weighted correlation coefficient with pandas? I saw that R has such a method.
Also, I'd like to get the p value of the correlation. This I did not find also in R.
Link to Wikipedia for explanation about weighted correlation: <a href="https://en.wikipedia.org/wiki/Pearson_product-moment_co... | 1 | 2016-07-28T16:14:26Z | 38,647,581 | <p>I don't know of any Python packages that implement this, but it should be fairly straightforward to roll your own implementation. Using the naming conventions of the wikipedia article:</p>
<pre><code>def m(x, w):
"""Weighted Mean"""
return np.sum(x * w) / np.sum(w)
def cov(x, y, w):
"""Weighted Covari... | 1 | 2016-07-28T22:11:43Z | [
"python",
"pandas",
"correlation",
"pearson-correlation"
] |
subprocess error message:[Errno 2] in _execute_child raise child_exception | 38,641,712 | <p>In my program I call the command:</p>
<pre><code>command_two = 'sfit4Layer0.py -bv5 -fs'
subprocess.call(command_two.split(), shell=False)
</code></pre>
<p>I am using PyCharm and I get the error message:</p>
<pre><code>Traceback (most recent call last):
File "part2test.py", line 5, in <module>
subproc... | 0 | 2016-07-28T16:15:37Z | 38,641,853 | <p>You've missed <a href="https://docs.python.org/3/library/subprocess.html#frequently-used-arguments" rel="nofollow">an important part of the <code>subprocess</code> documentation</a>. "If passing a single string <em>[at the command, rather than a list of strings]</em>, either shell must be True (see below) or else th... | 0 | 2016-07-28T16:22:18Z | [
"python",
"subprocess"
] |
Sending JSON from python to Flask using request with no results | 38,641,745 | <p>I try to run small meet station on Arduino, in fact it is already can monitor temperature and humidity. So I decided to store data in DB and visualise ob web server using Flask. I create small script on python which get data from serial and send it to server.</p>
<pre><code>def send_JSON_to_server(meteodata):
p... | 0 | 2016-07-28T16:17:00Z | 38,682,290 | <p>I find out a stupid mistake in my Flask app, during routing you can see the line:</p>
<pre><code>@app.route('/api/meteo/', methods=['GET','POST'])
</code></pre>
<p>and here is a mistake which lead to response 301 and immediately generate GET. The right line should be:</p>
<pre><code>@app.route('/api/meteo', metho... | 0 | 2016-07-31T08:44:13Z | [
"python",
"json",
"flask"
] |
Finding the format of my timestamp in Python | 38,641,760 | <p>My time format is screwy, but it seemed workable, as a string with the following format:</p>
<pre><code>'47:37:00'
</code></pre>
<p>I tried to set a variable where:</p>
<pre><code>DT = '%H:%M:%S'
</code></pre>
<p>So I could find the difference between two times, but it's given me the following error:</p>
<pre><... | 0 | 2016-07-28T16:17:38Z | 38,642,281 | <p>It's because you set 47 to %H, that is not a proper value.
Here is an example:</p>
<pre><code>import datetime
dt = datetime.datetime.strptime('2016/07/28 12:37:00','%Y/%m/%d %H:%M:%S')
print dt
</code></pre>
<p>Output: 2016-07-28 12:37:00</p>
| 1 | 2016-07-28T16:45:16Z | [
"python",
"datetime"
] |
Finding the format of my timestamp in Python | 38,641,760 | <p>My time format is screwy, but it seemed workable, as a string with the following format:</p>
<pre><code>'47:37:00'
</code></pre>
<p>I tried to set a variable where:</p>
<pre><code>DT = '%H:%M:%S'
</code></pre>
<p>So I could find the difference between two times, but it's given me the following error:</p>
<pre><... | 0 | 2016-07-28T16:17:38Z | 38,645,834 | <p>You wrote "I can't seem to find documentation that would help me determine my time format so I could set DT and do arithmetic on it"</p>
<p>Try this: <a href="https://docs.python.org/3/library/datetime.html" rel="nofollow">https://docs.python.org/3/library/datetime.html</a></p>
<p>Way down to the bottom.</p>
<p>... | 1 | 2016-07-28T20:09:26Z | [
"python",
"datetime"
] |
Change name of xml attribute for multiple files via python | 38,641,765 | <p>I would like to change the name of an attribute on an xml element in multiple files. These files are an output from an image annotation tool. I have 1000 of such files, thus the position of those attribute name is not absolute.</p>
<p>My file is available at [XML FILE][1]. </p>
<p>Here I would like to change</p>
... | 0 | 2016-07-28T16:17:57Z | 38,642,734 | <p>I am assuming that the structure of your xml file will be same as </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<viper xmlns="http://lamp.cfar.umd.edu/viper#" xmlns:data="http://lamp.cfar.umd.edu/viperdata#">
<config>
<descriptor name="Desc0" type="OBJECT">
&... | 1 | 2016-07-28T17:10:05Z | [
"python",
"xml"
] |
Change name of xml attribute for multiple files via python | 38,641,765 | <p>I would like to change the name of an attribute on an xml element in multiple files. These files are an output from an image annotation tool. I have 1000 of such files, thus the position of those attribute name is not absolute.</p>
<p>My file is available at [XML FILE][1]. </p>
<p>Here I would like to change</p>
... | 0 | 2016-07-28T16:17:57Z | 38,643,192 | <p>A bit different from bhansa solution. I need some if else clause to check the names and then replace the name for some conditions.</p>
<pre><code>root=xmldoc.getroot()
#print(root[0][0])
for child in root[0][0]:
if(child.get('name') == 'Coulmn Chart with Error Bars '):
child.set("name","Column Chart")
... | 1 | 2016-07-28T17:36:24Z | [
"python",
"xml"
] |
Specify domains for Flask-CORS | 38,641,785 | <p>I have a Python script serving as web api and many domains will call this to get data they want. So to make this workable I need to enable CORS. I read through the Flask documentation but did not find the way to specify multiples domains to allows CORS for them.</p>
<p>Here is code snippet that enables CORS:</p>
<... | -1 | 2016-07-28T16:18:56Z | 38,643,881 | <p>From the documentation of CORS: <a href="http://flask-cors.corydolphin.com/en/latest/api.html?highlight=origin#flask_cors.cross_origin" rel="nofollow">http://flask-cors.corydolphin.com/en/latest/api.html?highlight=origin#flask_cors.cross_origin</a></p>
<p><code>flask_cors.cross_origin(*args, **kwargs)
</code>
<code... | 0 | 2016-07-28T18:13:22Z | [
"python",
"flask",
"cors"
] |
Push failed, heroku, django, scrapy-heroku | 38,641,857 | <p>Tried to add scrapy-heroku and dependencies to requirements.txt before pushing to heroku.</p>
<pre><code>remote: Traceback (most recent call last):
remote: File "<string>", line 1, in <module>
remote: File "/tmp/pip-build-IY3d_3/distribute/setup.py", line 58, in <... | 0 | 2016-07-28T16:22:32Z | 38,648,581 | <p>My problems began when I tried to add scrapy-heroku package to heroku. One of my dependencies contains the distribute package. Just put the scrapy-heroku package on the beginning of requirements.txt file. </p>
| 0 | 2016-07-29T00:07:01Z | [
"python",
"django",
"python-2.7",
"heroku"
] |
what is 'SingleBlockManager' in pandas? | 38,641,954 | <p>I get an error message when I am using some library</p>
<pre><code>AttributeError: 'SingleBlockManager' object has no attribute 'to_dense'
</code></pre>
<p>to_dense is a method for dataframe, therefore I assume SingleBlockManager should be a dataframe in my case. Does anyone know what SingleBlockManager is in Pand... | 0 | 2016-07-28T16:27:23Z | 38,642,029 | <p><code>SingleBlockManager</code> is an internal data structure which (essentially) holds the pieces of a <code>Series</code> - the index and values. You'd need to post some more context to see what's actually triggering the error.</p>
<pre><code>In [1]: s = pd.Series([1,2,3])
In [2]: s._data
Out[2]:
SingleBlockMan... | 2 | 2016-07-28T16:32:00Z | [
"python",
"pandas"
] |
How to benchmark a C program from a python script? | 38,641,967 | <p>I'm currently doing some work in uni that requires generating multiple benchmarks for multiple short C programs. I've written a python script to automate this process. Up until now I've been using the <code>time</code> module and essentially calculating the benchmark as such:</p>
<pre><code>start = time.time()
succ... | 1 | 2016-07-28T16:28:32Z | 38,642,153 | <p><code>timeit</code> will measure the CPU time used by the Python process in which it runs. Execution time of external processes will not be "credited" to those times.</p>
| 1 | 2016-07-28T16:38:31Z | [
"python",
"subprocess",
"benchmarking",
"timeit"
] |
How to benchmark a C program from a python script? | 38,641,967 | <p>I'm currently doing some work in uni that requires generating multiple benchmarks for multiple short C programs. I've written a python script to automate this process. Up until now I've been using the <code>time</code> module and essentially calculating the benchmark as such:</p>
<pre><code>start = time.time()
succ... | 1 | 2016-07-28T16:28:32Z | 38,642,875 | <p>A more accurate way would be to do it in C, where you can get true speed and throughput.</p>
| -1 | 2016-07-28T17:18:47Z | [
"python",
"subprocess",
"benchmarking",
"timeit"
] |
Scrapy send condition to parse from start_requests(self) | 38,641,972 | <p>Im scraping a website which has different rows base on the type of item that Im scraping. I have a working scraper that looks like the <em>1st blockcode</em> below, however, I would like to be able to take a type from the database and send from the start_requests(self) to the parse function. I have 11 different type... | 0 | 2016-07-28T16:28:48Z | 38,648,628 | <p>You can use <a href="http://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Request.meta" rel="nofollow"><code>request.meta</code></a></p>
<pre><code>def make_requests_from_url(self, url, type, callback):
request = scrapy.Request(url, callback)
request.meta['type'] = type
return reques... | 2 | 2016-07-29T00:13:15Z | [
"python",
"scrapy",
"conditional",
"scrape"
] |
concat two columns and store in a new column in a csv | 38,641,988 | <p>i am not getting the desired expected output.I have to concat "itemnumber" column with "imagename" column and save into another column "image" in that csv. Eg B001_B001 .It also creates a duplicate image "B001_B001.jpg" in the image folder. </p>
<p>My input is:</p>
<pre><code> ItemNumber UPC Keyword ImageName I... | 0 | 2016-07-28T16:29:54Z | 38,642,081 | <p>If you can use Pandas:</p>
<pre><code>import pandas as pd
df = pd.read_csv('rosary.csv')
df['Image'] = df.ImageName + "_" + df.ImageWChain
df.to_csv('rosary.csv')
>>> df
Unnamed: 0 Description ImageName ImageWChain ItemNumber Keyword UPC Image
0 0 Test1 B001 B001 ... | 0 | 2016-07-28T16:34:27Z | [
"python"
] |
Editing a specific cell with Pandas [Python] | 38,642,002 | <p>I am having a problem with Pandas, have looked everywhere but think I am overlooking something.</p>
<p>I have a csv file I import to pandas, which has a ID column and another column I will call Column 2. I want to:
1. Input an ID to python.
2. Search this ID in the ID column with Pandas, and put a 1 on the adjace... | 2 | 2016-07-28T16:30:36Z | 38,642,126 | <p>This is what I'd do:</p>
<pre><code>cond = csvfile.ID == '10099870.0'
col = 'Column 2'
csvfile.loc[cond, col] = csvfile.loc[cond, col].replace('missing', '1')
</code></pre>
| 2 | 2016-07-28T16:37:21Z | [
"python",
"pandas"
] |
Retrieving SmartSheet Content using Python SDK | 38,642,026 | <p>so ill try to keep this short as possible. I am a newbie to the SmartSheet Python SDK and im trying to call all the data from the Smartsheet and hopefully use that as a starting point for myself. So far what I have </p>
<pre><code>import smartsheet
smartsheet = smartsheet.Smartsheet('token1')
</code></pre>
<p>Whi... | -1 | 2016-07-28T16:31:41Z | 38,837,089 | <p>The following sample code retrieves a list of all columns from the specified Sheet, and then iterates through the columns printing out the Id and Title of each column. (You'll obviously need to replace <strong>ACCESS_TOKEN</strong> and <strong>SHEET_ID</strong> with your own values.)</p>
<pre><code># Import.
impor... | 0 | 2016-08-08T19:28:21Z | [
"python",
"sdk",
"smartsheet-api"
] |
raise ValueError("bad input shape {0}".format(shape)) ValueError: bad input shape (10, 90) | 38,642,046 | <p>I am new to this so any help is appriciated, this code was given to me by my prof when I asked for an example, I had hoped for a working model...</p>
<pre><code>from numpy import loadtxt
import numpy as np
from sklearn import svm
from sklearn.metrics import accuracy_score, f1_score
from sklearn.feature_selection im... | 0 | 2016-07-28T16:32:33Z | 38,644,693 | <p>I will submit this as an answer, because it directly addresses your real problem. </p>
<p>In general computer programming terminology, the error you have got is called a stack trace. There is a <a href="https://en.wikipedia.org/wiki/Stack_trace" rel="nofollow">Wikipedia page</a> on stack trace, but I will try and e... | 0 | 2016-07-28T19:00:43Z | [
"python",
"scikit-learn"
] |
Regex Lookbehind with 1 or more numbers | 38,642,084 | <p>I've searched under the tags <a href="/questions/tagged/regex" class="post-tag" title="show questions tagged 'regex'" rel="tag">regex</a>,<a href="/questions/tagged/lookbehind" class="post-tag" title="show questions tagged 'lookbehind'" rel="tag">lookbehind</a> and even <a href="/questions/tagged/neg... | 0 | 2016-07-28T16:34:55Z | 38,645,269 | <p>Variable-width lookbehinds are not supported in most regex engines, however, you can extract the <code>bar</code> part with one of two regexes:</p>
<pre><code><span class="foo">\d+\.<\/span>\K bar
</code></pre>
<p>Or</p>
<pre><code><span class="foo">(\d+)\.<\/span>(?<bar> bar)
</cod... | 0 | 2016-07-28T19:34:21Z | [
"python",
"html",
"regex",
"lookbehind",
"bbedit"
] |
string are splitted in 'list()' and not in '[]' why? | 38,642,110 | <p>I have been working in a project then I accidently
discovered when I pass string,they are splitted in <code>list()</code> but when I pass the same string to <code>[ ]</code> there is no splitting into single letters of the string.</p>
<p>Can anyone tell me what happend here?</p>
<pre><code>>>> y = list... | -2 | 2016-07-28T16:36:20Z | 38,642,162 | <p>in <code>>>> y = list("hello")</code>
You ask python to build a list from <code>"hello"</code> si it cut the string in element</p>
<p>and in <code>>>> z = ["hello"]</code>
you make a list with a single element <code>hello</code></p>
| 0 | 2016-07-28T16:38:56Z | [
"python",
"string",
"list"
] |
string are splitted in 'list()' and not in '[]' why? | 38,642,110 | <p>I have been working in a project then I accidently
discovered when I pass string,they are splitted in <code>list()</code> but when I pass the same string to <code>[ ]</code> there is no splitting into single letters of the string.</p>
<p>Can anyone tell me what happend here?</p>
<pre><code>>>> y = list... | -2 | 2016-07-28T16:36:20Z | 38,642,172 | <p>The list() method makes a list out of given input.</p>
<p>The version with square brackets implies you want to create a list with one element, your string. Therefore it is not splitted up.</p>
| 0 | 2016-07-28T16:39:31Z | [
"python",
"string",
"list"
] |
string are splitted in 'list()' and not in '[]' why? | 38,642,110 | <p>I have been working in a project then I accidently
discovered when I pass string,they are splitted in <code>list()</code> but when I pass the same string to <code>[ ]</code> there is no splitting into single letters of the string.</p>
<p>Can anyone tell me what happend here?</p>
<pre><code>>>> y = list... | -2 | 2016-07-28T16:36:20Z | 38,642,182 | <p>Because the <a href="https://docs.python.org/3/library/stdtypes.html#list" rel="nofollow"><code>list</code> constructor</a> takes an iterable as an argument and constructs a list from the items of that iterable. In your case it will grab each individual sub string in the string and us them as items.</p>
<p>On the c... | 3 | 2016-07-28T16:39:58Z | [
"python",
"string",
"list"
] |
string are splitted in 'list()' and not in '[]' why? | 38,642,110 | <p>I have been working in a project then I accidently
discovered when I pass string,they are splitted in <code>list()</code> but when I pass the same string to <code>[ ]</code> there is no splitting into single letters of the string.</p>
<p>Can anyone tell me what happend here?</p>
<pre><code>>>> y = list... | -2 | 2016-07-28T16:36:20Z | 38,642,201 | <p>y = list("hello")
list() is a built-in function that takes an iterable and "Return a list whose items are the same and in the same order as iterableâs items" (see <a href="https://docs.python.org/2/library/functions.html#list" rel="nofollow">https://docs.python.org/2/library/functions.html#list</a>).</p>
<p>z = [... | 0 | 2016-07-28T16:41:07Z | [
"python",
"string",
"list"
] |
string are splitted in 'list()' and not in '[]' why? | 38,642,110 | <p>I have been working in a project then I accidently
discovered when I pass string,they are splitted in <code>list()</code> but when I pass the same string to <code>[ ]</code> there is no splitting into single letters of the string.</p>
<p>Can anyone tell me what happend here?</p>
<pre><code>>>> y = list... | -2 | 2016-07-28T16:36:20Z | 38,642,207 | <p><a href="https://docs.python.org/2/library/functions.html#list" rel="nofollow"><code>list</code></a> is a <code>builtin</code> that takes an <em>iterable</em> and turns it into a list. </p>
<p><code>[]</code> on the other hand is a language construct for <em>defining</em> lists. To achieve the same results with the... | 2 | 2016-07-28T16:41:20Z | [
"python",
"string",
"list"
] |
string are splitted in 'list()' and not in '[]' why? | 38,642,110 | <p>I have been working in a project then I accidently
discovered when I pass string,they are splitted in <code>list()</code> but when I pass the same string to <code>[ ]</code> there is no splitting into single letters of the string.</p>
<p>Can anyone tell me what happend here?</p>
<pre><code>>>> y = list... | -2 | 2016-07-28T16:36:20Z | 38,642,209 | <p>Strings are iterable. The <code>list</code> function (really it's a type, but it's callable) iterates over its argument, making each element of the iterable (in your case, each character of a string) an element of the resulting list.</p>
<p>That's pretty much the same for any iterables. What you are doing is the st... | 1 | 2016-07-28T16:41:27Z | [
"python",
"string",
"list"
] |
string are splitted in 'list()' and not in '[]' why? | 38,642,110 | <p>I have been working in a project then I accidently
discovered when I pass string,they are splitted in <code>list()</code> but when I pass the same string to <code>[ ]</code> there is no splitting into single letters of the string.</p>
<p>Can anyone tell me what happend here?</p>
<pre><code>>>> y = list... | -2 | 2016-07-28T16:36:20Z | 38,642,355 | <p>In your first example;</p>
<pre><code>>>> y = list("hello")
</code></pre>
<p>you are casting a string "hello" to a list</p>
<p>In the second example;</p>
<pre><code>>>> z = ["hello"]
</code></pre>
<p>You are creating an array(list) with one item which is a string with contents "hello"</p>
| 0 | 2016-07-28T16:49:00Z | [
"python",
"string",
"list"
] |
Use String.Replace in a Python for loop | 38,642,197 | <p>I want to use <strong>string.replace</strong> using for loop. This is my code: </p>
<pre><code>new = ['p','q','r']
my_str = 'there are two much person a, person b, person c.'
old = ['a','b','c']
for i in range(0,len(old)):
my_str = string.replace(my_str,old[i],new[i])
print(my_str)
</code></pre>
<p>But it is... | 0 | 2016-07-28T16:40:49Z | 38,642,243 | <p>Try</p>
<pre><code>new = ['p','q','r']
my_str = 'there are two much person a, person b, person c.'
old = ['a','b','c']
for i in range(len(old)):
my_str = my_str.replace(old[i],new[i])
print(my_str)
</code></pre>
<p>but that is propably not very fast</p>
<p>If entries in old are all letters-only you can do</... | 2 | 2016-07-28T16:43:24Z | [
"python",
"string",
"replace"
] |
Use String.Replace in a Python for loop | 38,642,197 | <p>I want to use <strong>string.replace</strong> using for loop. This is my code: </p>
<pre><code>new = ['p','q','r']
my_str = 'there are two much person a, person b, person c.'
old = ['a','b','c']
for i in range(0,len(old)):
my_str = string.replace(my_str,old[i],new[i])
print(my_str)
</code></pre>
<p>But it is... | 0 | 2016-07-28T16:40:49Z | 38,642,291 | <p><code>string.replace()</code> is available on Python 2.x but deprecated in python 3.x.</p>
<p>Below is how you can use it in Python 3.x</p>
<blockquote>
<p>str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, ... | 1 | 2016-07-28T16:45:48Z | [
"python",
"string",
"replace"
] |
Use String.Replace in a Python for loop | 38,642,197 | <p>I want to use <strong>string.replace</strong> using for loop. This is my code: </p>
<pre><code>new = ['p','q','r']
my_str = 'there are two much person a, person b, person c.'
old = ['a','b','c']
for i in range(0,len(old)):
my_str = string.replace(my_str,old[i],new[i])
print(my_str)
</code></pre>
<p>But it is... | 0 | 2016-07-28T16:40:49Z | 38,642,413 | <p>Actually, I can not reproduce your problem; your code runs fine on Python 2.7. However, there are better ways to do it. First, instead of using a <code>range</code>, you could <code>zip</code> the <code>old</code> and <code>new</code> lists:</p>
<pre><code>for i in range(0,len(old)):
my_str = string.replace(my_... | 2 | 2016-07-28T16:52:15Z | [
"python",
"string",
"replace"
] |
iterate through previously filtered rows openpyxl | 38,642,234 | <p>I have a python code written that loads an excel workbook, iterates through all of the rows in a specified column, saves the rows in a dictionary and writes that dictionary to a .txt file. </p>
<p>The vb script that is referenced opens the workbook before openpyxl does and filters it to only show some data. </p>
<... | 0 | 2016-07-28T16:42:54Z | 38,642,410 | <p>Unfortunately <code>openpyxl</code> does not currently include filtering in its functionality. As <a href="http://openpyxl.readthedocs.io/en/default/filters.html#using-filters-and-sorts" rel="nofollow">the documentation</a> notes: "Filters and sorts can only be configured by openpyxl but will need to be applied in a... | 1 | 2016-07-28T16:52:09Z | [
"python",
"excel",
"vba",
"excel-vba",
"openpyxl"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.