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 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 and letters to generate the password, then the program is suppose to print out something like cold123, but instead it prints out cood111 or clld111, I will post a snippet of my code below, but please don't bad mouth it, I'm fairly new to python, self-taught and just about couple of months into the python experience. </p>
<pre><code>class G()
.
.
.
# self.forms is the format the user input they can input things such as C@@d%%%
# where @ is only letters and where % is only numbers
# self.Bank is a list where generated things go
AlphaB = [] #list Of All Of The Positions That have The @ sign in The self.forms
NumB = [] #list of All of the positions that have a % sign
for char in self.forms:
if char == '@':
EOL=(self.Position) # Positions End Of Line
Loc = self.forms[EOL] # Letter
AlphaB.append(EOL)
if char == '%':
EOL=(self.Position)
Loc = self.forms[EOL]
NumB.append(EOL)
self.Position+=1 # Move right a position
for pos in AlphaB:
for letter in self.alphas: #letters in The User Inputs
GenPass=(self.forms.replace(self.forms[pos],letter))
#Not Fully Formatted yet, because Only The letter been formatted
if GenPass.find('%'):
for Pos in NumB:
for number in self.ints:
GenPass=(GenPass.replace(GenPass[Pos],number))
if GenPass not in self.Bank:
#Cood111
print (GenPass)
self.Bank.append(GenPass)
else:
if GenPass not in self.Bank:
print (GenPass)
self.Bank.append(GenPass)
</code></pre>
| 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, SO posts and other peoples sourcecode, but I want to stick with python for easier textprocessing and interfaces to my other tools. </p>
<p>I found some code on sourceforge <a href="https://gist.github.com/evansneath/4650991" rel="nofollow">evansneath's Python CRC Implementation</a> which is nicely straight forward and wanted to give it a go, but I figured it does not work as expected (maybe I understood something completely wrong, but I am stuck here):</p>
<pre class="lang-py prettyprint-override"><code>def crc(msg, div, code='11111111'):
"""Cyclic Redundancy Check
Generates an error detecting code based on an inputted message and divisor in the form of a polynomial representation.
Arguments:
msg: The input message of which to generate the output code.
div: The divisor in polynomial form. For example, if the polynomial of x^3 + x + 1 is given, this should be represented as '1011' in the div argument.
code: This is an option argument where a previously generated code may be passed in. This can be used to check validity. If the inputted code produces an outputted code of all zeros, then the message has no errors.
Returns:
An error-detecting code generated by the message and the given divisor.
"""
msg = msg + code
msg = list (msg)
div = list (div)
for i in range (len (msg) - len (code)):
if msg[i] == '1':
for j in range (len (div)):
msg[i+j] = str ((int (msg[i+j])+int (div[j]))%2)
return ''.join (msg[-len (code):])
#Testing:
# Use a divisor that simulates: CRC8 SAE J1850 x^8+x^4+x^3+x^2+x^0
div = '100011101'#0x1D with leading 1 as given by polynomial
msg = '10101001' # 0xA9, just for a Test
print('Input message:', hex(int(msg,2)))
print('Polynomial:', hex(int(div,2)))
o = '11111111'
z = '00000000'
code = crc(msg, div, o)
print('CRC8 code:', hex(int(code,2)))
# Test for output code of '00000000' respectively '11111111' proving that the function worked correctly
print('Success:', crc(msg, div, code) == o)
</code></pre>
<p>I checked the results using this generator:
<a href="http://www.sunshine2k.de/coding/javascript/crc/crc_js.html" rel="nofollow">CRC Generator</a> which seems to be the only one featuring CRC8 SAE J1850 ZERO and non-ZERO. </p>
<p>Now the fun part: for ZERO the above code works perfectly fine. </p>
<p>Unfortunately the CRC codes I get from the software I want to check are initialized and checked against 0xFF ('11111111') where both tools deliver completely different results.
So far I wasn't even able to find some off-by-one issue (which I would have rated the most likely case) or a mathematical link between the solution calculated by the script above and the one by the website.
The website complies with the result from the software however the python part above doesn't.</p>
<p>Can anyone point me to a documentation I might have missed or is it another issue?
I already checked for MSB/LSB issues when entering messages on the website and tried initializing with 0xFE as some other code suggested. But no success... Most examples however are zero based and there I have no issues.</p>
<p><strong>Edit</strong>:</p>
<p>I checked the calculation and went through an example by hand as well as printing every single step and achieved the same. So mathematically it seems correct, but what is the SAE doing other than appending a line of '11111111' and then XOR-ing bitwise, then shifting until there is a leading one again, XOR-ing etc... and spitting out the remainder? It must be an issue of understanding on my side. </p>
<pre><code>Test 1 ---------------------------
Input message: 0xa9
Polynome: 0x11d
['1', '0', '1', '0', '1', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', 1']
/
['1', '0', '0', '0', '1', '1', '1', '0', '1']
=
current message: ['1', '0', '1', '0', '1', '0', '0', '1', '1', '1', '1', '1', '1 ', '1', '1', '1']
shift 0 Bits
1 XOR 1 = 0
0 XOR 0 = 0
1 XOR 0 = 1
0 XOR 0 = 0
1 XOR 1 = 0
0 XOR 1 = 1
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
current message: ['0', '0', '1', '0', '0', '1', '1', '1', '0', '1', '1', '1', '1 ', '1', '1', '1']
shift 2 Bits
1 XOR 1 = 0
0 XOR 0 = 0
0 XOR 0 = 0
1 XOR 0 = 1
1 XOR 1 = 0
1 XOR 1 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
current message: ['0', '0', '0', '0', '0', '1', '0', '0', '1', '1', '0', '1', '1 ', '1', '1', '1']
shift 5 Bits
1 XOR 1 = 0
0 XOR 0 = 0
0 XOR 0 = 0
1 XOR 0 = 1
1 XOR 1 = 0
0 XOR 1 = 1
1 XOR 1 = 0
1 XOR 0 = 1
1 XOR 1 = 0
CRC8 code: 0xab
Reverse Calculation: Check
['1', '0', '1', '0', '1', '0', '0', '1', '1', '0', '1', '0', '1', '0', '1', '1']
/
['1', '0', '0', '0', '1', '1', '1', '0', '1']
=
current message: ['1', '0', '1', '0', '1', '0', '0', '1', '1', '0', '1', '0', '1', '0', '1', '1']
shift 0 Bits
1 XOR 1 = 0
0 XOR 0 = 0
1 XOR 0 = 1
0 XOR 0 = 0
1 XOR 1 = 0
0 XOR 1 = 1
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
current message: ['0', '0', '1', '0', '0', '1', '1', '1', '0', '0', '1', '0', '1', '0', '1', '1']
shift 2 Bits
1 XOR 1 = 0
0 XOR 0 = 0
0 XOR 0 = 0
1 XOR 0 = 1
1 XOR 1 = 0
1 XOR 1 = 0
0 XOR 1 = 1
0 XOR 0 = 0
1 XOR 1 = 0
current message: ['0', '0', '0', '0', '0', '1', '0', '0', '1', '0', '0', '0', '1', '0', '1', '1']
shift 5 Bits
1 XOR 1 = 0
0 XOR 0 = 0
0 XOR 0 = 0
1 XOR 0 = 1
0 XOR 1 = 1
0 XOR 1 = 1
0 XOR 1 = 1
1 XOR 0 = 1
0 XOR 1 = 1
CRC correct: True
</code></pre>
| 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 easily translate that to Python if you like. Here is the bit-wise routine in C from crcgen:</p>
<pre><code>#include <stdint.h>
unsigned crc8sae_j1850_bit(unsigned crc, unsigned char const *data, size_t len) {
if (data == NULL)
return 0;
crc ^= 0xff;
while (len--) {
crc ^= *data++;
for (unsigned k = 0; k < 8; k++)
crc = crc & 0x80 ? (crc << 1) ^ 0x1d : crc << 1;
}
crc &= 0xff;
crc ^= 0xff;
return crc;
}
</code></pre>
<p>The "ZERO" version as listed on the linked CRC calculator page has these parameters, simply changing the initial and xorout values to zero:</p>
<pre><code>width=8 poly=0x1d init=0x00 refin=false refout=false xorout=0x00 check=0x37 name="CRC-8/SAE-J1850-ZERO"
</code></pre>
<p>Here is the bit-wise routine in C from crcgen for that one:</p>
<pre><code>#include <stdint.h>
unsigned crc8sae_j1850_zero_bit(unsigned crc, unsigned char const *data, size_t len) {
if (data == NULL)
return 0;
while (len--) {
crc ^= *data++;
for (unsigned k = 0; k < 8; k++)
crc = crc & 0x80 ? (crc << 1) ^ 0x1d : crc << 1;
}
crc &= 0xff;
return crc;
}
</code></pre>
| 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, SO posts and other peoples sourcecode, but I want to stick with python for easier textprocessing and interfaces to my other tools. </p>
<p>I found some code on sourceforge <a href="https://gist.github.com/evansneath/4650991" rel="nofollow">evansneath's Python CRC Implementation</a> which is nicely straight forward and wanted to give it a go, but I figured it does not work as expected (maybe I understood something completely wrong, but I am stuck here):</p>
<pre class="lang-py prettyprint-override"><code>def crc(msg, div, code='11111111'):
"""Cyclic Redundancy Check
Generates an error detecting code based on an inputted message and divisor in the form of a polynomial representation.
Arguments:
msg: The input message of which to generate the output code.
div: The divisor in polynomial form. For example, if the polynomial of x^3 + x + 1 is given, this should be represented as '1011' in the div argument.
code: This is an option argument where a previously generated code may be passed in. This can be used to check validity. If the inputted code produces an outputted code of all zeros, then the message has no errors.
Returns:
An error-detecting code generated by the message and the given divisor.
"""
msg = msg + code
msg = list (msg)
div = list (div)
for i in range (len (msg) - len (code)):
if msg[i] == '1':
for j in range (len (div)):
msg[i+j] = str ((int (msg[i+j])+int (div[j]))%2)
return ''.join (msg[-len (code):])
#Testing:
# Use a divisor that simulates: CRC8 SAE J1850 x^8+x^4+x^3+x^2+x^0
div = '100011101'#0x1D with leading 1 as given by polynomial
msg = '10101001' # 0xA9, just for a Test
print('Input message:', hex(int(msg,2)))
print('Polynomial:', hex(int(div,2)))
o = '11111111'
z = '00000000'
code = crc(msg, div, o)
print('CRC8 code:', hex(int(code,2)))
# Test for output code of '00000000' respectively '11111111' proving that the function worked correctly
print('Success:', crc(msg, div, code) == o)
</code></pre>
<p>I checked the results using this generator:
<a href="http://www.sunshine2k.de/coding/javascript/crc/crc_js.html" rel="nofollow">CRC Generator</a> which seems to be the only one featuring CRC8 SAE J1850 ZERO and non-ZERO. </p>
<p>Now the fun part: for ZERO the above code works perfectly fine. </p>
<p>Unfortunately the CRC codes I get from the software I want to check are initialized and checked against 0xFF ('11111111') where both tools deliver completely different results.
So far I wasn't even able to find some off-by-one issue (which I would have rated the most likely case) or a mathematical link between the solution calculated by the script above and the one by the website.
The website complies with the result from the software however the python part above doesn't.</p>
<p>Can anyone point me to a documentation I might have missed or is it another issue?
I already checked for MSB/LSB issues when entering messages on the website and tried initializing with 0xFE as some other code suggested. But no success... Most examples however are zero based and there I have no issues.</p>
<p><strong>Edit</strong>:</p>
<p>I checked the calculation and went through an example by hand as well as printing every single step and achieved the same. So mathematically it seems correct, but what is the SAE doing other than appending a line of '11111111' and then XOR-ing bitwise, then shifting until there is a leading one again, XOR-ing etc... and spitting out the remainder? It must be an issue of understanding on my side. </p>
<pre><code>Test 1 ---------------------------
Input message: 0xa9
Polynome: 0x11d
['1', '0', '1', '0', '1', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', 1']
/
['1', '0', '0', '0', '1', '1', '1', '0', '1']
=
current message: ['1', '0', '1', '0', '1', '0', '0', '1', '1', '1', '1', '1', '1 ', '1', '1', '1']
shift 0 Bits
1 XOR 1 = 0
0 XOR 0 = 0
1 XOR 0 = 1
0 XOR 0 = 0
1 XOR 1 = 0
0 XOR 1 = 1
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
current message: ['0', '0', '1', '0', '0', '1', '1', '1', '0', '1', '1', '1', '1 ', '1', '1', '1']
shift 2 Bits
1 XOR 1 = 0
0 XOR 0 = 0
0 XOR 0 = 0
1 XOR 0 = 1
1 XOR 1 = 0
1 XOR 1 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
current message: ['0', '0', '0', '0', '0', '1', '0', '0', '1', '1', '0', '1', '1 ', '1', '1', '1']
shift 5 Bits
1 XOR 1 = 0
0 XOR 0 = 0
0 XOR 0 = 0
1 XOR 0 = 1
1 XOR 1 = 0
0 XOR 1 = 1
1 XOR 1 = 0
1 XOR 0 = 1
1 XOR 1 = 0
CRC8 code: 0xab
Reverse Calculation: Check
['1', '0', '1', '0', '1', '0', '0', '1', '1', '0', '1', '0', '1', '0', '1', '1']
/
['1', '0', '0', '0', '1', '1', '1', '0', '1']
=
current message: ['1', '0', '1', '0', '1', '0', '0', '1', '1', '0', '1', '0', '1', '0', '1', '1']
shift 0 Bits
1 XOR 1 = 0
0 XOR 0 = 0
1 XOR 0 = 1
0 XOR 0 = 0
1 XOR 1 = 0
0 XOR 1 = 1
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
current message: ['0', '0', '1', '0', '0', '1', '1', '1', '0', '0', '1', '0', '1', '0', '1', '1']
shift 2 Bits
1 XOR 1 = 0
0 XOR 0 = 0
0 XOR 0 = 0
1 XOR 0 = 1
1 XOR 1 = 0
1 XOR 1 = 0
0 XOR 1 = 1
0 XOR 0 = 0
1 XOR 1 = 0
current message: ['0', '0', '0', '0', '0', '1', '0', '0', '1', '0', '0', '0', '1', '0', '1', '1']
shift 5 Bits
1 XOR 1 = 0
0 XOR 0 = 0
0 XOR 0 = 0
1 XOR 0 = 1
0 XOR 1 = 1
0 XOR 1 = 1
0 XOR 1 = 1
1 XOR 0 = 1
0 XOR 1 = 1
CRC correct: True
</code></pre>
| 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 premises I assumed. </p>
<p>This is why the C-Code did not help me solve the issue, because I never understood THIS was the problem in the first place. </p>
<p>The corrected code for SAE J1850 Calculation (with XORin 0xFF, XORout 0xFF, non reflected, non reversed, polynomial 0x1D) Bit-by-Bit is as follows.</p>
<p>Credits for the code remain with <a href="https://gist.github.com/evansneath/4650991" rel="nofollow">evensneath on github</a>, I merely changed the input. </p>
<pre><code>def crc(msg, div, code='11111111'):
"""Cyclic Redundancy Check
Generates an error detecting code based on an inputted message
and divisor in the form of a polynomial representation.
Arguments:
msg: The input message of which to generate the output code.
div: The divisor in polynomial form. For example, if the polynomial
of x^3 + x + 1 is given, this should be represented as '1011' in
the div argument.
code: This is an option argument where a previously generated code may
be passed in. This can be used to check validity. If the inputted
code produces an outputted code of all zeros, then the message has
no errors.
Returns:
An error-detecting code generated by the message and the given divisor.
"""
# Append the code to the message. If no code is given, default to '1111111'
# Uncomment every occurence of msg_XORIN if not CRC-8 SAE J1850
msg_XORIN = [] # XOR the input before appending the code
msg_XORIN = [str((int(msg[i])+1) %2) for i in range(len(list(msg)))]
msg = msg_XORIN
div = list(div)
msg = list(msg) + list(code) # Convert msg and div into list form for easier handling
# Loop over every message bit (minus the appended code)
for i in range(len(msg)-len(code)):
# If that messsage bit is not one, shift until it is.
if msg[i] == '1':
for j in range(len(div)):
# Perform modulo 2 ( == XOR) on each index of the divisor
msg[i+j] = str((int(msg[i+j])+int(div[j]))%2)
# Output the last error-checking code portion of the message generated
return ''.join(msg[-len(code):])
</code></pre>
<p>The testcases from the question can be carried over. call once to generate CRC, call again with msg + generated crc to verify.</p>
<p>Good source: <a href="http://reveng.sourceforge.net/crc-catalogue/1-15.htm#crc.cat-bits.8" rel="nofollow">http://reveng.sourceforge.net/crc-catalogue/1-15.htm#crc.cat-bits.8</a></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.connect('db.sqlite')
print "Opened database successfully";
cur = conn.execute("SELECT * FROM sightings")
row = cur.fetchone()
while row is not None:
if row[1] == 133:
print row[0], row[1]
else:
row = cur.fetchone():
cur.close()
conn.close()
</code></pre>
| -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], row[3], row[4], row[5], row[6]
row = cur.fetchone()
cur.close()
conn.close()
</code></pre>
| -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.connect('db.sqlite')
print "Opened database successfully";
cur = conn.execute("SELECT * FROM sightings")
row = cur.fetchone()
while row is not None:
if row[1] == 133:
print row[0], row[1]
else:
row = cur.fetchone():
cur.close()
conn.close()
</code></pre>
| -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 [1,3]. I have searched around for hours, but I don't understand the complex things I have been reading online so I'm not certain how to apply them.</p>
<pre><code># random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# one player mode
def onePlayer():
scoreP = 0
scoreC = 0
again = ""
player = False
print("---------------------------------------------")
print("\n\tPlayer VS Computer")
while player == False:
print("Weapons:")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("4. Quit")
player = input("\nSelect your weapon: ")
if player == "quit" or player == "q" or player == "4":
player = True
main()
else:
try:
player = int(player)
if player == 1:
player = WEAPON[0]
elif player == 2:
player = WEAPON[1]
elif player == 3:
player = WEAPON[2]
except:
print("please enter a number 1 through 4\n")
computer = WEAPON[randint(0,2)]
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 1:
# computer == paper
if computer == 1:
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Rock smashes scissors. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 2:
if computer == 2:
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Paper covers rock. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 3:
if computer == 0:
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Scissors cut paper. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
#else:
# print("Please select a valid play option\n")
player = False
</code></pre>
<p>Please don't mind the print statements inside the if/else statements. I realize these will need to be changed. My main issue is the logic of comparing user input to the computer's random list selection.</p>
| 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>if computer == 1:</code> to compare it with the person (your person variable is the same way; you assign a string to it before you compare it to integers). </p>
<p>You just have to make sure you are comparing apples to apples</p>
| 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 [1,3]. I have searched around for hours, but I don't understand the complex things I have been reading online so I'm not certain how to apply them.</p>
<pre><code># random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# one player mode
def onePlayer():
scoreP = 0
scoreC = 0
again = ""
player = False
print("---------------------------------------------")
print("\n\tPlayer VS Computer")
while player == False:
print("Weapons:")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("4. Quit")
player = input("\nSelect your weapon: ")
if player == "quit" or player == "q" or player == "4":
player = True
main()
else:
try:
player = int(player)
if player == 1:
player = WEAPON[0]
elif player == 2:
player = WEAPON[1]
elif player == 3:
player = WEAPON[2]
except:
print("please enter a number 1 through 4\n")
computer = WEAPON[randint(0,2)]
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 1:
# computer == paper
if computer == 1:
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Rock smashes scissors. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 2:
if computer == 2:
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Paper covers rock. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 3:
if computer == 0:
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Scissors cut paper. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
#else:
# print("Please select a valid play option\n")
player = False
</code></pre>
<p>Please don't mind the print statements inside the if/else statements. I realize these will need to be changed. My main issue is the logic of comparing user input to the computer's random list selection.</p>
| 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 seeing.</p>
<p>Also, in general, when coding try to use meaningful variable names and avoid reusing them for more than one purpose: In this case, two new variables like player_weapon and computer_weapon (instead of reusing player and computer) would have probably prevented your bug. Don't be lazy when declaring variables! ;)</p>
| 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 [1,3]. I have searched around for hours, but I don't understand the complex things I have been reading online so I'm not certain how to apply them.</p>
<pre><code># random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# one player mode
def onePlayer():
scoreP = 0
scoreC = 0
again = ""
player = False
print("---------------------------------------------")
print("\n\tPlayer VS Computer")
while player == False:
print("Weapons:")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("4. Quit")
player = input("\nSelect your weapon: ")
if player == "quit" or player == "q" or player == "4":
player = True
main()
else:
try:
player = int(player)
if player == 1:
player = WEAPON[0]
elif player == 2:
player = WEAPON[1]
elif player == 3:
player = WEAPON[2]
except:
print("please enter a number 1 through 4\n")
computer = WEAPON[randint(0,2)]
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 1:
# computer == paper
if computer == 1:
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Rock smashes scissors. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 2:
if computer == 2:
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Paper covers rock. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 3:
if computer == 0:
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Scissors cut paper. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
#else:
# print("Please select a valid play option\n")
player = False
</code></pre>
<p>Please don't mind the print statements inside the if/else statements. I realize these will need to be changed. My main issue is the logic of comparing user input to the computer's random list selection.</p>
| 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 == 'Paper':
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Rock smashes scissors. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 'Paper':
if computer == 'Scissors':
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Paper covers rock. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 'Scissors':
if computer == 'Rock':
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Scissors cut paper. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
#else:
# print("Please select a valid play option\n")
player = False
</code></pre>
| 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 [1,3]. I have searched around for hours, but I don't understand the complex things I have been reading online so I'm not certain how to apply them.</p>
<pre><code># random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# one player mode
def onePlayer():
scoreP = 0
scoreC = 0
again = ""
player = False
print("---------------------------------------------")
print("\n\tPlayer VS Computer")
while player == False:
print("Weapons:")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("4. Quit")
player = input("\nSelect your weapon: ")
if player == "quit" or player == "q" or player == "4":
player = True
main()
else:
try:
player = int(player)
if player == 1:
player = WEAPON[0]
elif player == 2:
player = WEAPON[1]
elif player == 3:
player = WEAPON[2]
except:
print("please enter a number 1 through 4\n")
computer = WEAPON[randint(0,2)]
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 1:
# computer == paper
if computer == 1:
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Rock smashes scissors. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 2:
if computer == 2:
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Paper covers rock. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 3:
if computer == 0:
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Scissors cut paper. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
#else:
# print("Please select a valid play option\n")
player = False
</code></pre>
<p>Please don't mind the print statements inside the if/else statements. I realize these will need to be changed. My main issue is the logic of comparing user input to the computer's random list selection.</p>
| 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"},
"Paper":{"Win":"Rock", "Loss":"Scissors", "Adj":"Covers"},
"Scissors":{"Win":"Paper", "Loss":"Rock", "Adj":'Cuts'}}
def have_won(player, computer):
#determines if the players choice has beaten the computers
if MAPP[player]["Win"] == computer:
adj = MAPP[player]['Adj']
return True, ' '.join([player, adj, computer])
else:
adj = MAPP[computer]['Adj']
return False, ' '.join([computer, adj, player])
# one player mode
def onePlayer():
scoreP = 0
scoreC = 0
again = ""
player = False
print("---------------------------------------------")
print("\n\tPlayer VS Computer")
while player == False:
print("Weapons:")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("4. Quit")
player = input("\nSelect your weapon: ")
if player == "quit" or player == "q" or player == "4":
player = True
else:
try:
player = int(player)
if player == 1:
player = WEAPON[0]
elif player == 2:
player = WEAPON[1]
elif player == 3:
player = WEAPON[2]
except:
print("please enter a number 1 through 4\n")
computer = WEAPON[randint(0,2)]
print player, computer
outcome = have_won(player, computer)
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif outcome[0] == True:
print(outcome[1]+"! You Win!!")
scoreP += 1
elif outcome[0] == False:
print(outcome[1]+"! You Lose!!")
scoreC += 1
#else:
# print("Please select a valid play option\n")
print("Player:",scoreP,"\nComputer:",scoreC)
player = False
onePlayer()
</code></pre>
| 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 keypress:</p>
<pre><code>def handle_keyrelease(self, event):
"""event handler for the keyrelease event on this widget"""
if event.keysym == "BackSpace":
self.delete(self.index(Tkinter.INSERT), Tkinter.END)
self.position = self.index(Tkinter.END)
if event.keysym == "Left":
if self.position < self.index(Tkinter.END): # delete the selection
self.delete(self.position, Tkinter.END)
else:
self.position = self.position-1 # delete one character
self.delete(self.position, Tkinter.END)
if event.keysym == "Right":
self.position = self.index(Tkinter.END) # go to end (no selection)
if event.keysym == "Down":
self.autocomplete(1) # cycle to next hit
if event.keysym == "Up":
self.autocomplete(-1) # cycle to previous hit
# perform normal autocomplete if event is a single key or an umlaut
if len(event.keysym) == 1 or event.keysym in tkinter_umlauts:
self.autocomplete()
</code></pre>
<p>And the Right key is set to do what I want, complete the first word I type in and skip to the end of it, my problem is the following, I want to change the Right key for the Tab key, but the tab key on my entry box selects all the text, and I couldn't find a way to change this behaviour, is there a way?</p>
<p>And here's the part of my code where I create my entry box for reference, sorry for that:</p>
<pre><code>from tkinter import *
import entryautocomplete as eac
if __name__ == '__main__':
# create Tkinter window
master = Tk()
# change the window name
master.title('Jarbas')
# avoids resizing of the window
master.resizable(width=False, height=False)
# center top the window on my computer
master.geometry('+400+0')
# adds an icon
img = Image("photo", file="jarbas.png")
master.tk.call('wm', 'iconphoto', master._w, img)
# create the entry frame
uinput = Frame(master)
# create the other frame
resultado = LabelFrame(
master, text='###', labelanchor='n', font='arial 12', relief='flat')
# places the two frames on the window
uinput.grid()
resultado.grid()
# place a label on the Entry frame, picked random from a list
Label(uinput, text=ola[randint(0, len(ola) - 1)]).grid()
# Creates the entry
texto = eac.AutocompleteEntry(
uinput, font='arial 14 bold', width='60', takefocus='off')
texto.grid(padx=5, pady=4)
texto.set_completion_list(comandos)
# calls the function 'get_input' once you press Return on the Entry box
# the function reads what is typed and does what it should do
texto.bind('<Return>', get_input)
# tkinter main loop
mainloop()
</code></pre>
| 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>def tab_handler(event):
return 'break'
entry.bind('<Tab>', tab_handler)
</code></pre>
<p>and simply changed the <code>if event.keysym == "Right":</code> on the EntryAutoComplete file to <code>if event.keysym == "Tab":</code></p>
<p>Worked great.</p>
| 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, "Ðе замÑжем / Ðе женаÑ", "ÐамÑжем / Ð¶ÐµÐ½Ð°Ñ / Ð¶Ð¸Ð²Ñ Ð² гÑажданÑком бÑаке", "Разведен/ живем поÑознÑ", "ÐÐ´Ð¾Ð²ÐµÑ / вдова")
</code></pre>
<p>I mean <code>1 - Ðе замÑжем / Ðе женаÑ, 2 - ÐамÑжем / Ð¶ÐµÐ½Ð°Ñ / Ð¶Ð¸Ð²Ñ Ð² гÑажданÑком бÑаке, 3 - Разведен/ живем поÑознÑ, 4 - ÐÐ´Ð¾Ð²ÐµÑ / вдова</code>
But it return <code>TypeError: function takes at most 3 arguments (5 given)</code>
Is another way to do this?</p>
| 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 1
1 2
2 3
3 4
d = {1:"Ðе замÑжем / Ðе женаÑ",
2:"ÐамÑжем / Ð¶ÐµÐ½Ð°Ñ / Ð¶Ð¸Ð²Ñ Ð² гÑажданÑком бÑаке",
3:"Разведен/ живем поÑознÑ",
4: "ÐÐ´Ð¾Ð²ÐµÑ / вдова"}
df['new'] = df.Qfamilystatus.map(d)
print (df)
Qfamilystatus new
0 1 Ðе замÑжем / Ðе женаÑ
1 2 ÐамÑжем / Ð¶ÐµÐ½Ð°Ñ / Ð¶Ð¸Ð²Ñ Ð² гÑажданÑком бÑаке
2 3 Разведен/ живем поÑознÑ
3 4 ÐÐ´Ð¾Ð²ÐµÑ / вдова
</code></pre>
<p>Then you can new column convert to <code>category</code>, which save memory:</p>
<pre><code>df['new'] = df.Qfamilystatus.map(d).astype('category')
print (df)
Qfamilystatus new
0 1 Ðе замÑжем / Ðе женаÑ
1 2 ÐамÑжем / Ð¶ÐµÐ½Ð°Ñ / Ð¶Ð¸Ð²Ñ Ð² гÑажданÑком бÑаке
2 3 Разведен/ живем поÑознÑ
3 4 ÐÐ´Ð¾Ð²ÐµÑ / вдова
print (df.dtypes)
Qfamilystatus int64
new category
dtype: object
</code></pre>
| 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.
Please see PEP 440 for more details.`
</code></pre>
<p>Fine. So I look at PEP 440 which says basically says "don't do that":</p>
<pre><code>As hashes cannot be ordered reliably such versions are not permitted in the
public version field. As with semantic versioning, the public .devN
suffix may be used to uniquely identify such releases for publication,
while the original DVCS based label can be stored in the project metadata.
</code></pre>
<p>I understand the logic here. But how <em>can</em> I include the hg revision in the project metadata? I can't find any (up-to-date) documentation for what the arguments to <code>setup.py:setup()</code> can include, but the distutils one I found <a href="https://docs.python.org/2/distutils/setupscript.html#additional-meta-data%20here" rel="nofollow">here</a> doesn't seem to provide a field for this.</p>
| 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 to a file, and include that in your source distribution via <code>MANIFEST.in</code>.</p>
<p>You could even include it directly in the arguments to <code>setup()</code>, which seems to simply ignore unknown keyword arguments:</p>
<pre><code>setup(name='Distutils',
version='1.0',
description='Python Distribution Utilities',
author='Greg Ward',
author_email='gward@python.net',
url='https://www.python.org/sigs/distutils-sig/',
packages=['distutils', 'distutils.command'],
revision='7ae7970a82c1',
)
</code></pre>
<p>This doesn't get recorded anywhere, but it is always available by inspection if someone needs to know it for debugging information or something. Because this relies on <code>setup()</code> ignoring unknown arguments -- which I'm not sure is explicitly documented behavior -- I don't know that this idea is actually one I would recommend.</p>
| 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.
Please see PEP 440 for more details.`
</code></pre>
<p>Fine. So I look at PEP 440 which says basically says "don't do that":</p>
<pre><code>As hashes cannot be ordered reliably such versions are not permitted in the
public version field. As with semantic versioning, the public .devN
suffix may be used to uniquely identify such releases for publication,
while the original DVCS based label can be stored in the project metadata.
</code></pre>
<p>I understand the logic here. But how <em>can</em> I include the hg revision in the project metadata? I can't find any (up-to-date) documentation for what the arguments to <code>setup.py:setup()</code> can include, but the distutils one I found <a href="https://docs.python.org/2/distutils/setupscript.html#additional-meta-data%20here" rel="nofollow">here</a> doesn't seem to provide a field for this.</p>
| 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 label>]</code></p>
</blockquote>
<p>In your case this would be <code><major>.<minor>+<mercurial_version></code>, which would result into <code>1.0+7ae7970a82c1</code></p>
| 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 "<string>", line 1, in <module>
File "/tmp/pip-build-JC9mq_/distribute/setup.py", line 58, in <module>
setuptools.setup(**setup_params)
File "/usr/lib/python2.7/distutils/core.py", line 151, in setup
dist.run_commands()
File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
self.run_command(cmd)
File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "setuptools/command/egg_info.py", line 177, in run
writer = ep.load(installer=installer)
File "pkg_resources.py", line 2241, in load
if require: self.require(env, installer)
File "pkg_resources.py", line 2254, in require
working_set.resolve(self.dist.requires(self.extras),env,installer)))
File "pkg_resources.py", line 2471, in requires
dm = self._dep_map
File "pkg_resources.py", line 2682, in _dep_map
self.__dep_map = self._compute_dependencies()
File "pkg_resources.py", line 2699, in _compute_dependencies
from _markerlib import compile as compile_marker
ImportError: No module named _markerlib
</code></pre>
<p>python 2.7, pip 8.1.2</p>
<p>[EDIT]
The solution of creating a new env. with <code>virtualenv myenv --distribute</code> worked for the local environment, but when I try to push to the heroku, it gives me exactly the same error: No module named _markerlib. So, the problem is not just in the local env.</p>
| 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>
<pre><code>pip install django-validated-file
</code></pre>
| 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
import geopy.distance
# Define starting point.
start = geopy.Point(48.853, 2.349)
# Define a general distance object, initialized with a distance of 1 km.
d = geopy.distance.VincentyDistance(kilometers = 1)
# Use the `destination` method with a bearing of 0 degrees (which is north)
# in order to go from point `start` 1 km to north.
print d.destination(point=start, bearing=0)
# ^^^ That prints "48 52m 0.0s N, 2 21m 0.0s E"
# How to get it to lat lng?
</code></pre>
<p>Also, I don't know the terminology. I think the coordinates I want are in 4236, but I don't know what <code>48 52m 0.0s N, 2 21m 0.0s E</code> is called.</p>
| 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 all elements of <code>sub</code> are negative, you would do this:</p>
<pre><code>all(x < 0 for x in sub)
</code></pre>
| 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><Table_title>fatal crashes by&#160;time of day</Table_title>
<cell>data1</cell>
<cell>data2</cell>
<cell>data3</cell>
</code></pre>
<p>CSV input:</p>
<pre><code>'fatal crashes by&#160;time of day', data1, data2, data3
</code></pre>
<p>However, when I read the XML into the ElementTree script using <code>ET.parse('file.xml')</code>, it seems to render the character a non-breaking space:</p>
<pre><code><Table_title>fatal crashes by time of day</Table_title>
<cell>data1</cell>
<cell>data2</cell>
<cell>data3</cell>
</code></pre>
<p>Which is exactly what it should do (I think). But in this scenario, I actually want <code>&#160;</code> to render as a string, so that it matches the first cell of the CSV (because when the CSV is read in, it interprets it as a string: <code>'fatal crashes by&#160;time of day'</code>).</p>
<p>Is there a way to:</p>
<ol>
<li>Force the XML script to read the non-breaking space as a string instead of an escaped character: <code><Table_title>fatal crashes by&#160;time of day</Table_title></code></li>
</ol>
<p>or</p>
<ol start="2">
<li>Force the XML script to read the CSV and render the character as an escaped character instead of a string: <code>'fatal crashes by time of day', data1, data2, data3</code></li>
</ol>
| 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 value: <code>"fatal crashes byã»time of day"</code> (where <code>ã»</code> is to represent the character with code 160, i.e. the non-breaking space)</li>
</ul></li>
</ul>
<p>This is 100% correct and you can't (and should not want to) do anything about it.</p>
<p>Your CSV <em>also</em> appears to contain a snippet of XML in its first column. However, it remains un-parsed until you parse it.</p>
<p>If you want to be able to compare the text values, you have no choice but to XML-parse the first column.</p>
<pre><code>import csv
import xml.etree.ElementTree as ET
# open your XML and CSV files...
for row in csv_reader:
temp = ET.fromstring('<temp>' + row[0] + '</temp>')
print(temp.text)
# compare temp.text to your XML
</code></pre>
| 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 exact middle of that surface with a linear value 10. The edge of the surface will be, let's say, 5. Of course all the voxels in between are within the range 5-10. Then, as the voxels move away from the surface the values quickly go down to zero. </p>
<p>With the binary classification I had an image with 1's in the places of the foreground and an image with 1's in the place of the background -- in other words a classification :) Now I want to have just one ground truth image with values like the following... </p>
<p><a href="http://i.stack.imgur.com/7dl8Q.png" rel="nofollow"><img src="http://i.stack.imgur.com/7dl8Q.png" alt="enter image description here"></a></p>
<p>Via this linear regression example, I assumed I could simply change the cost function to a least square function -- <code>cost = tf.square(y - pred)</code>. And of course I would change the ground truth.</p>
<p>However, when I do this, my predictions output <code>NaN</code>. My last layer is a linear sum of matrix weight values multiplied by the final output. I'm guessing this has something to do with it? I can't make it a <code>tf.nn.softmax()</code> function because that would normalize the values between 0 and 1. </p>
<p>So I believe <code>cost = tf.square(y - pred)</code> is the source of the issue. I tried this next... <code>cost = tf.reduce_sum(tf.square(y - pred))</code> and that didn't work.</p>
<p>So then I tried this (recommended <a href="http://blog.altoros.com/using-linear-regression-in-tensorflow.html" rel="nofollow">here</a>) <code>cost = tf.reduce_sum(tf.pow(pred - y, 2))/(2 * batch_size)</code> and that didn't work.</p>
<p>Should I be initializing weights differently? Normalize weights?</p>
<p>Full code looks like this: </p>
<pre><code>import tensorflow as tf
import pdb
import numpy as np
from numpy import genfromtxt
from PIL import Image
from tensorflow.python.ops import rnn, rnn_cell
from tensorflow.contrib.learn.python.learn.datasets.scroll import scroll_data
# Parameters
learning_rate = 0.001
training_iters = 1000000
batch_size = 2
display_step = 1
# Network Parameters
n_input_x = 396 # Input image x-dimension
n_input_y = 396 # Input image y-dimension
n_classes = 1 # Binary classification -- on a surface or not
n_steps = 396
n_hidden = 128
n_output = n_input_y * n_classes
dropout = 0.75 # Dropout, probability to keep units
# tf Graph input
x = tf.placeholder(tf.float32, [None, n_input_x, n_input_y])
y = tf.placeholder(tf.float32, [None, n_input_x * n_input_y], name="ground_truth")
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)
# Create some wrappers for simplicity
def conv2d(x, W, b, strides=1):
# Conv2D wrapper, with bias and relu activation
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool2d(x, k=2):
# MaxPool2D wrapper
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
padding='SAME')
def deconv2d(prev_layer, w, b, output_shape, strides):
# Deconv layer
deconv = tf.nn.conv2d_transpose(prev_layer, w, output_shape=output_shape, strides=strides, padding="VALID")
deconv = tf.nn.bias_add(deconv, b)
deconv = tf.nn.relu(deconv)
return deconv
# Create model
def net(x, cnn_weights, cnn_biases, dropout):
# Reshape input picture
x = tf.reshape(x, shape=[-1, 396, 396, 1])
with tf.name_scope("conv1") as scope:
# Convolution Layer
conv1 = conv2d(x, cnn_weights['wc1'], cnn_biases['bc1'])
# Max Pooling (down-sampling)
#conv1 = tf.nn.local_response_normalization(conv1)
conv1 = maxpool2d(conv1, k=2)
# Convolution Layer
with tf.name_scope("conv2") as scope:
conv2 = conv2d(conv1, cnn_weights['wc2'], cnn_biases['bc2'])
# Max Pooling (down-sampling)
# conv2 = tf.nn.local_response_normalization(conv2)
conv2 = maxpool2d(conv2, k=2)
# Convolution Layer
with tf.name_scope("conv3") as scope:
conv3 = conv2d(conv2, cnn_weights['wc3'], cnn_biases['bc3'])
# Max Pooling (down-sampling)
# conv3 = tf.nn.local_response_normalization(conv3)
conv3 = maxpool2d(conv3, k=2)
temp_batch_size = tf.shape(x)[0] #batch_size shape
with tf.name_scope("deconv1") as scope:
output_shape = [temp_batch_size, 99, 99, 64]
strides = [1,2,2,1]
# conv4 = deconv2d(conv3, weights['wdc1'], biases['bdc1'], output_shape, strides)
deconv = tf.nn.conv2d_transpose(conv3, cnn_weights['wdc1'], output_shape=output_shape, strides=strides, padding="SAME")
deconv = tf.nn.bias_add(deconv, cnn_biases['bdc1'])
conv4 = tf.nn.relu(deconv)
# conv4 = tf.nn.local_response_normalization(conv4)
with tf.name_scope("deconv2") as scope:
output_shape = [temp_batch_size, 198, 198, 32]
strides = [1,2,2,1]
conv5 = deconv2d(conv4, cnn_weights['wdc2'], cnn_biases['bdc2'], output_shape, strides)
# conv5 = tf.nn.local_response_normalization(conv5)
with tf.name_scope("deconv3") as scope:
output_shape = [temp_batch_size, 396, 396, 1]
#this time don't use ReLu -- since output layer
conv6 = tf.nn.conv2d_transpose(conv5, cnn_weights['wdc3'], output_shape=output_shape, strides=[1,2,2,1], padding="VALID")
x = tf.nn.bias_add(conv6, cnn_biases['bdc3'])
# Include dropout
#conv6 = tf.nn.dropout(conv6, dropout)
x = tf.reshape(conv6, [-1, n_input_x, n_input_y])
# Prepare data shape to match `rnn` function requirements
# Current data input shape: (batch_size, n_steps, n_input)
# Permuting batch_size and n_steps
x = tf.transpose(x, [1, 0, 2])
# Reshaping to (n_steps*batch_size, n_input)
x = tf.reshape(x, [-1, n_input_x])
# Split to get a list of 'n_steps' tensors of shape (batch_size, n_hidden)
# This input shape is required by `rnn` function
x = tf.split(0, n_steps, x)
# Define a lstm cell with tensorflow
lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True, activation=tf.nn.relu)
# lstm_cell = rnn_cell.MultiRNNCell([lstm_cell] * 12, state_is_tuple=True)
# lstm_cell = rnn_cell.DropoutWrapper(lstm_cell, output_keep_prob=0.8)
outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32)
# Linear activation, using rnn inner loop last output
# pdb.set_trace()
output = []
for i in xrange(396):
output.append(tf.matmul(outputs[i], lstm_weights[i]) + lstm_biases[i])
return output
cnn_weights = {
# 5x5 conv, 1 input, 32 outputs
'wc1' : tf.Variable(tf.random_normal([5, 5, 1, 32])),
# 5x5 conv, 32 inputs, 64 outputs
'wc2' : tf.Variable(tf.random_normal([5, 5, 32, 64])),
# 5x5 conv, 32 inputs, 64 outputs
'wc3' : tf.Variable(tf.random_normal([5, 5, 64, 128])),
'wdc1' : tf.Variable(tf.random_normal([2, 2, 64, 128])),
'wdc2' : tf.Variable(tf.random_normal([2, 2, 32, 64])),
'wdc3' : tf.Variable(tf.random_normal([2, 2, 1, 32])),
}
cnn_biases = {
'bc1': tf.Variable(tf.random_normal([32])),
'bc2': tf.Variable(tf.random_normal([64])),
'bc3': tf.Variable(tf.random_normal([128])),
'bdc1': tf.Variable(tf.random_normal([64])),
'bdc2': tf.Variable(tf.random_normal([32])),
'bdc3': tf.Variable(tf.random_normal([1])),
}
lstm_weights = {}
lstm_biases = {}
for i in xrange(396):
lstm_weights[i] = tf.Variable(tf.random_normal([n_hidden, n_output]))
lstm_biases[i] = tf.Variable(tf.random_normal([n_output]))
# Construct model
# with tf.name_scope("net") as scope:
pred = net(x, cnn_weights, cnn_biases, keep_prob)
# pdb.set_trace()
pred = tf.pack(pred)
pred = tf.transpose(pred, [1,0,2])
pred = tf.reshape(pred, [-1, n_input_x * n_input_y])
with tf.name_scope("opt") as scope:
# cost = tf.reduce_sum(tf.square(y-pred))
cost = tf.reduce_sum(tf.pow((pred-y),2)) / (2*batch_size)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Evaluate model
with tf.name_scope("acc") as scope:
# accuracy is the difference between prediction and ground truth matrices
correct_pred = tf.equal(0,tf.cast(tf.sub(cost,y), tf.int32))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Initializing the variables
init = tf.initialize_all_variables()
saver = tf.train.Saver()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
summary = tf.train.SummaryWriter('/tmp/logdir/', sess.graph) #initialize graph for tensorboard
step = 1
# Import data
data = scroll_data.read_data('/home/kendall/Desktop/')
# Keep training until reach max iterations
while step * batch_size < training_iters:
batch_x, batch_y = data.train.next_batch(batch_size)
# Run optimization op (backprop)
# pdb.set_trace()
batch_x = batch_x.reshape((batch_size, n_input_x, n_input_y))
batch_y = batch_y.reshape(batch_size, n_input_x * n_input_y)
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
step = step + 1
if step % display_step == 0:
batch_y = batch_y.reshape(batch_size, n_input_x * n_input_y)
loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
y: batch_y})
# Make prediction
im = Image.open('/home/kendall/Desktop/cropped/temp data0001.tif')
batch_x = np.array(im)
batch_x = batch_x.reshape((1, n_input_x, n_input_y))
batch_x = batch_x.astype(float)
prediction = sess.run(pred, feed_dict={x: batch_x})
prediction = prediction.reshape((1, n_input_x * n_input_y))
prediction = tf.nn.softmax(prediction)
prediction = prediction.eval()
prediction = prediction.reshape((n_input_x, n_input_y))
# my_accuracy = accuracy_custom(temp_arr1,batch_y[0,:,:,0])
#
# print "Step = " + str(step) + " | Accuracy = " + str(my_accuracy)
print "Step = " + str(step) + " | Accuracy = " + str(acc)
# csv_file = "CNN-LSTM-reg/CNNLSTMreg-step-" + str(step) + "-accuracy-" + str(my_accuracy) + ".csv"
csv_file = "CNN-LSTM-reg/CNNLSTMreg-step-" + str(step) + "-accuracy-" + str(acc) + ".csv"
np.savetxt(csv_file, prediction, delimiter=",")
</code></pre>
| 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 initializations already provided in TensorFlow <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/contrib.layers.html#initializers" rel="nofollow">here</a> (as a contribution), feel free to use them.</p>
| 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:</p>
<pre><code>Button Id:'ctl00_contentPlaceHolderConteudo_BuscaNomeEmpresa1_btnTodas'
from selenium import webdriver
import time
driver = webdriver.Firefox(executable_path='')
driver.implicitly_wait(12)
driver.get("http://www.bmfbovespa.com.br/pt_br/produtos/listados-a-vista-e-derivativos/renda-variavel/empresas-listadas.htm")
driver.find_element_by_id("ctl00_contentPlaceHolderConteudo_BuscaNomeEmpresa1_btnTodas")
</code></pre>
<p>Error message: </p>
<blockquote>
<p>NoSuchElementException: Unable to locate element:
{"method":"id","selector":"ctl00_contentPlaceHolderConteudo_BuscaNomeEmpresa1_btnTodas"}</p>
</blockquote>
<p>In fact, the element is present in the browser html </p>
<p><a href="http://i.stack.imgur.com/ZBASn.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZBASn.png" alt="https"></a></p>
<p>I read the related topics but I didn't get a solution.</p>
<p>So, what I need to do in order to click that button and get the data list after?</p>
<p>Thanks so much!</p>
| 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 finding this button as below :-</p>
<pre><code>driver = webdriver.Firefox(executable_path='')
driver.implicitly_wait(12)
driver.switch_to_frame("bvmf_iframe")
driver.get("http://www.bmfbovespa.com.br/pt_br/produtos/listados-a-vista-e-derivativos/renda-variavel/empresas-listadas.htm")
driver.find_element_by_id("ctl00_contentPlaceHolderConteudo_BuscaNomeEmpresa1_btnTodas")
</code></pre>
| 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:</p>
<pre><code>Button Id:'ctl00_contentPlaceHolderConteudo_BuscaNomeEmpresa1_btnTodas'
from selenium import webdriver
import time
driver = webdriver.Firefox(executable_path='')
driver.implicitly_wait(12)
driver.get("http://www.bmfbovespa.com.br/pt_br/produtos/listados-a-vista-e-derivativos/renda-variavel/empresas-listadas.htm")
driver.find_element_by_id("ctl00_contentPlaceHolderConteudo_BuscaNomeEmpresa1_btnTodas")
</code></pre>
<p>Error message: </p>
<blockquote>
<p>NoSuchElementException: Unable to locate element:
{"method":"id","selector":"ctl00_contentPlaceHolderConteudo_BuscaNomeEmpresa1_btnTodas"}</p>
</blockquote>
<p>In fact, the element is present in the browser html </p>
<p><a href="http://i.stack.imgur.com/ZBASn.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZBASn.png" alt="https"></a></p>
<p>I read the related topics but I didn't get a solution.</p>
<p>So, what I need to do in order to click that button and get the data list after?</p>
<p>Thanks so much!</p>
| 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_contentPlaceHolderConteudo_BuscaNomeEmpresa1_btnTodas")
</code></pre>
| 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 error: </p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "c:\python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "c:\python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "C:\Python27\Scripts\pip2.exe\__main__.py", line 5, in <module>
File "c:\python27\lib\site-packages\pip\__init__.py", line 13, in <module>
from pip.commands import commands, get_similar_commands, get_summaries
File "c:\python27\lib\site-packages\pip\commands\__init__.py", line 6, in <module>
from pip.commands.bundle import BundleCommand
File "c:\python27\lib\site-packages\pip\commands\bundle.py", line 5, in <module>
from pip.commands.install import InstallCommand
File "c:\python27\lib\site-packages\pip\commands\install.py", line 5, in <module>
from pip.req import InstallRequirement, RequirementSet, parse_requirements
File "c:\python27\lib\site-packages\pip\req\__init__.py", line 3, in <module>
from .req_install import InstallRequirement
File "c:\python27\lib\site-packages\pip\req\req_install.py", line 20, in <module>
import pip.wheel
File "c:\python27\lib\site-packages\pip\wheel.py", line 27, in <module>
from pip.download import path_to_url, unpack_url
ImportError: cannot import name unpack_url
</code></pre>
<p>I also try this: <code>python2.7 -m pip install scikit-learn</code> or <code>python27 -m pip install scikit-learn</code>
and I get this error:</p>
<pre class="lang-none prettyprint-override"><code>python2.7 : The term 'python2.7' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try agai
At line:1 char:1
+ python2.7 -m pip install scikit-learn
+ ~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (python2.7:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code></pre>
<p>I do have python 2.7 on <code>C:\Python27</code>.<br>
What to do?</p>
| 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> <name virtualenv>
</code></pre>
<p>To run it...</p>
<pre><code>workon <name virtualenv>
</code></pre>
| 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 error: </p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "c:\python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "c:\python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "C:\Python27\Scripts\pip2.exe\__main__.py", line 5, in <module>
File "c:\python27\lib\site-packages\pip\__init__.py", line 13, in <module>
from pip.commands import commands, get_similar_commands, get_summaries
File "c:\python27\lib\site-packages\pip\commands\__init__.py", line 6, in <module>
from pip.commands.bundle import BundleCommand
File "c:\python27\lib\site-packages\pip\commands\bundle.py", line 5, in <module>
from pip.commands.install import InstallCommand
File "c:\python27\lib\site-packages\pip\commands\install.py", line 5, in <module>
from pip.req import InstallRequirement, RequirementSet, parse_requirements
File "c:\python27\lib\site-packages\pip\req\__init__.py", line 3, in <module>
from .req_install import InstallRequirement
File "c:\python27\lib\site-packages\pip\req\req_install.py", line 20, in <module>
import pip.wheel
File "c:\python27\lib\site-packages\pip\wheel.py", line 27, in <module>
from pip.download import path_to_url, unpack_url
ImportError: cannot import name unpack_url
</code></pre>
<p>I also try this: <code>python2.7 -m pip install scikit-learn</code> or <code>python27 -m pip install scikit-learn</code>
and I get this error:</p>
<pre class="lang-none prettyprint-override"><code>python2.7 : The term 'python2.7' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try agai
At line:1 char:1
+ python2.7 -m pip install scikit-learn
+ ~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (python2.7:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code></pre>
<p>I do have python 2.7 on <code>C:\Python27</code>.<br>
What to do?</p>
| 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 error: </p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "c:\python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "c:\python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "C:\Python27\Scripts\pip2.exe\__main__.py", line 5, in <module>
File "c:\python27\lib\site-packages\pip\__init__.py", line 13, in <module>
from pip.commands import commands, get_similar_commands, get_summaries
File "c:\python27\lib\site-packages\pip\commands\__init__.py", line 6, in <module>
from pip.commands.bundle import BundleCommand
File "c:\python27\lib\site-packages\pip\commands\bundle.py", line 5, in <module>
from pip.commands.install import InstallCommand
File "c:\python27\lib\site-packages\pip\commands\install.py", line 5, in <module>
from pip.req import InstallRequirement, RequirementSet, parse_requirements
File "c:\python27\lib\site-packages\pip\req\__init__.py", line 3, in <module>
from .req_install import InstallRequirement
File "c:\python27\lib\site-packages\pip\req\req_install.py", line 20, in <module>
import pip.wheel
File "c:\python27\lib\site-packages\pip\wheel.py", line 27, in <module>
from pip.download import path_to_url, unpack_url
ImportError: cannot import name unpack_url
</code></pre>
<p>I also try this: <code>python2.7 -m pip install scikit-learn</code> or <code>python27 -m pip install scikit-learn</code>
and I get this error:</p>
<pre class="lang-none prettyprint-override"><code>python2.7 : The term 'python2.7' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try agai
At line:1 char:1
+ python2.7 -m pip install scikit-learn
+ ~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (python2.7:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code></pre>
<p>I do have python 2.7 on <code>C:\Python27</code>.<br>
What to do?</p>
| 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 -E -m pip install scikit-learn for v2.7
</code></p>
| 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 importing or call the Person class?</p>
| 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. This is done to align protein sequences, but I am seeing no way of doing this</p>
| -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 you mention.</p>
<pre><code>>>> import re
>>> s = 'MVMGLGVLLLVFVLGLGLTPPTLAQDNSRYTHFLTQHYDAKPQGRDDRYCESIMRRRGLT'
>>> matches = re.findall("M[A-Z]{3}V", s)
>>> for match in matches:
... print match
...
MGLGV
</code></pre>
| 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.</p>
| 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 dictionary value lists into integers?</p>
<p>So far this is what I have:</p>
<pre><code>import csv
reader = csv.reader(open('filename.csv'))
dictname = {}
for row in reader:
key = row[0]
if key in dictname:
pass
dictname[key] = row[1:]
print dictname
</code></pre>
| 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 dictionary value lists into integers?</p>
<p>So far this is what I have:</p>
<pre><code>import csv
reader = csv.reader(open('filename.csv'))
dictname = {}
for row in reader:
key = row[0]
if key in dictname:
pass
dictname[key] = row[1:]
print dictname
</code></pre>
| 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>
<pre><code>df = pd.read_csv('filename.csv',converters={'yourintegercolumn':int})
</code></pre>
| 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 dictionary value lists into integers?</p>
<p>So far this is what I have:</p>
<pre><code>import csv
reader = csv.reader(open('filename.csv'))
dictname = {}
for row in reader:
key = row[0]
if key in dictname:
pass
dictname[key] = row[1:]
print dictname
</code></pre>
| 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.</p>
<p>Note that the <code>if key in dictname: pass</code> block doesn't do anything. If there are duplicate keys in your data, you have three options:</p>
<p>1) Overwrite the existing key's data with the new row that has the identical key value (this is what is currently happening).</p>
<p>2) Only use the first occurrence of the key row. In this case, change <code>pass</code> to <code>continue</code>.</p>
<p>3) Try to aggregate the data. This is more complicated and beyond the scope of your original question, so I will leave it to you to figure out or post a new question covering this scope.</p>
<pre><code>def convert_to_numeric(value):
if isinstance(i, (str, unicode)):
try:
result = float(value)
except:
pass # Returns result on next line.
return result
for row in reader:
key = row[0]
if key in dictname:
pass # This doesn't do anything. Use `continue` to avoid overwriting.
dictname[key] = [convert_to_numeric(i) for i in row[1:]]
</code></pre>
| 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/OpenGLContext/scenegraph/polygontessellator.py" rel="nofollow">http://www.math.uiuc.edu/~gfrancis/illimath/windows/aszgard_mini/pylibs/OpenGLContext/scenegraph/polygontessellator.py</a></p>
<p>But I don't understand how to use it. Can anyone give me a clear example? </p>
<p>It have to use pyopengl as it has to integrate with another project (pygame etc won't work)</p>
<p>Alternatively, is there a way of buidling a trimesh from a line array?</p>
| 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 the sample code that renders a concave polygon with two holes (another potential limitation of raw OpenGL without GLU) that does not have any of the custom classes I typically use and utilizes the (slow and terrible) immediate mode for simplicity. The triangulate function contains the relevant code for creating a gluTesselator.</p>
<pre><code>from OpenGL.GLU import *
from OpenGL.GL import *
from pygame.locals import *
import pygame
import sys
def triangulate(polygon, holes=[]):
"""
Returns a list of triangles.
Uses the GLU Tesselator functions!
"""
vertices = []
def edgeFlagCallback(param1, param2): pass
def beginCallback(param=None):
vertices = []
def vertexCallback(vertex, otherData=None):
vertices.append(vertex[:2])
def combineCallback(vertex, neighbors, neighborWeights, out=None):
out = vertex
return out
def endCallback(data=None): pass
tess = gluNewTess()
gluTessProperty(tess, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_ODD)
gluTessCallback(tess, GLU_TESS_EDGE_FLAG_DATA, edgeFlagCallback)#forces triangulation of polygons (i.e. GL_TRIANGLES) rather than returning triangle fans or strips
gluTessCallback(tess, GLU_TESS_BEGIN, beginCallback)
gluTessCallback(tess, GLU_TESS_VERTEX, vertexCallback)
gluTessCallback(tess, GLU_TESS_COMBINE, combineCallback)
gluTessCallback(tess, GLU_TESS_END, endCallback)
gluTessBeginPolygon(tess, 0)
#first handle the main polygon
gluTessBeginContour(tess)
for point in polygon:
point3d = (point[0], point[1], 0)
gluTessVertex(tess, point3d, point3d)
gluTessEndContour(tess)
#then handle each of the holes, if applicable
if holes != []:
for hole in holes:
gluTessBeginContour(tess)
for point in hole:
point3d = (point[0], point[1], 0)
gluTessVertex(tess, point3d, point3d)
gluTessEndContour(tess)
gluTessEndPolygon(tess)
gluDeleteTess(tess)
return vertices
if __name__ == "__main__":
width, height = 550, 400
pygame.init()
pygame.display.set_mode((width, height), DOUBLEBUF|OPENGL)
pygame.display.set_caption("Tesselation Demo")
clock = pygame.time.Clock()
glClear(GL_COLOR_BUFFER_BIT)
glClear(GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, height, 0, -1, 1)#flipped so top-left = (0, 0)!
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
#define the polygon and some holes
polygon = [(0, 0), (550, 0), (550, 400), (275, 200), (0, 400)]
hole1 = [(10, 10), (10, 100), (100, 100), (100, 10)]
hole2 = [(300, 50), (350, 100), (400, 50), (350, 200)]
holes = [hole1, hole2]
vertices = triangulate(polygon, holes=holes)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
glColor(1, 0, 0)
glBegin(GL_TRIANGLES)
for vertex in vertices:
glVertex(*vertex)
glEnd()
pygame.display.flip()
clock.tick_busy_loop(60)
</code></pre>
<p>The output of the above code should look like <a href="http://i.stack.imgur.com/yOhll.png" rel="nofollow">this</a> (I don't have enough reputation to include the image directly).</p>
<p>Also, as a side note, you can use pygame with pyopengl as the code sample above shows. However, I personally prefer to use pysdl2 to provide the window for my application rather than pygame, which is based on the older sdl 1.2 and seems abandoned. I only use pygame in the above sample as it is more concise to work with in a demo.</p>
| 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, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
</code></pre>
<p>The above code will create a user profile for each new created user. </p>
<p>But how to create the user profile for each existing user <strong>automatically</strong>?</p>
<p>Thanks</p>
| 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 anyway, no one in the real world will add new data to their existing profiles if not forced or gamified into it :) )</p>
| -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, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
</code></pre>
<p>The above code will create a user profile for each new created user. </p>
<p>But how to create the user profile for each existing user <strong>automatically</strong>?</p>
<p>Thanks</p>
| 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=None
if not kwargs['created']:
try:
profile=kwargs['instance'].get_profile()
if len(sync_profile_field(kwargs['instance'],profile)):
profile.save()
execpt ObjectDoesNotExist:
pass
if not profile:
profile=created_profile_for_new_user(kwargs['instance'])
if not kwargs['created'] and sender==get_user_profile_model():
kwargs['instance'].user.save()
</code></pre>
<p>to connect signal use:</p>
<pre><code>post_save.connect(post_save_create_or_update_profile)
</code></pre>
| 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, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
</code></pre>
<p>The above code will create a user profile for each new created user. </p>
<p>But how to create the user profile for each existing user <strong>automatically</strong>?</p>
<p>Thanks</p>
| 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">data migration</a> if you wish, or run the code in the shell.</p>
| 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 search type. By working with individual <em>tweet id</em> I am able to get the username and from that username I can get the <em>user id</em>. But this manual work for each tweet is too lenghty. Can't there be a way to get directly the <em>user id</em> from the <em>tweet id</em>.</p>
<p>I am using python with tweepy library. </p>
<p>code for search with tweepy.
<code>
public_tweets = api.search(q="TheGhantas", lang ="en", count = 200)
</code>
<code>
public_tweets.id_str
</code>
is returning me the <em>tweet id</em> and this is helping me to get the tweet username. And from that username, I am getting the <em>user id</em>.
Can there be a simple way to get directly the <em>user id</em> from <em>tweet ids</em> if I have a file with <em>tweet ids</em>?</p>
| 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:</p>
<pre><code>{
"created_at": "Wed Jun 06 20:07:10 +0000 2012",
"id_str": "210462857140252672",
"text": "Along with our new #Twitterbird, we've also updated our Display Guidelines ^JC",
"id": 210462857140252672,
"user": {
"name": "Twitter API",
"id_str": "6253282",
"statuses_count": 3333,
"screen_name": "twitterapi"
},
}
</code></pre>
<p>Depending on how you're getting the JSON, it's as simple as going <code>tweet->user->screen_name</code></p>
| 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 way to replace the <code>NaN</code>s with some other value, say, <code>-np.inf</code>? Of course, one way to do it is simply to specify it as data:</p>
<pre><code>df = pd.DataFrame(data=np.ones((2,2))*(-np.inf), index=list('AB'), columns=list('CD'))
</code></pre>
<p>Perhaps there a more succinct way?</p>
| 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/generated/pandas.DataFrame.html#pandas.DataFrame" rel="nofollow">docs</a> show that <code>data</code> param can accept constants (scalar values) as well as array-like structures and dicts.</p>
| 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']
['StudentA','94']
etc...
</code></pre>
| 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']
['StudentA','94']
etc...
</code></pre>
| 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']
['StudentA','94']
etc...
</code></pre>
| 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']
['StudentA','94']
etc...
</code></pre>
| 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 = [['studentA', 90, 90],['studentB', 78, 40]]
print to_dict(l)
>>> {'studentB': [78, 40], 'studentA': [90, 90]}
for key, value in d.iteritems():
for i in value:
print key, i
>>> studentB 78
>>> studentB 40
>>> studentA 90
>>> studentA 90
</code></pre>
| 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']
['StudentA','94']
etc...
</code></pre>
| 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 list comprehension:</p>
<pre><code>>>> [(k, w) for k, v in d.items() for w in v]
[('StudentA', '80'), ('StudentA', '94'), ('StudentA', '93'), ('StudentB', '93'), ('StudentB', '94')]
</code></pre>
| 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</code> contains class C1 and C2. In <code>A/__init__.py</code>, it adds all the class names of A and its sub packages into <code>__all__</code>. </p>
<p>Now, I want to print out all package names as well as their contained class names, e.g. </p>
<blockquote>
<p>A contains A1, A2, B contains B1, B2, C contains C1, C2</p>
</blockquote>
<p>So given the absolute path of package A, e.g. 'xx/yy/A', how can I print the above line?</p>
<blockquote>
<p><strong>My question is not about how to retrieve file path of a package.</strong></p>
</blockquote>
| 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</em> way to know. You could figure it out by looking at what the <a href="https://docs.python.org/3/reference/import.html" rel="nofollow">import mechanism does</a> and following that to find a folder/file named <code>A</code>.</p>
<blockquote>
<p>I only know the absolute folder path of this package.</p>
</blockquote>
<p>But that makes it sound like you already know the location of the package on disk and you want to import it, even though it's not installed <a href="https://packaging.python.org/distributing/" rel="nofollow">as a package</a>. You <em>can</em> do something like that, but you shouldn't.</p>
| 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</code> contains class C1 and C2. In <code>A/__init__.py</code>, it adds all the class names of A and its sub packages into <code>__all__</code>. </p>
<p>Now, I want to print out all package names as well as their contained class names, e.g. </p>
<blockquote>
<p>A contains A1, A2, B contains B1, B2, C contains C1, C2</p>
</blockquote>
<p>So given the absolute path of package A, e.g. 'xx/yy/A', how can I print the above line?</p>
<blockquote>
<p><strong>My question is not about how to retrieve file path of a package.</strong></p>
</blockquote>
| 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 each imported module. </li>
</ol>
<p>I don't there is any nice way to import a module based on it's absolute path. The import process works by importing paths which are either relative to the existing module, or relative to an entry in sys.path. An option might be to force add the root of your package into sys.path - and for every file you find work out the dotted module name for the module.</p>
| 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 number:</p>
<pre><code>for i in range(10):
my_string = my_string.replace(str(i)+" ",str(i))
</code></pre>
<p>But this isn't a smart and efficient solution. Any thoughts?</p>
| 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 number:</p>
<pre><code>for i in range(10):
my_string = my_string.replace(str(i)+" ",str(i))
</code></pre>
<p>But this isn't a smart and efficient solution. Any thoughts?</p>
| 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 and slower:</p>
<pre><code>>>> timeit(lambda: re.sub('(?<=\d) (?=\d)', '', my_string))
1.991465161754789
>>> timeit(lambda: re.sub('(\d) (\d)', '$1$2', my_string))
1.82666541270698
</code></pre>
| 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)):
star.append(data[i].values()[10])
attributes = []
for i in range(len(data)):
attributes.append(data[i].values()[12])
def flatten_dict(dd, separator=' ', prefix=''):
return { prefix + separator + k if prefix else k : v
for kk, vv in dd.items()
for k, v in flatten_dict(vv, separator, kk).items()
} if isinstance(dd, dict) else { prefix : dd }
flatten_attr = list(flatten_dict(attributes[i], separator = ' ', prefix = '') for i in range(len(attributes)))
from sklearn.feature_extraction import DictVectorizer
v = DictVectorizer(sparse = False)
X = v.fit_transform(flatten_attr)
from sklearn.feature_extraction.text import TfidfTransformer
Transformer = TfidfTransformer()
A = Transformer.fit_transform(X)
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import train_test_split
from sklearn.neighbors import KNeighborsRegressor
from sklearn.cross_validation import KFold
F = KNeighborsRegressor(n_neighbors = 27)
Ffit = F.fit(A, star)
Fpred = F.predict(A)
Score = F.score(A, star)
print(Score)
</code></pre>
<p>My json file looks like this - </p>
<pre><code>{"business_id": "vcNAWiLM4dR7D2nwwJ7nCA", "full_address": "4840 E Indian School Rd\nSte 101\nPhoenix, AZ 85018", "hours": {"Tuesday": {"close": "17:00", "open": "08:00"}, "Friday": {"close": "17:00", "open": "08:00"}, "Monday": {"close": "17:00", "open": "08:00"}, "Wednesday": {"close": "17:00", "open": "08:00"}, "Thursday": {"close": "17:00", "open": "08:00"}}, "open": true, "categories": ["Doctors", "Health & Medical"], "city": "Phoenix", "review_count": 7, "name": "Eric Goldberg, MD", "neighborhoods": [], "longitude": -111.98375799999999, "state": "AZ", "stars": 3.5, "latitude": 33.499313000000001, "attributes": {"By Appointment Only": true}, "type": "business"}
{"business_id": "JwUE5GmEO-sH1FuwJgKBlQ", "full_address": "6162 US Highway 51\nDe Forest, WI 53532", "hours": {}, "open": true, "categories": ["Restaurants"], "city": "De Forest", "review_count": 26, "name": "Pine Cone Restaurant", "neighborhoods": [], "longitude": -89.335843999999994, "state": "WI", "stars": 4.0, "latitude": 43.238892999999997, "attributes": {"Take-out": true, "Good For": {"dessert": false, "latenight": false, "lunch": true, "dinner": false, "breakfast": false, "brunch": false}, "Caters": false, "Noise Level": "average", "Takes Reservations": false, "Delivery": false, "Ambience": {"romantic": false, "intimate": false, "touristy": false, "hipster": false, "divey": false, "classy": false, "trendy": false, "upscale": false, "casual": false}, "Parking": {"garage": false, "street": false, "validated": false, "lot": true, "valet": false}, "Has TV": true, "Outdoor Seating": false, "Attire": "casual", "Alcohol": "none", "Waiter Service": true, "Accepts Credit Cards": true, "Good for Kids": true, "Good For Groups": true, "Price Range": 1}, "type": "business"}
$ls -l yelp_data.json
</code></pre>
<p>shows the file size is 33524921</p>
<p>The worse I could do is to extract the needed data in a different file and import it to this program?
What would be good to improve this program to make it run more efficiently? Thank you!!</p>
| 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="https://docs.python.org/3/library/stdtypes.html#list" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#list</a></p>
<p>Also in Python 3, indexing dict values no longer work, you will end up with:</p>
<pre><code> star.append(data[i].values()[10])
TypeError: 'dict_values' object does not support indexing
</code></pre>
<p>Since items in <code>data</code> are json dicts, you may want to search for attributes by name instead of relying on attribute index:</p>
<pre><code>for item in data:
star.append(item['thekeyyourelookingfor'])
</code></pre>
<p>And then make it single-line:</p>
<pre><code>star = [item['thekeyyourelookingfor'] for item in data]
</code></pre>
<p><strong>EDIT</strong>: actually since <code>json.loads</code> reads the JSON string into a dictionary, the order or attributes is arbitrary, so when you access them by index you will very likely end up with a different attribute than the one you're looking for. Here you want read <code>stars</code> I guess. <strong>I'd even guess that is why your code fails, since you give sklearn input he is not expecting.</strong></p>
| 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.customContextMenuRequested.connect(self.shotsPopUp)
</code></pre>
<p>A user has requested the menu appear on right mouse press (as opposed to mouse release), then they can select a menu item, which is triggered on release (marking menu style).</p>
<p>Is this possible? </p>
| 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__(parent)
self.listWidget = QtGui.QListWidget(self)
self.listWidget.setObjectName('listWidget')
self.pushButton = QtGui.QPushButton(self)
self.pushButton.setGeometry(QtCore.QRect(20, 220, 101, 23))
self.pushButton.setObjectName('pushButton')
self.pushButton.setText('Add')
self.verticalLayout = QtGui.QVBoxLayout(self)
self.verticalLayout.setObjectName ('verticalLayout')
self.verticalLayout.addWidget(self.listWidget)
self.verticalLayout.addWidget(self.pushButton)
#Right click menu
self.listWidget.setContextMenuPolicy (QtCore.Qt.CustomContextMenu)
self.listWidget.customContextMenuRequested.connect (self.rightClickFunction)
self.action = QtGui.QAction (self)
self.action.setObjectName('action')
self.action.setText ('Open')
self.action1 = QtGui.QAction (self)
self.action1.setObjectName('action1')
self.action1.setText ('Test')
self.customMenu = QtGui.QMenu('Menu', self.listWidget)
self.customMenu.addAction (self.action)
self.customMenu.addAction (self.action1)
#self.customMenu.addAction (QtGui.QIcon(''), 'Open', (self.oepnFunction))
#self.customMenu.addAction (QtGui.QIcon(''), 'Test', (self.testFunction))
self.pushButton.clicked.connect (self.addItem)
self.action.triggered.connect (self.oepnFunction)
self.action1.triggered.connect (self.testFunction)
#void changed ()
#void hovered ()
#void toggled (bool)
#void triggered (bool = 0)
def addItem (self) :
count = int (self.listWidget.count ())
self.listWidget.addItem (str(count+1) + '_')
def rightClickFunction (self, event) :
index = self.listWidget.indexAt (event)
if not index.isValid():
return
item = self.listWidget.indexAt(event)
self.customMenu.popup (QtGui.QCursor.pos())
def oepnFunction (self) :
print 'hai............open'
def testFunction (self) :
print 'hai............test'
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())
</code></pre>
| 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 with MULTILINE). This seems to match any character (newlines also) but not sure of any eventual side effects. Don't want to have it match an integer or something and give me malformed data in the end.
Any info on this would be great.</p>
<p>What i really need though, is some assistance in making this example code work. I only need to fetch the numbers from the data.</p>
<p>I used re.fullmatch when i only needed one specific match in a previous case and not entirely sure which function i should use now by the way (finditer, findall, search etc.).</p>
<p>Thank you for any and all help :)</p>
<pre><code>data = """http://store.steampowered.com/app/254060/
http://www.store.steampowered.com/app/254061/
https://www.store.steampowered.com/app/254062
store.steampowered.com/app/254063
254064"""
regPattern = '^\s*(?:https?:\/\/)?(?:www\.)?(?:store\.steampowered\.com\/app\/)?([0-9]+)\/?\s*$'
evaluateData = re.search(regPattern, data, re.DOTALL | re.MULTILINE)
if evaluateString2 is not None:
print('do stuff')
else:
print('found no match')
</code></pre>
| 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 with MULTILINE). This seems to match any character (newlines also) but not sure of any eventual side effects. Don't want to have it match an integer or something and give me malformed data in the end.
Any info on this would be great.</p>
<p>What i really need though, is some assistance in making this example code work. I only need to fetch the numbers from the data.</p>
<p>I used re.fullmatch when i only needed one specific match in a previous case and not entirely sure which function i should use now by the way (finditer, findall, search etc.).</p>
<p>Thank you for any and all help :)</p>
<pre><code>data = """http://store.steampowered.com/app/254060/
http://www.store.steampowered.com/app/254061/
https://www.store.steampowered.com/app/254062
store.steampowered.com/app/254063
254064"""
regPattern = '^\s*(?:https?:\/\/)?(?:www\.)?(?:store\.steampowered\.com\/app\/)?([0-9]+)\/?\s*$'
evaluateData = re.search(regPattern, data, re.DOTALL | re.MULTILINE)
if evaluateString2 is not None:
print('do stuff')
else:
print('found no match')
</code></pre>
| 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\n254064"
re.findall(p, test_str)
</code></pre>
<p><a href="https://regex101.com/r/rC9rI0/1" rel="nofollow">https://regex101.com/r/rC9rI0/1</a></p>
<p>this gives <code>[u'254060', u'254061', u'254062', u'254063', u'254064']</code>.</p>
<p>Are you trying to return those specific integers?</p>
| 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 with MULTILINE). This seems to match any character (newlines also) but not sure of any eventual side effects. Don't want to have it match an integer or something and give me malformed data in the end.
Any info on this would be great.</p>
<p>What i really need though, is some assistance in making this example code work. I only need to fetch the numbers from the data.</p>
<p>I used re.fullmatch when i only needed one specific match in a previous case and not entirely sure which function i should use now by the way (finditer, findall, search etc.).</p>
<p>Thank you for any and all help :)</p>
<pre><code>data = """http://store.steampowered.com/app/254060/
http://www.store.steampowered.com/app/254061/
https://www.store.steampowered.com/app/254062
store.steampowered.com/app/254063
254064"""
regPattern = '^\s*(?:https?:\/\/)?(?:www\.)?(?:store\.steampowered\.com\/app\/)?([0-9]+)\/?\s*$'
evaluateData = re.search(regPattern, data, re.DOTALL | re.MULTILINE)
if evaluateString2 is not None:
print('do stuff')
else:
print('found no match')
</code></pre>
| 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 python script to verify the data coming from the arduino:</p>
<pre><code>import serial
sp = serial.Serial(
port="/dev/ttyAMA0",
baudrate=9600,
timeout=0.1
)
while True:
i = sp.read()
print i.encode("hex")
</code></pre>
<p>But the data coming out is corrupt / wrong about x times out of n times.</p>
<p>A good packet looks like
A0
2
1
4F
50
45
4E
B7
1B
80</p>
<p>Bad packets which is most of the time:
13
0a
7a
41
15
39
dd
1b
80
00</p>
<p>Also the test script works fine when using a USB to UART connected to the rs485 tranceiver instead of the internal uart.</p>
<p>Suggestions on what I am doing wrong?</p>
| 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)
borrower = Borrower.query.filter_by(full_name=full_name).first()
if request.method == 'POST' and 'photo' in request.files:
profile_pic = photos.save(request.files['photo'])
borrower.profile_pic = profile_pic
db.session.add(borrower)
db.session.commit()
return render_template('employees/borrower.html', borrower=borrower)
@employees.route('/uploaded_profile_pic/<filename>')
@login_required
def uploaded_profile_pic(filename):
if not current_user.is_employee:
abort(403)
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
</code></pre>
<p>My template file is as follows:</p>
<pre><code> {% if borrower.profile_pic %}
<img src="{{ url_for('employees.uploaded_profile_pic', filename = borrower.profile_pic)}}" />
{% else %}
<form action="{{url_for('employees.upload', full_name=borrower.full_name)}}" method="POST" enctype="multipart/form-data">
<input type="file" name="photo"><br /><br />
<input type="submit" value="Upload">
</form>
{% endif %}
</code></pre>
<p>The problem is i keep getting a broken image on the template.</p>
| 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.profile_pic = profile_pic</code> which will return the image path when accessed as <code>{{ borrower.profile_pic }}</code>.</p>
<pre><code><img src="{{ borrower.profile_pic }}">
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
</code></pre>
| 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: " + (str(i)).split("/")[-1]
print "Image Size " + str(len(iab))
print "Image Data: " + str(iab) + "\n"
pca = RandomizedPCA(n_components=2)
X = pca.fit_transform(iab)
Xy = pca.transform(X)
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X, Xy.ravel())
def aip(img):
a = cv2.imread(img)
b = cv2.resize(a, (500, 500))
tivb = []
r = flatten_image(b)
tivb.append(r)
o = np.array(tivb)
l = trueArray(o)
print "Test Image: " + (str(img)).split("/")[-1]
print "Test Image Size " + str(len(l))
print "Test Image Data: " + str(l) + "\n"
return l
testIm = aip(sys.argv[2])
b = pca.fit_transform(testIm)
print "KNN Prediction: " + str(knn.predict(b))
</code></pre>
<p>And while it <em>functioned</em> perfectly, it had an error: it gave me the exact same value regardless of the image used:</p>
<pre><code>Image: 150119131035-green-bay-seattle-nfl-1024x576.jpg
Image Size 750000
Image Data: [255 242 242 ..., 148 204 191]
Test Image: agun.jpg
Test Image Size 750000
Test Image Data: [216 255 253 ..., 205 225 242]
KNN Prediction: [-255.]
</code></pre>
<p>and </p>
<pre><code>Image: 150119131035-green-bay-seattle-nfl-1024x576.jpg
Image Size 750000
Image Data: [255 242 242 ..., 148 204 191]
Test Image: bliss.jpg
Test Image Size 750000
Test Image Data: [243 240 232 ..., 13 69 48]
KNN Prediction: [-255.]
</code></pre>
<p>The KNN prediction is always 255, no matter the image used. After investigation further, A found that the problem was my PCA: For some reason, it was taking an array with 750000 values and returning an array with only one:</p>
<pre><code>pca = RandomizedPCA(n_components=2)
X = pca.fit_transform(iab)
Xy = pca.transform(X)
print "Iab: " + str(iab)
print "Iab Type: " + str(type(iab))
print "Iab length: " + str(len(iab))
print "X Type: " + str(type(X))
print "X length: " + str(len(X))
print "X: " + str(X)
print "Xy Type: " + str(type(Xy))
print "Xy Length: " + str(len(X))
print "Xy: " + str(Xy)
</code></pre>
<p>gives this:</p>
<pre><code>Image: 150119131035-green-bay-seattle-nfl-1024x576.jpg
Image Size 750000
Image Data: [255 242 242 ..., 148 204 191]
Iab: [255 242 242 ..., 148 204 191]
Iab Type: <type 'numpy.ndarray'>
Iab length: 750000
X Type: <type 'numpy.ndarray'>
X length: 1
X: [[ 0.]]
Xy Type: <type 'numpy.ndarray'>
Xy Length: 1
Xy: [[-255.]]
</code></pre>
<p>My question is why? X and Xy should both have hundreds of values, not just one. The tutorial I followed didn't have an explanation, and the documentation only says that there needs to be the same array format for both the transform and the fit_transform. How should I be approaching this?</p>
| 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 should solve your issue.</p>
| 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: " + (str(i)).split("/")[-1]
print "Image Size " + str(len(iab))
print "Image Data: " + str(iab) + "\n"
pca = RandomizedPCA(n_components=2)
X = pca.fit_transform(iab)
Xy = pca.transform(X)
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X, Xy.ravel())
def aip(img):
a = cv2.imread(img)
b = cv2.resize(a, (500, 500))
tivb = []
r = flatten_image(b)
tivb.append(r)
o = np.array(tivb)
l = trueArray(o)
print "Test Image: " + (str(img)).split("/")[-1]
print "Test Image Size " + str(len(l))
print "Test Image Data: " + str(l) + "\n"
return l
testIm = aip(sys.argv[2])
b = pca.fit_transform(testIm)
print "KNN Prediction: " + str(knn.predict(b))
</code></pre>
<p>And while it <em>functioned</em> perfectly, it had an error: it gave me the exact same value regardless of the image used:</p>
<pre><code>Image: 150119131035-green-bay-seattle-nfl-1024x576.jpg
Image Size 750000
Image Data: [255 242 242 ..., 148 204 191]
Test Image: agun.jpg
Test Image Size 750000
Test Image Data: [216 255 253 ..., 205 225 242]
KNN Prediction: [-255.]
</code></pre>
<p>and </p>
<pre><code>Image: 150119131035-green-bay-seattle-nfl-1024x576.jpg
Image Size 750000
Image Data: [255 242 242 ..., 148 204 191]
Test Image: bliss.jpg
Test Image Size 750000
Test Image Data: [243 240 232 ..., 13 69 48]
KNN Prediction: [-255.]
</code></pre>
<p>The KNN prediction is always 255, no matter the image used. After investigation further, A found that the problem was my PCA: For some reason, it was taking an array with 750000 values and returning an array with only one:</p>
<pre><code>pca = RandomizedPCA(n_components=2)
X = pca.fit_transform(iab)
Xy = pca.transform(X)
print "Iab: " + str(iab)
print "Iab Type: " + str(type(iab))
print "Iab length: " + str(len(iab))
print "X Type: " + str(type(X))
print "X length: " + str(len(X))
print "X: " + str(X)
print "Xy Type: " + str(type(Xy))
print "Xy Length: " + str(len(X))
print "Xy: " + str(Xy)
</code></pre>
<p>gives this:</p>
<pre><code>Image: 150119131035-green-bay-seattle-nfl-1024x576.jpg
Image Size 750000
Image Data: [255 242 242 ..., 148 204 191]
Iab: [255 242 242 ..., 148 204 191]
Iab Type: <type 'numpy.ndarray'>
Iab length: 750000
X Type: <type 'numpy.ndarray'>
X length: 1
X: [[ 0.]]
Xy Type: <type 'numpy.ndarray'>
Xy Length: 1
Xy: [[-255.]]
</code></pre>
<p>My question is why? X and Xy should both have hundreds of values, not just one. The tutorial I followed didn't have an explanation, and the documentation only says that there needs to be the same array format for both the transform and the fit_transform. How should I be approaching this?</p>
| 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 iteration overwrites the <code>iab</code>
array.</li>
<li>Even if you saved the two arrays separately, as say <code>iab[0]</code> and <code>iab[1]</code>, you will need to perform PCA on both and use both images represented along the transformed axes. You need to decide what to use to learn the transformation though. </li>
</ol>
<p>Here is sample code:</p>
<pre><code># First initialize the PCA with desired components
pca = RandomizedPCA(n_components=2)
# Next you need to fit data to learn the transformations
pca.fit(np.vstack(iab[0].shape(1, len(iab[0]), iab[1].shape(1, len(iab[1])))
# Finally you apply this learned transformation on input data
X[0] = pca.transform(iab[0])
X[1] = pca.transform(iab[1])
</code></pre>
<p>You basically learn PCA on a matrix. The rows represent each image. What you want to be doing is trying to identify which pixels in the image best describe the image. For this you need to input many images, and find which pixels differentiate between them better than others. In your way of using the fit, you simply input 100s of values in a 1D list, which effectively means, you had one value representing each image, and you had 100s of images.</p>
<p>Also in your case, you combined <code>fit()</code> and <code>transform()</code>, which is a valid use case, if only you understand what it represents. You missed transformation of the second image, regardless. </p>
<p>If you want to know more about how PCA works you can read this <a href="http://stackoverflow.com/a/22986100/3919475">answer</a>. </p>
<p>Finally, you cannot learn a KNN classifier on 1 training sample and 1 testing sample! Learning algorithms are meant to learn from a population of input. </p>
<p>All you seem to need is basic distance between the two. You need to pick a distance metric. If you choose to use Euclidean distance (also called the L2 norm), then here is the code for it:</p>
<pre><code>dist = numpy.linalg.norm(X[0]-X[1])
</code></pre>
<p>You can also do this instead:</p>
<pre><code>from scipy.spatial import distance
dist = distance.euclidean(X[0], X[1])
</code></pre>
<p>In any case, there is no meaning in transforming the transformed data again, as you are doing with <code>Xy = pca.transform(X)</code>. That doesn't give you a target. </p>
<p>You can only apply classification such as KNN when you have say, 100 images, where 50 show a "tree" and the remaining 50 show a "car". Once you train the model, you can predict if a new image is of a tree or a car. </p>
| 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 4.905
91-100%
f 12.447
l 8.522
</code></pre>
<p>and say I want to produce a barplot where I have the columns as categories on the x axis and, for each category, two bars, one for <code>f</code> and one for <code>l</code>, so to make comparisons.</p>
<p><strong>How to do this in order to avoid the bars being stacked?</strong></p>
<p>My attempt produces stacked bars and an offset in terms of x labels:</p>
<pre><code>x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
labels = ['0-10%','11-20%','21-30%','31-40%','41-50%','51-60%','61-70%','71-80%','81-90%','91-100%']
row1 = df.iloc[0]
row1.plot(kind='bar',title='Binned comparison', color='r',stacked=False)
row2 = df.iloc[1]
row2.plot(kind='bar',title='Binned comparison', color='k',stacked=False)
plt.xticks(x,labels, rotation='horizontal',fontsize=8)
</code></pre>
| 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_d', 'Type D'),
)
obj_type = models.CharField(choices=OBJ_TYPES, default='type_a')
class GenericChild(Base):
# obj_type defaults to type_a
pass
class TypeDChild(Base)
# Want obj_type to default to type_d
# This causes error (local field clashes...)
obj_type = models.CharField(choices=OBJ_TYPES, default='type_d')
</code></pre>
| 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.CharField(choices=OBJ_TYPES, default='type_a')
# Make sure you do this, always always always set your base classes to abstract
class Meta:
abstract = True
class GenericChild(Base):
# obj_type defaults to type_a
pass
class TypeDChild(Base)
# Want obj_type to default to type_d
# This causes error (local field clashes...)
# obj_type = models.CharField(choices=OBJ_TYPES, default='type_d')
pass
TypeDChild._meta.get_field('obj_type').default = 'type_d'
</code></pre>
<p>As you can see, you have to update the default after the class definition. Keep in mind, this may or may not work with future versions of Django, as they update the way model introspection works every few releases.</p>
| 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.PIPE,
stderr=subprocess.PIPE)
result = process.stdout.readlines()
if not result:
print "Im an error"
err = process.stderr.readlines()
print('ERROR: {}'.format(err))
else:
print "I'm a success"
print(result)
</code></pre>
<p>When I run this I receive the following output in my terminal:</p>
<pre><code>dredbounds-computer: documents$ python terminal_test.py
Im an error
ERROR: ['sudo: sorry, you must have a tty to run sudo\n']
</code></pre>
<p>I've tried multiple things but I keep getting that error "sudo: sorry, you must have a tty to run sudo". It works fine if I just do it through the terminal manually, but I need to automate this. I read that a workaround might be to use '-t' or '-tt' in my ssh call, but I haven't been able to implement this successfully in subprocess yet (terminal just hangs for me). Anyone know how I can fix my code, or work around this issue? Ideally I'd like to ssh, then switch to the sudo user, and then run a file from there (I just put ls for testing purposes). </p>
| 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, HOST),
'-p', PORT, CMD],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
process.stdin.write("password\r\n")
</code></pre>
<p>Keep in mind, though, that the <code>ls</code> doesn't run until <em>after</em> the shell started by <code>su</code> exits. You should either log into the machine as <code>ec2-user</code> directly (if possible), or just use <code>sudo</code> to run whatever command you want without going through <code>su</code> first.</p>
| 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.PIPE,
stderr=subprocess.PIPE)
result = process.stdout.readlines()
if not result:
print "Im an error"
err = process.stderr.readlines()
print('ERROR: {}'.format(err))
else:
print "I'm a success"
print(result)
</code></pre>
<p>When I run this I receive the following output in my terminal:</p>
<pre><code>dredbounds-computer: documents$ python terminal_test.py
Im an error
ERROR: ['sudo: sorry, you must have a tty to run sudo\n']
</code></pre>
<p>I've tried multiple things but I keep getting that error "sudo: sorry, you must have a tty to run sudo". It works fine if I just do it through the terminal manually, but I need to automate this. I read that a workaround might be to use '-t' or '-tt' in my ssh call, but I haven't been able to implement this successfully in subprocess yet (terminal just hangs for me). Anyone know how I can fix my code, or work around this issue? Ideally I'd like to ssh, then switch to the sudo user, and then run a file from there (I just put ls for testing purposes). </p>
| 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 <code>ec2-user</code> without entering a password.</p>
<p>This assumes you change your command to look like this, which seems more reasonable to me:</p>
<pre><code>CMD = 'sudo -u ec2-user ls'
</code></pre>
| 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-forward. The reindex part is a bit tricky, on the other hand, at least for me. </p>
<p>If I use the DataFrame.reindex() method, it will only erase all the entries from the dataframe. I have tried to do it manually, by using .loc() to create new 'NaN' entries between each consecutive months, but this method overwrites the entries I already have. </p>
<p>Any clue how to do it? Thanks! </p>
| 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.resample('W').interpolate()
</code></pre>
<p><a href="http://i.stack.imgur.com/t0gmL.png" rel="nofollow"><img src="http://i.stack.imgur.com/t0gmL.png" alt="enter image description here"></a></p>
<hr>
<h3>Replicable code</h3>
<pre><code>from StringIO import StringIO
import pandas as pd
text = """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"""
df = pd.read_csv(StringIO(text), decimal=',', delim_whitespace=True)
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.resample('W').interpolate()
</code></pre>
| 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, and dict. Upon class creation, the callable
is used instead of the built-in <code>type()</code>.</p>
<p>New in version 2.2.</p>
</blockquote>
<p>However, <a href="http://www.cafepy.com/article/python_types_and_objects/ch02s05.html">this article</a> argues:</p>
<blockquote>
<p><strong>Q</strong>: Wow! Can I use any type object as the <code>__metaclass__</code>?</p>
<p><strong>A</strong>: No. It must be a subclass of the type of the base object. ...</p>
</blockquote>
<p>So I did an experiment on my own:</p>
<pre><code>class metacls(list): # <--- subclassing list, rather than type
def __new__(mcs, name, bases, dict):
dict['foo'] = 'metacls was here'
return type.__new__(mcs, name, bases, dict)
class cls(object):
__metaclass__ = metacls
pass
</code></pre>
<p>This gives me:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 6, in <module>
class cls(object):
File "test.py", line 4, in __new__
return type.__new__(mcs, name, bases, dict)
TypeError: Error when calling the metaclass bases
type.__new__(metacls): metacls is not a subtype of type
</code></pre>
<p>So is the document really wrong?</p>
| 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)
</code></pre>
<p>This one just returns the result of <code>type()</code> (not <code>type.__new__()</code>), yet it is <em>just a callable</em>. The return value is used <em>as the class</em>. You could really return anything:</p>
<pre><code>>>> class Foo(object):
... __metaclass__ = lambda *args: []
...
>>> Foo
[]
</code></pre>
<p>Here the callable produced a list instance, so <code>Foo</code> is bound to a list. Not very useful, but <code>__metaclass__</code> is just called to produce <em>something</em>, and that something is used directly.</p>
<p>In your example, the first argument to <code>type.__new__()</code> is <em>not a type</em>, and it is <strong>that call</strong> that fails. <code>mcs</code> is bound to <code>list</code>, and not a (subclass of) <code>type</code>. <code>type.__new__()</code> is free to set such restrictions.</p>
<p>Now, because a metaclass is still tied to the class object (<code>type(ClassObj)</code> returns it) and it is used when resolving attribute look-ups on the class object (where the attribute is not available in the class MRO), it is usually a <em>honking good idea</em> to make it a subclass of <code>type</code>, because that gives you the right implementation of things like <code>__getattribute__</code>. It is for that reason that <code>type.__new__()</code> make a restriction on what can be passed in as the first argument; it is that first argument that <code>type()</code> attaches to the class object returned.</p>
| 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/1M</p>
<pre><code>for data in user_list:
q = """ insert into users(id,name,address,password)
Values({id},{name},{address},{password})
""".format(id=data['id'],name=data['name'],address=data['address'],password=data['password'])
db.command(q)
</code></pre>
<p>I think it would be a whole lot faster if i run for example 8 concurrent threads inserting 8 at a time instead of single thread doing single insert</p>
| 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 from Python using the pyorient library:</p>
<p><a href="https://github.com/mogui/pyorient#execute-orientdb-sql-batch" rel="nofollow">https://github.com/mogui/pyorient#execute-orientdb-sql-batch</a></p>
<p>To insert data in parallel you will need to create multiple connections,
one for each thread.</p>
| 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'][i]['Pokemon']['Type1'][13:]
pokemon_type_two = json['Items'][i]['Pokemon']['Type2'][13:] if 'Type2' in json['Items'][i]['Pokemon'] else ''
pokeD.update({pokemon_name: {'Type1' : pokemon_type_one, 'Type2' : pokemon_type_two }})
</code></pre>
| -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:]
pokeD.update({pokemon_name: {'Type1' : pokemon_type_one, 'Type2' : pokemon_type_two }})
else:
pokeD.update({pokemon_name: {'Type1' : pokemon_type_one})
</code></pre>
| 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]
[27 26]
[28 26]
[29 26]
[30 26]
[31 26]
[32 26]
[33 26]
[34 26]
[35 26]
[36 26]
[37 26]
[38 26]
[39 26]
[40 26]
[41 26]
[42 26]
[43 26]
[44 26]
[45 26]
[46 26]
[47 26]
[48 26]
[49 26]
[50 26]
[51 26]
[52 26]
[53 26]
[54 26]
[55 26]
[56 26]
[57 26]
[58 26]
[59 26]
[60 26]
[61 26]
[62 26]
[63 26]
[64 26]
[65 26]
[66 26]
[67 26]
[68 26]
[69 26]]
Y = [ 192770 14817993 1393537 437541 514014 412468 509393 172715
329806 425876 404031 524371 362817 692020 585431 446286
744061 458805 330027 495654 459060 734793 701697 663319
750496 525311 1045502 250641 500360 507594 456444 478666
431382 495689 458200 349161 538770 355879 535924 549858
611428 517146 239513 354071 342354 698360 467248 500903
625170 404462 1057368 564703 700988 1352634 727453 782708
1023673 1046348 1175588 698072 605187 684739 884551 1067267
728643 790098 580151 340890 299185]
</code></pre>
<p>I am trying to plot the result to see the regression line using</p>
<pre><code>regr = linear_model.LinearRegression()
regr.fit(X, Y)
plt.scatter(X[:,0], Y, color='black')
plt.plot(X[:,0], regr.predict(X), color='blue',
linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
</code></pre>
<p>The graph I get is
<a href="http://i.stack.imgur.com/K9rPA.png" rel="nofollow"><img src="http://i.stack.imgur.com/K9rPA.png" alt="enter image description here"></a></p>
<p>('Coefficients: \n', array([-34296.90306122, 0. ]))
Residual sum of squares: 1414631501323.43
Variance score: -17.94</p>
<p>I am trying to predict </p>
<pre><code>pred = regr.predict([[49, 26]])
print pred
</code></pre>
<p>something which is already there in the training data and the result is
[-19155.16326531]</p>
<p>whose actual value is 625170</p>
<p>What am i doing wrong ?</p>
<p>Please not the value of 26 is coming from a larger array, I have sliced that dat to a small portion so as to train and predict on 26, similarly the X[:,0] might not be continuous value its again coming from a larger array.
By array I mean numpy array</p>
| 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 = [26]*69
X = np.column_stack([x1, x2])
y = ''' 192770 14817993 1393537 437541 514014 412468 509393 172715
329806 425876 404031 524371 362817 692020 585431 446286
744061 458805 330027 495654 459060 734793 701697 663319
750496 525311 1045502 250641 500360 507594 456444 478666
431382 495689 458200 349161 538770 355879 535924 549858
611428 517146 239513 354071 342354 698360 467248 500903
625170 404462 1057368 564703 700988 1352634 727453 782708
1023673 1046348 1175588 698072 605187 684739 884551 1067267
728643 790098 580151 340890 299185'''
Y = np.array(map(int, y.split()))
regr = linear_model.LinearRegression()
regr.fit(X, Y)
plt.scatter(X[:,0], Y, color='black')
plt.plot(X[:,0], regr.predict(X), color='blue',
linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
print regr.predict([[49,26]])
# 611830.33589088
</code></pre>
| 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]
[27 26]
[28 26]
[29 26]
[30 26]
[31 26]
[32 26]
[33 26]
[34 26]
[35 26]
[36 26]
[37 26]
[38 26]
[39 26]
[40 26]
[41 26]
[42 26]
[43 26]
[44 26]
[45 26]
[46 26]
[47 26]
[48 26]
[49 26]
[50 26]
[51 26]
[52 26]
[53 26]
[54 26]
[55 26]
[56 26]
[57 26]
[58 26]
[59 26]
[60 26]
[61 26]
[62 26]
[63 26]
[64 26]
[65 26]
[66 26]
[67 26]
[68 26]
[69 26]]
Y = [ 192770 14817993 1393537 437541 514014 412468 509393 172715
329806 425876 404031 524371 362817 692020 585431 446286
744061 458805 330027 495654 459060 734793 701697 663319
750496 525311 1045502 250641 500360 507594 456444 478666
431382 495689 458200 349161 538770 355879 535924 549858
611428 517146 239513 354071 342354 698360 467248 500903
625170 404462 1057368 564703 700988 1352634 727453 782708
1023673 1046348 1175588 698072 605187 684739 884551 1067267
728643 790098 580151 340890 299185]
</code></pre>
<p>I am trying to plot the result to see the regression line using</p>
<pre><code>regr = linear_model.LinearRegression()
regr.fit(X, Y)
plt.scatter(X[:,0], Y, color='black')
plt.plot(X[:,0], regr.predict(X), color='blue',
linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
</code></pre>
<p>The graph I get is
<a href="http://i.stack.imgur.com/K9rPA.png" rel="nofollow"><img src="http://i.stack.imgur.com/K9rPA.png" alt="enter image description here"></a></p>
<p>('Coefficients: \n', array([-34296.90306122, 0. ]))
Residual sum of squares: 1414631501323.43
Variance score: -17.94</p>
<p>I am trying to predict </p>
<pre><code>pred = regr.predict([[49, 26]])
print pred
</code></pre>
<p>something which is already there in the training data and the result is
[-19155.16326531]</p>
<p>whose actual value is 625170</p>
<p>What am i doing wrong ?</p>
<p>Please not the value of 26 is coming from a larger array, I have sliced that dat to a small portion so as to train and predict on 26, similarly the X[:,0] might not be continuous value its again coming from a larger array.
By array I mean numpy array</p>
| 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, 14817993,1393537, 437541, 514014, 412468, 509393, 172715, 329806, 425876, 404031, 524371, 362817, 692020, 585431, 446286, 744061, 458805, 330027, 495654, 459060, 734793, 701697, 663319, 750496, 525311,1045502, 250641, 500360, 507594, 456444, 478666, 431382, 495689, 458200, 349161, 538770, 355879, 535924, 549858, 611428, 517146, 239513, 354071, 342354, 698360, 467248, 500903, 625170, 404462,1057368, 564703, 700988,1352634, 727453, 782708, 1023673,1046348,1175588, 698072, 605187, 684739, 884551,1067267, 728643, 790098, 580151, 340890, 299185]
# your code for regression
regr = linear_model.LinearRegression()
regr.fit(x, y)
# the correct coef is different from your findings
print regr.coef_
</code></pre>
<p>This returns a result: <code>array([-13139.72031421, 0. ])</code></p>
<p>When trying prediction: <code>regr.predict([[49, 26]])</code> returns <code>array([ 611830.33589088])</code>, which is close to the answer you expected. </p>
| 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-options" method = "post" action = "/prediction/results">
<!--the input fields-->
</form>
</code></pre>
<p><strong>Flask app.py</strong></p>
<pre><code>@app.route("/")
def main():
return render_template('index.html')
@app.route("/prediction/results", methods = ['POST'])
def predict():
input_aqi = float(request.form['aqi'])/272
input_pm2_5 = float(request.form['pm2_5'])/224
input_pm10 = float(request.form['pm10'])/283
input_so2 = float(request.form['so2'])/36
input_no2 = float(request.form['no2'])/110
input_co = float(request.form['co'])/1.83
input_o3 = float(request.form['o3'])/124
input_list = [[input_aqi,input_pm2_5,input_pm10,input_so2,input_no2,input_co,input_o3]]
output_acute_bronchitis = model_acute_bronchitis.predict(input_list)
output_asthma = model_asthma.predict(input_list)
output_asthmatic_bronchitis = model_asthmatic_bronchitis.predict(input_list)
output_aurti = model_aurti.predict(input_list)
output_bronchitis = model_bronchitis.predict(input_list)
output_pneumonia = model_pneumonia.predict(input_list)
d = collections.OrderedDict()
d['acute_bronchitis'] = output_acute_bronchitis[0]
d['asthma'] = output_asthma[0]
d['asthmatic_bronchitis'] = output_asthmatic_bronchitis[0]
d['aurti'] = output_aurti[0]
d['bronchitis'] = output_bronchitis[0]
d['pneumonia'] = output_pneumonia[0]
prediction = jsonify(d)
return prediction
</code></pre>
<p>Right now, I have managed to take in the user input and render the predicted results on the '/prediction/results' page. How can I get the results to show up on the '/' page? I tried to do this:</p>
<pre><code>@app.route("/", methods = ['POST','GET'])
def main():
if request.method == 'POST':
def predict():
#predict function that returns prediction
return render_template('index.html')
</code></pre>
<p>But I always get a <code>socket.error: [Errno 32] Broken pipe</code> error message. What should I do?</p>
| 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>
<pre><code>@app.route("/", methods = ['POST','GET'])
def main():
if request.method == 'POST':
pass
prediction = session['prediction']
return render_template('index.html', prediction=prediction)
</code></pre>
| 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 method as part of a pipeline: </p>
<pre><code> def clean(self):
HTTP_PATTERN = '^https?:\/\/.*[\r\n]*'
AT_PATTERN = '@\w+ ?'
# tke away links
self.tweets = [re.sub(HTTP_PATTERN, '', str(x), flags=re.MULTILINE) for x in self.tweets]
# take away @ signs
self.tweets = [re.sub(AT_PATTERN,'',str(x)) for x in self.tweets]
</code></pre>
<p>but when I call this:</p>
<pre><code>tweet = load_data('The_Donald.json')
block = twitter_block(tag='donald')
block.load(data=tweet)
block.clean()
block.print()
</code></pre>
<p>it returns the 1504 tweets that I loaded into the block object same as before, no cleaning links or anything. Although, actually it does remove @ signs... but this method, </p>
<pre><code>def smilecheck(self):
#save a tweet if there is a smiley there
smiley_pattern = '^(:\(|:\))+$'
for tweet in self.tweets:
if re.match(smiley_pattern, str(tweet)):
pass
else:
self.tweets.remove(tweet)
</code></pre>
<p>does not remove the tweets without smileys, returns 1504 tweets, the same as I put in... any help guys? im sure this is a problem with the way I am approaching objects </p>
| -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-search">python -- re.match vs re.search</a></p>
| 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
4 B 07/04/1999 4
</code></pre>
<p>For each group, I want to extend the data frame to include all the missing dates between the max and the min of the dates, and then interpolate the column value linearly. The result should look like this:</p>
<pre><code> ID date value
0 A 06/24/2014 4
1 A 06/25/2014 5
2 A 06/26/2014 6
3 A 06/27/2014 7
4 A 06/28/2014 8
5 A 06/29/2014 9
6 B 07/02/1999 2
7 B 07/03/1999 3
8 B 07/04/1999 4
</code></pre>
<p>My idea so far is as follows:</p>
<p>Set date as the index:</p>
<pre><code>df.date = pd.DatetimeIndex(df.date)
</code></pre>
<p>Group by ID and apply the following function:</p>
<pre><code>B = df1.groupby('ID').apply(lambda x: x.reindex(pd.date_range(x.date.min(),x.date.max()), fill_value=0) )
</code></pre>
<p>What would be the best approach for this?</p>
<p>thank you,</p>
| 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
1999-07-03 B 2
1999-07-04 B 4
</code></pre>
| 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
4 B 07/04/1999 4
</code></pre>
<p>For each group, I want to extend the data frame to include all the missing dates between the max and the min of the dates, and then interpolate the column value linearly. The result should look like this:</p>
<pre><code> ID date value
0 A 06/24/2014 4
1 A 06/25/2014 5
2 A 06/26/2014 6
3 A 06/27/2014 7
4 A 06/28/2014 8
5 A 06/29/2014 9
6 B 07/02/1999 2
7 B 07/03/1999 3
8 B 07/04/1999 4
</code></pre>
<p>My idea so far is as follows:</p>
<p>Set date as the index:</p>
<pre><code>df.date = pd.DatetimeIndex(df.date)
</code></pre>
<p>Group by ID and apply the following function:</p>
<pre><code>B = df1.groupby('ID').apply(lambda x: x.reindex(pd.date_range(x.date.min(),x.date.max()), fill_value=0) )
</code></pre>
<p>What would be the best approach for this?</p>
<p>thank you,</p>
| 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_datetime(df.date)
df.value = pd.to_numeric(df.value, 'coerce')
df = df.set_index('date')
</code></pre>
<h3>Solution</h3>
<pre><code>df.groupby('ID', group_keys=False).value \
.apply(lambda df: df.resample('D').interpolate()).reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/PJJ78.png" rel="nofollow"><img src="http://i.stack.imgur.com/PJJ78.png" alt="enter image description here"></a></p>
| 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 service on my Spot Instances that:</p>
<ol>
<li>Loops over long polling SQS Queues</li>
<li>If it gets a message, it pauses polling and works on the payload.</li>
<li>Working on the payload can take 5-50 minutes.</li>
<li>Working on the payload will involve spawning a threadpool of up to 50 threads to handle parallel uploading of files to S3, this is the majority of the time spent working on the payload.</li>
<li>Finally, remove the message from the queue, rinse, repeat.</li>
</ol>
<p>The work is idempotent, so if the same payload runs multiple times, I'm out the processing time/costs, but will not negatively impact the application workflow.</p>
<p>I'm searching for an elegant way to now also poll for the termination notice every five seconds in the background. As soon as the termination notice appears, I'd like to immediately release the message back to the SQS queue in order for another instance to pick it up as quickly as possible.</p>
<p>As a bonus, I'd like to shutdown the work, kill off the threadpool, and have the service enter a stasis state. If I terminate the service, supervisord will simply start it back up again.</p>
<p>Even bigger bonus! Is there not a python module available that simplifies this and just works?</p>
| 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. Eventually the polling thread will kick in <em>(about 10 seconds into execution as implemented)</em> and kill the whole thing.</p>
<p>To prevent the script from continuing to work after Supervisor restarts it, we would simply put a check at the beginning of the <code>__main__</code> and if the termination notice is there we sleep for 2.5 minutes, which is longer than that notice lasts before the instance is shutdown.</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
import threading
import Queue
import random
import time
import sys
import os
class Instance_Termination_Poll(threading.Thread):
"""
Sleep for 5 seconds and eventually pretend that we then recieve the
termination event
if requests.get("http://169.254.169.254/latest/meta-data/spot/termination-time").status_code == 200
"""
def run(self):
print("Polling for termination")
while True:
for i in range(30):
time.sleep(5)
if i==2:
print("Recieve Termination Poll!")
print("Pretend we returned the message to the queue.")
print("Now Kill the entire program.")
os._exit(1)
print("Well now, this is embarassing!")
class ThreadPool:
"""
Pool of threads consuming tasks from a queue
"""
def __init__(self, num_threads):
self.num_threads = num_threads
self.errors = Queue.Queue()
self.tasks = Queue.Queue(self.num_threads)
for _ in range(num_threads):
Worker(self.tasks, self.errors)
def add_task(self, func, *args, **kargs):
"""
Add a task to the queue
"""
self.tasks.put((func, args, kargs))
def wait_completion(self):
"""
Wait for completion of all the tasks in the queue
"""
try:
while True:
if self.tasks.empty() == False:
time.sleep(10)
else:
break
except KeyboardInterrupt:
print "Ctrl-c received! Kill it all with Prejudice..."
os._exit(1)
self.tasks.join()
class Worker(threading.Thread):
"""
Thread executing tasks from a given tasks queue
"""
def __init__(self, tasks, error_queue):
threading.Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.errors = error_queue
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try:
func(*args, **kargs)
except Exception, e:
print("Exception " + str(e))
error = {'exception': e}
self.errors.put(error)
self.tasks.task_done()
def do_work(n):
"""
Sleeps a random ammount of time, then creates a little CPU usage to
mimic some work taking place.
"""
for z in range(100):
time.sleep(random.randint(3,10))
print "Thread ID: {} working.".format(threading.current_thread())
for x in range(30000):
x*n
print "Thread ID: {} done, sleeping.".format(threading.current_thread())
if __name__ == '__main__':
num_threads = 30
# Start up the termination polling thread
term_poll = Instance_Termination_Poll()
term_poll.start()
# Create our threadpool
pool = ThreadPool(num_threads)
for y in range(num_threads*2):
pool.add_task(do_work, n=y)
# Wait for the threadpool to complete
pool.wait_completion()
</code></pre>
| 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/__init__.py", line 72, in <module>
from _qi import Application as _Application
ImportError: dlopen(/Users/zhangshirui/pynaoqi-python2.7-2.1.4.13-mac64/_qi.so, 2): Library not loaded: libboost_python.dylib
Referenced from: /Users/zhangshirui/pynaoqi-python2.7-2.1.4.13-mac64/_qi.so
Reason: unsafe use of relative rpath libboost_python.dylib in /Users/zhangshirui/pynaoqi-python2.7-2.1.4.13-mac64/_qi.so with restricted binary
</code></pre>
| 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.</p>
<p>Please refer to this to find out about disabling system integrity protection.</p>
<p><a href="http://www.macworld.com/article/2986118/security/how-to-modify-system-integrity-protection-in-el-capitan.html" rel="nofollow">http://www.macworld.com/article/2986118/security/how-to-modify-system-integrity-protection-in-el-capitan.html</a></p>
<p>That made it work.</p>
<p>Thanks,</p>
<p>Dinesh </p>
| 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'] KeyError: Set-1 "
</code></pre>
<p>I understand like Set-1 doesnt exit but that's not true. I hope someones can help me.</p>
<p>I create Set-1 :</p>
<hr>
<pre><code>mdb.models['Model-1'].parts['Part-1'].Set(faces= mdb.models['Model-1'].parts['Part-1'].faces.getSequenceFromMask(('[#1 ]', ), ), name='Set-1')
</code></pre>
<hr>
<p>And my code for getting to read the stresses is:</p>
<hr>
<pre><code>odb = openOdb( path='C:\Temp\Job-1.odb')
RegionTen = odb.rootAssembly.nodeSets['Set-1']
tamFrames = len(odb.steps['Step-1'].frames)
lastFrames = odb.steps['Step-1'].frames[tamFrames-1]
stress33 = lastFrame.fieldOutputs['S'].getSubset(position=ELEMENT_NODAL, region=RegionTen)
stress13 = lastFrame.fieldOutputs['CTSHR13'].getSubset(position=ELEMENT_NODAL, region=RegionTen)
stress23 = lastFrame.fieldOutputs['CTSHR23'].getSubset(position=ELEMENT_NODAL, region=RegionTen)
print(stress11, stress22, stress12)
</code></pre>
<hr>
| 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>
<pre><code>regionTen = odb.rootAssembly.instances['instanceName'].nodeSets['Set-1']
</code></pre>
<p>You can see the difference between these set types in Abaqus. Instance level node sets have a prefix - 'InstanceName.'. Notice a dot after an instance name.</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_correlation_coefficient#Weighted_correlation_coefficient" rel="nofollow">https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#Weighted_correlation_coefficient</a></p>
| 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 Covariance"""
return np.sum(w * (x - m(x, w)) * (y - m(y, w))) / np.sum(w)
def corr(x, y, w):
"""Weighted Correlation"""
return cov(x, y, w) / np.sqrt(cov(x, x, w) * cov(y, y, w))
</code></pre>
<p>I tried to make the functions above match the formulas in the wikipedia as closely as possible, but there are some potential simplifications and performance improvements. For example, as pointed out by @Alberto Garcia-Raboso, <code>m(x, w)</code> is really just <code>np.average(x, weights=w)</code>, so there's no need to actually write a function for it.</p>
<p>The functions are pretty bare-bones, just doing the calculations. You may want to consider forcing inputs to be arrays prior to doing the calculations, i.e. <code>x = np.asarray(x)</code>, as these functions will not work if lists are passed. Additional checks to verify all inputs have equal length, non-null values, etc. could also be implemented.</p>
<p>Example usage:</p>
<pre><code># Initialize a DataFrame.
np.random.seed([3,1415])
n = 10**6
df = pd.DataFrame({
'x': np.random.choice(3, size=n),
'y': np.random.choice(4, size=n),
'w': np.random.random(size=n)
})
# Compute the correlation.
r = corr(df['x'], df['y'], df['w'])
</code></pre>
<p>There's a discussion <a href="http://stats.stackexchange.com/q/94569">here</a> regarding the p-value. It doesn't look like there's a generic calculation, and it depends on how you're actually getting the weights.</p>
| 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>
subprocess.call(command_two.split(), shell=False) #writes the summary file
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
</code></pre>
<p>When walking through my program, it never gets to the program I want it to sfit4Layer0.py, it is getting stuck in subprocess but I am not sure why. Changing the shell=True doesn't do anything helpful either - I don't get these error messages but it does not execute my code properly. Any suggestions would be helpful. </p>
<p>My bash profile:</p>
<pre><code>PATH="~/bin:/usr/bin:${PATH}"
export PATH PYTHONPATH="/Users/nataliekille/Documents/sfit4/pbin/Layer0:/Users/nataliekille/Documents/sfit4/pbin/Layer1:/Users/nataliekille/Documents/sfit4/pbin/ModLib:/Users/nataliekille/Documents/sfit4/SpectralDB"
export PYTHONPATH
PATH=${PATH}:${PYTHONPATH}
export PATH
</code></pre>
| 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 the string must simply name the program to be executed without specifying any arguments."</p>
<p>So the kernel is compaining because there is not executable with the name <code>'sfit4Layer0.py -bv5 -fs'</code>. Should work if you replace the string with (for example) <code>'sfit4Layer0.py -bv5 -fs'.split()</code>, or <code>['sfit4Layer0.py', '-bv5', '-fs']</code>.</p>
| 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):
print(meteodata)
url = 'http://127.0.0.1:8080/api/meteo'
headers = {'Content-Type': 'application/json'}
resp = requests.post(url , data = json.dumps(meteodata), headers=headers)
print(resp)
ser = serial.Serial('/dev/cu.usbmodem1411', 9600)
while True:
json_string = ser.readline().decode("utf-8")
send_JSON_to_server(json_string)
</code></pre>
<p>And it get data perforated string from serial port and try to send it Flask app. On server side I have a code:</p>
<pre><code>@app.route('/api/meteo/', methods=['GET','POST'])
def save_meteo_data():
if request.method == 'POST':
if request.json:
json_dict = request.get_json()
save_meteo_data_to_db(json_dict)
return 200
else:
return render_template('test.html'), 999
</code></pre>
<p>And here I got a problem, it seems to me that request come to server as GET, at least if I left only POST in methods, I immediately get 405 response and no error in apache log. If I left it like this request send to server and return 999, which means that it was not accepted as POST. I know that 405 is usually connected to configuration or security issue, so you can see my virtual host configuration bellow. I use the same in different project and it is working.</p>
<pre><code>WSGIScriptAlias / /var/www/meteo/meteo.wsgi
DocumentRoot /var/www/meteo
<Directory /var/www/meteo>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</code></pre>
<p>I also want to provide example of JSON which I get from Arduino and response after requests.post, as you can see bellow.</p>
<pre><code>{"humidity":57.10,"temperature":28.10,"tempbyfeeling":29.27}
<Response [405]>
</code></pre>
| 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', methods=['GET','POST'])
</code></pre>
<p>One / need to be deleted thats all.</p>
| 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><code>ValueError: time data '47:37:00' does not match format '%H:%M:%S'
</code></pre>
<p>Is it possible there are more elements to my time stamps than I thought? Or that it's formatted in minutes/seconds/milliseconds? 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>
| 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><code>ValueError: time data '47:37:00' does not match format '%H:%M:%S'
</code></pre>
<p>Is it possible there are more elements to my time stamps than I thought? Or that it's formatted in minutes/seconds/milliseconds? 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>
| 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>And yes, when the %H is matched with 47, you get boom the error.</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>
<pre><code> <attribute dynamic="false" name="Multiset Column Chart with Error Bars " type="http://lamp.cfar.umd.edu/viperdata#bbox"/>
</code></pre>
<p>TO</p>
<pre><code><attribute dynamic="false" name="Column Chart " type="http://lamp.cfar.umd.edu/viperdata#bbox"/>
</code></pre>
<p>and </p>
<pre><code><attribute name="Multiset Column Chart with Error Bars "/>
</code></pre>
<p>TO</p>
<pre><code><attribute name="Column Chart "/>
</code></pre>
<p>So far I can access the element in the first code snipped as</p>
<pre><code>root=xmldoc.getroot()
print(root[0][0][11].attrib)
</code></pre>
<p>but it is not certain that this name "Multiset Column Chart with Error Bars " will always be at position [0][0][11]. </p>
<p>So, I am not sure how can I access those specific names and can change the value for the name as I showed above.</p>
<p>Any assistance will be appreciated. </p>
<h2>END NOTE</h2>
<p>I had to remove the link to the source xml file because this file is part of my research project.</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">
<attribute dynamic="false" name="Reflexive Bar Chart " type="http://lamp.cfar.umd.edu/viperdata#bbox"/>
</code></pre>
<p>and so on.</p>
<p>you can select the tag <code>attribute</code> and set the attribute for that tag like this:</p>
<pre><code>import xml.etree.ElementTree as ET
tree = ET.parse('contents.xml').getroot()
print tree.tag, tree.text
for child in tree[0][0]:
print child.set("name","bhansa")
print child.attrib #just to check whether changed or not
</code></pre>
<p>then write the changes in xml file </p>
<pre><code>tree.write("file_name")
</code></pre>
<p>Have a good reading <a href="https://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow">here</a> about xml and python</p>
| 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>
<pre><code> <attribute dynamic="false" name="Multiset Column Chart with Error Bars " type="http://lamp.cfar.umd.edu/viperdata#bbox"/>
</code></pre>
<p>TO</p>
<pre><code><attribute dynamic="false" name="Column Chart " type="http://lamp.cfar.umd.edu/viperdata#bbox"/>
</code></pre>
<p>and </p>
<pre><code><attribute name="Multiset Column Chart with Error Bars "/>
</code></pre>
<p>TO</p>
<pre><code><attribute name="Column Chart "/>
</code></pre>
<p>So far I can access the element in the first code snipped as</p>
<pre><code>root=xmldoc.getroot()
print(root[0][0][11].attrib)
</code></pre>
<p>but it is not certain that this name "Multiset Column Chart with Error Bars " will always be at position [0][0][11]. </p>
<p>So, I am not sure how can I access those specific names and can change the value for the name as I showed above.</p>
<p>Any assistance will be appreciated. </p>
<h2>END NOTE</h2>
<p>I had to remove the link to the source xml file because this file is part of my research project.</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")
print (child.attrib) #just to check whether changed or not
</code></pre>
| 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>
<pre><code>from flask_cors import cross_origin
@app.route("/")
@cross_origin()
</code></pre>
<p>The above snippet enables CORS for all the domains. I want to restrict this to some specific list of domains. All I want to know how I can specify this list. Here is what I am trying to do:</p>
<pre><code>@cross_origin(["www.domain1.com, www.domain2.com"])
</code></pre>
| -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>The origin, or list of origins to allow requests from. The origin(s) may be regular expressions, case-sensitive strings, or else an asterisk
</code></p>
<p>So, here you need to give <code>list</code> of <code>string</code>. Like:</p>
<p><code>cross_origin(["http://www.domain1.com", "http://www.domain2.com"])
</code></p>
<p>Notice here that you were giving all domain in a single string. But you needed to provide a list. Also notice that you provide Fully Qualified Domain Name (FQDN) as per <a href="https://tools.ietf.org/html/rfc6454#section-7.1" rel="nofollow">RFC 6454</a> and <a href="https://www.w3.org/TR/cors/#access-control-allow-origin-response-header" rel="nofollow">W3C Recommendation</a>.</p>
<p>You can also do something like this:</p>
<p><code>cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
</code></p>
<p>Here we're allowing every path in our app which starts with <code>/api</code>. Depending on your requirement, you can define appropriate path here. Here you can also specify origins to a list of domains you want to enable CORS for.</p>
<p>Here is the link to the code I've written: <a href="https://github.com/Mozpacers/MozStar/" rel="nofollow">https://github.com/Mozpacers/MozStar/</a></p>
<p>CORS doesn't do anything special; you just need to reply to the request with a special header which says that <code>Access-Control-Allow-Origin</code> contains the domain request is coming from.</p>
<p>For pre-flight requests, you can see how you can reply with custom headers with Flask before_request and after_request decorators: <a href="https://github.com/CuriousLearner/TrackMyLinks/blob/master/src/server/views.py#L130" rel="nofollow">https://github.com/CuriousLearner/TrackMyLinks/blob/master/src/server/views.py#L130</a></p>
<p>I hope this helps!</p>
| 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 <module>
remote: setuptools.setup(**setup_params)
remote: File "/app/.heroku/python/lib/python2.7/distutils/core.py", line 151, in setup
remote: dist.run_commands()
remote: File "/app/.heroku/python/lib/python2.7/distutils/dist.py", line 953, in run_commands
remote: self.run_command(cmd)
remote: File "/app/.heroku/python/lib/python2.7/distutils/dist.py", line 972, in run_command
remote: cmd_obj.run()
remote: File "setuptools/command/egg_info.py", line 177, in run
remote: writer = ep.load(installer=installer)
remote: File "pkg_resources.py", line 2241, in load
remote: if require: self.require(env, installer)
remote: File "pkg_resources.py", line 2254, in require
remote: working_set.resolve(self.dist.requires(self.extras),env,installer)))
remote: File "pkg_resources.py", line 2471, in requires
remote: dm = self._dep_map
remote: File "pkg_resources.py", line 2682, in _dep_map
remote: self.__dep_map = self._compute_dependencies()
remote: File "pkg_resources.py", line 2699, in _compute_dependencies
remote: from _markerlib import compile as compile_marker
remote: ImportError: No module named _markerlib
</code></pre>
<p>I solved this problem in local after I installed a new env with --distribute, but the error persists on heroku. </p>
| 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 Pandas so that I can possibly guess where my error is? Here is the last bit of the error message.</p>
<pre><code>/users/xx/xxxx/pyenvs/xx/lib/python2.7/site-packages/pandas-0.16.2+xxx1-
py2.7-linux-x86_64.egg/pandas/sparse/series.py in get_values(self)
228 def get_values(self):
229 """ same as values """
--> 230 return self._data._values.to_dense().view()
231
232 @property
</code></pre>
| 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]:
SingleBlockManager
Items: RangeIndex(start=0, stop=3, step=1)
IntBlock: 3 dtype: int64
</code></pre>
| 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()
successful = run_program(path)
end = time.time()
runtime = end - start
</code></pre>
<p>where the <code>run_program</code> function just uses the <code>subprocess</code> module to run the C program:</p>
<pre><code>def run_program(path):
p = subprocess.Popen(path, shell=True, stdout=subprocess.PIPE)
p.communicate()[0]
if (p.returncode > 1):
return False
return True
</code></pre>
<p>However I've recently discovered that this measures elapsed time and not CPU time, i.e. this sort of measurement is sensitive to noise from the OS. Similar questions on SO suggest that the <code>timeit</code> module is is better for measuring CPU time, so I've adapted the run method as such:</p>
<pre><code>def run_program(path):
command = 'p = subprocess.Popen(\'time ' + path + '\', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE); out, err = p.communicate()'
result = timeit.Timer(command, setup='import subprocess').repeat(1, 10)
return numpy.median(result)
</code></pre>
<p>But from looking at the <code>timeit</code> documentation it seems that the <code>timeit</code> module is only meant for small snippets of python code passed in as a string. So I'm not sure if <code>timeit</code> is giving me accurate results for this computation. So my question is: Will <code>timeit</code> measure the CPU for every step of the process that it runs or will it only measure the CPU time for the actual python(i.e. the <code>subprocess</code> module) code to run? Is this an accurate way to benchmark a set of C programs?</p>
| 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()
successful = run_program(path)
end = time.time()
runtime = end - start
</code></pre>
<p>where the <code>run_program</code> function just uses the <code>subprocess</code> module to run the C program:</p>
<pre><code>def run_program(path):
p = subprocess.Popen(path, shell=True, stdout=subprocess.PIPE)
p.communicate()[0]
if (p.returncode > 1):
return False
return True
</code></pre>
<p>However I've recently discovered that this measures elapsed time and not CPU time, i.e. this sort of measurement is sensitive to noise from the OS. Similar questions on SO suggest that the <code>timeit</code> module is is better for measuring CPU time, so I've adapted the run method as such:</p>
<pre><code>def run_program(path):
command = 'p = subprocess.Popen(\'time ' + path + '\', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE); out, err = p.communicate()'
result = timeit.Timer(command, setup='import subprocess').repeat(1, 10)
return numpy.median(result)
</code></pre>
<p>But from looking at the <code>timeit</code> documentation it seems that the <code>timeit</code> module is only meant for small snippets of python code passed in as a string. So I'm not sure if <code>timeit</code> is giving me accurate results for this computation. So my question is: Will <code>timeit</code> measure the CPU for every step of the process that it runs or will it only measure the CPU time for the actual python(i.e. the <code>subprocess</code> module) code to run? Is this an accurate way to benchmark a set of C programs?</p>
| 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 types, that all have different number of rows for one table on some part of the page, whereas the rest of the rows in the other tables on the page are the same. I have tried showing the code in the <em>2nd blockcode</em>. </p>
<p><strong>How do I accomplish taking the type from the database in the start_requests, and sending it to parse?</strong></p>
<p><em>1st blockcode</em></p>
<pre><code># -*- coding: utf-8 -*-
from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapeInfo.items import infoItem
import pyodbc
class scrapeInfo(Spider):
name = "info"
allowed_domains = ["http://www.nevermind.com"]
start_urls = []
def start_requests(self):
#Get infoID and Type from database
self.conn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=dbname;UID=user;PWD=password')
self.cursor = self.conn.cursor()
self.cursor.execute("SELECT InfoID FROM dbo.infostage")
rows = self.cursor.fetchall()
for row in rows:
url = 'http://www.nevermind.com/info/'
yield self.make_requests_from_url(url+row[0])
def parse(self, response):
hxs = Selector(response)
infodata = hxs.xpath('div[2]/div[2]') # input item path
itemPool = []
InfoID = ''.join(response.url)
id = InfoID[29:len(InfoID)-1]
for info in infodata:
item = infoItem()
# Details
item['id'] = id #response.url
item['field'] = info.xpath('tr[1]/td[2]/p/b/text()').extract()
item['field2'] = info.xpath('tr[2]/td[2]/p/b/text()').extract()
item['field3'] = info.xpath('tr[3]/td[2]/p/b/text()').extract()
item['field4'] = info.xpath('tr[4]/td[2]/p/b/text()').extract()
item['field5'] = info.xpath('tr[5]/td[2]/p/b/text()').extract()
item['field6'] = info.xpath('tr[6]/td[2]/p/b/text()').extract()
itemPool.append(item)
yield item
pass
</code></pre>
<p><em>2nd blockcode</em> <br>
This does not work, but Im not sure how to get it working. Do I create a global list, a new function?</p>
<pre><code># -*- coding: utf-8 -*-
from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapeInfo.items import infoItem
import pyodbc
class scrapeInfo(Spider):
name = "info"
allowed_domains = ["http://www.nevermind.com"]
start_urls = []
def start_requests(self):
#Get infoID and Type from database
self.conn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=dbname;UID=user;PWD=password')
self.cursor = self.conn.cursor()
self.cursor.execute("SELECT InfoID, type FROM dbo.infostage")
rows = self.cursor.fetchall()
for row in rows:
url = 'http://www.nevermind.com/info/'
type = row[1] # how do I send this value to the parse function?
yield self.make_requests_from_url(url+row[0])
def parse(self, response):
hxs = Selector(response)
infodata = hxs.xpath('div[2]/div[2]') # input base path
itemPool = []
InfoID = ''.join(response.url)
id = InfoID[29:len(InfoID)-1]
for info in infodata:
item = infoItem()
# Details
item['id'] = id #response.url
# Here I need to implement a condition that comes from def start_requests(self).
# If condition meet then scrape the following fields else the next
if type = 'type1':
# This is where I would like to use it.
# I have 11 different types, that all have different number of rows for one table on some part of the page, whereas the rest of the rows in the other tables on the page are the same.
# Type 1
item['field'] = info.xpath('tr[1]/td[2]/p/b/text()').extract()
item['field2'] = info.xpath('tr[2]/td[2]/p/b/text()').extract()
item['field3'] = info.xpath('tr[3]/td[2]/p/b/text()').extract()
item['field4'] = info.xpath('tr[4]/td[2]/p/b/text()').extract()
item['field5'] = info.xpath('tr[5]/td[2]/p/b/text()').extract()
item['field6'] = info.xpath('tr[6]/td[2]/p/b/text()').extract()
else:
item['field2'] = info.xpath('tr[2]/td[2]/p/b/text()').extract()
item['field4'] = info.xpath('tr[4]/td[2]/p/b/text()').extract()
item['field6'] = info.xpath('tr[6]/td[2]/p/b/text()').extract()
itemPool.append(item)
yield item
pass
</code></pre>
<p><br>
Thank you all for your help and insight!</p>
| 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 request
</code></pre>
<p>In <code>parse</code> you can access <code>type</code> using <code>response.meta['type']</code></p>
| 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 ImageWChain Description
0 B001 123 XYZ B001 B001 Test1
1 B002 456 GDH B002 B002 Test2
2 B003 789 GFR B003 B003 Test3
</code></pre>
<p>and my expected output is: </p>
<pre><code> ItemNumber UPC Keyword ImageName ImageWChain Description Image
0 B001 123 XYZ B001 B001 Test1 B001_B001
1 B002 456 GDH B002 B002 Test2 B002_B002
2 B003 789 GFR B003 B003 Test3 B003_B003
</code></pre>
<p>This is what I have so far:</p>
<pre><code>import csv
import os
from os.path import splitext # splits name & extension from a file
import shutil # making a duplicate copy of a file
import logging
class Image:
def image_fix(self):
#open and read csv
with open('rosary.csv') as csvfile:
#create list for sku, old_imagename_column_1, old_imagename_column_1
#and renamed new_imagename
keyList = [] #for ItemNumber
itemList = [] #for ImageName
itemList1 = [] #for ImageWChain
renamedList = [] #for Renamed NEW_ImageName
spamreader = csv.reader(csvfile, delimiter=",")
#storing all the columns into list
for row in spamreader:
keyList.append(row[0])
itemList.append(row[3])
itemList1.append(row[4])
renamedList.append(row[6])
# processing for ImageName
for item in enumerate(itemList):
oldFileName = name
newFileName = '{}_{}{}'.format(name, keyList[item[0]])
# check if the image file existsin image folder for ImageName column
if (os.path.isfile(oldFileName)):
shutil.copy2(oldFileName, newFileName) #make a duplicate image of every itemname
renamedList[item[0]] = '{}_{}{}'.format(oldFileName, keyList[item[0]])
# write the final output in new csv
with open('rosary.csv','wb') as my_csv:
csvWriter = csv.writer(my_csv,delimiter=',')
for row in zip(keyList, itemList, itemList1, renamedList):
# printing row in order
print(row[0] + '\t' + '\t' + row[3] + '\t' + '\t' +
row[4] + '\t' + '\t' + row[6])
csvWriter.writerow(row)
if __name__=="__main__":
obj = Image()
obj.image_fix()
</code></pre>
| 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 B001 XYZ 123 B001_B001
1 1 Test2 B002 B002 B002 GDH 456 B002_B002
2 2 Test3 B003 B003 B003 GFR 789 B003_B003
</code></pre>
<p>To make a new image copy:</p>
<pre><code>for old_image, new_image in zip(df.ImageName, df.Image):
if (os.path.isfile(old_image)):
shutil.copy2(old_image, new_image)
</code></pre>
| 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 adjacent cell, in Column 2. </p>
<pre><code>import pandas
csvfile = pandas.read_csv('document1.csv')
#Convert everything to string for simplicity
csvfile['ID'] = csvfile['ID'].astype(str)
#Fill in all missing NaN
csvfile = csvfile.fillna('missing')
#looking for the row in which the ID '10099870.0' is in.
indexid = csvfile.loc[csvfile['ID'] == '10099870.0'].index
# Important part! I think this selects the column 2, row 'indexid' and replaces missing with 1.
csvfile['Column 2'][indexid].replace('missing', '1')
</code></pre>
<p>I know this is a simple question but thanks for all your help!</p>
<p>Mauricio</p>
| 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>Which I am running/compile on Python Shell, and so far with those two lines I am running it and not getting an issue, when I try to implement anything else to pull the data, I keep getting errors. </p>
<p>on topic but a separate thing</p>
<p>I also have this line of code to pull specific line from the SmartSheet,</p>
<pre><code>action = smartsheet.Sheets.get_sheet(SheetID, column_ids=COL_ID, row_numbers="2,4")
</code></pre>
<p>My question regarding this is, where do I find the Column ID, I know how to access the Sheet ID, but I cant access or find the Column ID on smartsheets, I dont know if i am overlooking it. Just looking to get off in the right direction, being the newbie I am, any help appreciated. </p>
<p><strong><em>EDIT</em></strong></p>
<pre><code>5183127460046724
Task Name
2931327646361476
Duration
7434927273731972
Start
</code></pre>
<p><strong><em>EDIT 2</em></strong></p>
<pre><code>Task Name
task1 text here
Duration
duration1 text here
Start
start1 example here
</code></pre>
| -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.
import smartsheet
# Instantiate smartsheet and specify access token value.
smartsheet = smartsheet.Smartsheet('ACCESS_TOKEN')
# Get all columns.
action = smartsheet.Sheets.get_columns(SHEET_ID, include_all=True)
columns = action.data
# For each column, print Id and Title.
for col in columns:
print(col.id)
print(col.title)
print('')
</code></pre>
<hr>
<h2>UPDATE #1</h2>
<p>Here's some sample code that shows how to access property values within a <strong>Get Sheet</strong> response.</p>
<pre><code># Get Sheet - but restrict results to just 2 rows (#2, #4) and a single column/cell (Id = COLUMN_ID)
action = smartsheet.Sheets.get_sheet(SHEET_ID, column_ids=COLUMN_ID, row_numbers="2,4")
# print info from row #2 (the first row in the "Get Sheet" response) for the single specified column (cell)
print('Row #: ' + str(action.rows[0].row_number))
print('Row ID: ' + str(action.rows[0].id))
print('Column ID: ' + str(action.columns[0].id))
print('Column Title: ' + action.columns[0].title)
print('Cell (display) value: ' + action.rows[0].cells[0].display_value)
print('')
# print info from row #4 (the second row in the "Get Sheet" response) for the single specified column (cell)
print('Row #: ' + str(action.rows[1].row_number))
print('Row ID: ' + str(action.rows[1].id))
print('Column ID: ' + str(action.columns[0].id))
print('Column Title: ' + action.columns[0].title)
print('Cell (display) value: ' + action.rows[1].cells[0].display_value)
print('')
</code></pre>
| 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 import SelectPercentile, f_classif
</code></pre>
<p>Read data</p>
<pre><code>data = loadtxt('running.txt')
label = loadtxt('walking.txt')
X = data
y = label
</code></pre>
<p>Define walking status as 0, running status as 1</p>
<pre><code>print('Class labels:', np.unique(y))
</code></pre>
<p>Random pick 50% data as test data and leave the rest as train data</p>
<pre><code>from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)
</code></pre>
<p>Use sklearn to select 50% features</p>
<pre><code>selector = SelectPercentile(f_classif, 50)
selector.fit(X_train, y_train)
X_train_transformed = selector.transform(X_train)
X_test_transformed = selector.transform(X_test)
</code></pre>
<p>Apply support vector machine algorithm</p>
<pre><code>clf = svm.SVC(kernel="rbf", C=1)
clf.fit(X_train_transformed, y_train)
</code></pre>
<p> </p>
<pre><code>SVC(C=1, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',max_iter=-1,probability=False, random_state=None, shrinking=True,tol=0.001, verbose=False)
</code></pre>
<p> </p>
<pre><code>pred=clf.predict(X_test_transformed)
print("Accuracy is %.4f and the f1-score is %.4f " %
(accuracy_score(pred, y_test), f1_score(y_test, pred)))
</code></pre>
<blockquote>
<p>Traceback (most recent call last): File "", line 1, in File "C:\Users\praym\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile execfile(filename, namespace) File "C:\Users\praym\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/praym/OneDrive/School/Information Structres/Assignment4.py", line 18, in
selector.fit(X_train, y_train)
File "C:\Users\praym\Anaconda3\lib\site-packages\sklearn\feature_selection\univariate_selection.py", line 322, in fit
X, y = check_X_y(X, y, ['csr', 'csc'])
File "C:\Users\praym\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 515, in check_X_y
y = column_or_1d(y, warn=True)
File "C:\Users\praym\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 551, in column_or_1d
raise ValueError("bad input shape {0}".format(shape))
ValueError: bad input shape (10, 90)</p>
</blockquote>
| 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 explain it in more simple terms here. </p>
<p>The error has a heading "Traceback", because that is what it is doing - tracing back the error. You can see in your python script that every line is some sort of an API call, whether it is <code>loadtxt</code> or <code>print</code> or <code>fit</code>. If an error occurred when you made the call to <code>loadtxt</code>, the Traceback shows you what went wrong exactly, inside the <code>loadtxt</code> call. That function may be calling other functions within the API, and hence you see a "trace". When you write more complicated Python code where you have many functions and classes, you might end up seeing functions that made calls to other functions, all written by you. Therefore, </p>
<ol>
<li>Always read the Traceback bottom up (it tells you in your output that the "most recent call is last"). You need to get the line number along with the name of the python file where the error occurred. </li>
</ol>
<p>The line number will take you to the point in code that actually caused the error. Usually, you only need the bottom 1 or 2 calls to solve general problems. If you wrote your own custom API, then the entire trace might become more useful. However, the file name and line number alone is not enough to effectively debug any program. </p>
<ol start="2">
<li>Next you need to understand what exactly the error is. In your case you see a <code>ValueError</code>. This generally means that the value of your variable does not match the variable type. However, the sentence following the exception type gives you more detail on what exactly caused this <code>ValueError</code>. </li>
</ol>
<p>For more details about each of the exception types and their meanings, read the documentation about <a href="https://docs.python.org/2/library/exceptions.html" rel="nofollow">built-in exceptions</a>. Further, you can understand more about how to handle such exceptions from the tutorial <a href="https://docs.python.org/2/tutorial/errors.html" rel="nofollow">here</a>.</p>
<ol start="3">
<li>Usually, knowing the line number of the bottom most call and the type of exception is enough for you to understand what you did wrong. However, if you are sure that your use of the variable in that line is correct, then you must delve deeper into the stack trace, and look for the call second from the bottom. For that you will again see a file name and a line number. </li>
</ol>
<p>By repeating these steps, you will be able to effectively debug your own programs. Note that debugging is not only a method to remove errors from your programs. It is the ability to step through your code and identify what each line is doing and comparing it to what they are supposed to be doing. It is the very foundation of what is called computer programming. If you do this right, you may still have questions to ask, but your questions will improve. That is when Stack Overflow comes in (note that the name of this website is by itself a play on the concept of stack trace). </p>
<hr>
<p>EDIT: In yor stack trace, your error is here:</p>
<p>File "C:/Users/praym/OneDrive/School/Information Structres/Assignment4.py", line 18, in selector.fit(X_train, y_train). </p>
<p>It appears that one or both of your input variables X_train and y_train aren't of the shape that is acceptable by that fit function. </p>
<hr>
<p>EDIT:
If you load the files the way you have, then you cannot get the right X_train and y_train variables. You seem to have two types of data, one for walking and one for running. They are both data. Each entry in the walking data should have a label 'walking' and each entry in the running data should have label 'running'. </p>
<p>Now, this is fundamental to data mining. You need to know what data and label means. </p>
| 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/negative-lookbehind" class="post-tag" title="show questions tagged 'negative-lookbehind'" rel="tag">negative-lookbehind</a> to see if I can return a Q&A that shows how to match numbers 1 or more times in a lookbehind.</p>
<p>I have HTML and I'm using BBEdit to search for:</p>
<pre><code><span class="foo">1.</span> bar
<span class="foo">10.</span> bar
</code></pre>
<p><code>(?<=<span class="foo">[0-9]\.<\/span>) bar</code> and <code>(?<=<span class="foo">\d\.<\/span>) bar</code> will find:</p>
<pre><code><span class="foo">1.</span> bar
</code></pre>
<p><code>(?<=<span class="foo">\d\d\.<\/span>) bar</code> and <code>(?<=<span class="foo">[0-9][0-9]\.<\/span>) bar</code> will find:</p>
<pre><code><span class="foo">10.</span> bar
</code></pre>
<p>However when I use <code>(?<=<span class="foo">[0-9]+\.<\/span>) bar</code> and <code>(?<=<span class="foo">\d{1,2}\.<\/span>) bar</code> I get an error in BBEdit and on <a href="https://regex101.com/" rel="nofollow">regex101</a>. Is it possible to find 1 or more numbers in a lookbehind with BBEdit? If it is not supported what is an alternative solution?</p>
| 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)
</code></pre>
<p>And using capturing group "bar", the former working better for replacing but not working in all regex engines.</p>
| 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("hello")
>>> y
['h', 'e', 'l', 'l', 'o']
>>> z = ["hello"]
>>> z
['hello']
</code></pre>
| -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("hello")
>>> y
['h', 'e', 'l', 'l', 'o']
>>> z = ["hello"]
>>> z
['hello']
</code></pre>
| -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("hello")
>>> y
['h', 'e', 'l', 'l', 'o']
>>> z = ["hello"]
>>> z
['hello']
</code></pre>
| -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 contrary, <code>[]</code> is an alternate constructor that constructs a list from the elements the comma-separated values that are provided, no additional actions are performed.</p>
<p>You could achieve a similar result with <code>[]</code> in Python 3 by unpacking the string inside the square brackets:</p>
<pre><code>s = "hello"
l = [*s]
print(l) # ['h', 'e', 'l', 'l', 'o']
</code></pre>
<p>In <strong>both</strong> Python versions, you can get the <em>same</em> result with a comprehension:</p>
<pre><code>l = [char for char in s]
</code></pre>
| 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("hello")
>>> y
['h', 'e', 'l', 'l', 'o']
>>> z = ["hello"]
>>> z
['hello']
</code></pre>
| -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 = ["hello"]
This is just a list with a single element (of type string) on it.</p>
| 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("hello")
>>> y
['h', 'e', 'l', 'l', 'o']
>>> z = ["hello"]
>>> z
['hello']
</code></pre>
| -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 construct <code>[]</code> you can use a comprehension:</p>
<pre><code>>>> z = [i for i in "hello"]
>>> z
['h', 'e', 'l', 'l', 'o']
</code></pre>
| 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("hello")
>>> y
['h', 'e', 'l', 'l', 'o']
>>> z = ["hello"]
>>> z
['hello']
</code></pre>
| -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 string equivalent of</p>
<pre><code>>>> list([1, 2, 3])
[1, 2, 3]
>>> [[1, 2, 3]]
[[1, 2, 3]]
</code></pre>
<p>Which is to say, in the second case you get a list containing a single iterable while in the first one you get a list made up of the individual elements of the iterable.</p>
| 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("hello")
>>> y
['h', 'e', 'l', 'l', 'o']
>>> z = ["hello"]
>>> z
['hello']
</code></pre>
| -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 giving me error:</p>
<blockquote>
<p>TypeError: 'str' object cannot be interpreted as an integer</p>
</blockquote>
<p>Desired output:</p>
<blockquote>
<p>there are two much person p, person q, person r.</p>
</blockquote>
<p>This is just an example, I want to run a for loop for 10,000 length list. </p>
| 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</p>
<pre><code>import re
new = ['p','q','r']
my_str = 'there are two much person a, person b, person c.'
old = ['a','b','c']
word=re.compile(r"\w*") # word characters
old_new=dict(zip(old,new))
ong=old_new.get
my_str=word.sub((lambda s:ong(s,s)),my_str)
print(my_str)
</code></pre>
<p>this also avoids the double replacement problem if an entry is in both old and new (not avoided in the shorter solution)</p>
| 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 giving me error:</p>
<blockquote>
<p>TypeError: 'str' object cannot be interpreted as an integer</p>
</blockquote>
<p>Desired output:</p>
<blockquote>
<p>there are two much person p, person q, person r.</p>
</blockquote>
<p>This is just an example, I want to run a for loop for 10,000 length list. </p>
| 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, only the first count occurrences are replaced.</p>
</blockquote>
<p>In your case, it is <code>my_str.replace(old[index], new[index])</code></p>
| 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 giving me error:</p>
<blockquote>
<p>TypeError: 'str' object cannot be interpreted as an integer</p>
</blockquote>
<p>Desired output:</p>
<blockquote>
<p>there are two much person p, person q, person r.</p>
</blockquote>
<p>This is just an example, I want to run a for loop for 10,000 length list. </p>
| 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_str,old[i],new[i])
</code></pre>
<p>However, this will still replace the <code>a</code> in <code>are</code> and the <code>c</code> in <code>much</code>, and it might also replace characters that were introduced in an earlier replacement, which is probably not what you want. Instead, you could use the <a href="https://docs.python.org/3/library/re.html" rel="nofollow"><code>re</code></a> module, joining the strings to be replaced with <code>|</code> to a regex and delimiting it with <code>\b</code> word boundary characters, e.g. <code>\b(a|b|c)\b</code> in your case, and use a dictionary to look up the proper replacements. </p>
<pre><code>d = dict(zip(old, new))
p = r'\b(' + '|'.join(old) + r')\b'
my_str = re.sub(p, lambda m: d.get(m.group()), my_str)
</code></pre>
<p>Result: <code>there are two much person p, person q, person r.</code></p>
| 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>
<p>The only problem is that when openpyxl iterates through the workbook, it records every value instead of the filtered data. </p>
<p>for example if the original spreadsheet is:</p>
<pre><code> A B C
1 x x x
2 x y x
3 x x x
</code></pre>
<p>and I filter column B to only show rows that contain "x", then save the workbook. I want openpyxl to only iterate through rows 1 and 3. </p>
<p>here is my code:</p>
<pre><code>from openpyxl import load_workbook
from openpyxl import workbook
import os
#sort using vba script
os.system(r"C:\script.vbs")
#load workbook
path = 'C:/public/temp/workbook.xlsm'
wb = load_workbook(filename = path)
ws=wb.get_sheet_by_name('Sheet3')
#make empty lists
proj_name = []
proj_num = []
proj_status = []
#iterate through rows and append values to lists
for row in ws.iter_rows('D{}:D{}'.format(ws.min_row,ws.max_row)):
for cell in row:
proj_name.append(cell.value)
for row in ws.iter_rows('R{}:R{}'.format(ws.min_row,ws.max_row)):
for cell in row:
proj_num.append(cell.value)
for row in ws.iter_rows('G{}:G{}'.format(ws.min_row,ws.max_row)):
for cell in row:
proj_status.append(cell.value)
#create dictionary from lists using defaultdict
from collections import defaultdict
dict1 = dict((z[0],list(z[1:])) for z in zip(proj_num,proj_name,proj_status))
with open(r"C:\public\list2.txt", "w") as text_file:
text_file.write(str(dict1))
text_file.close()
</code></pre>
| 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 applications like Excel."</p>
<p>It looks as though you may have to find another solution ...</p>
| 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.