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
sequence |
---|---|---|---|---|---|---|---|---|---|
How to select all values from one threshold to another? | 40,011,617 | <p>I have an ordered tuple of data:</p>
<pre><code>my_data = (1,2,3,2,4,2,3,3,5,7,5,3,6,8,7)
</code></pre>
<p>How can I subset the tuple items such that all items including and after the first instance of 3 are kept until the first value == 7? For example, the result should be:</p>
<pre><code>desired_output = (3,2,4,2,3,3,5,7)
</code></pre>
| -1 | 2016-10-13T03:04:14Z | 40,011,683 | <p><code>itertools</code> has <code>dropwhile</code> and <code>takewhile</code> that you can use to your advantage. Use <code>dropwhile</code> to drop everything until the first <code>3</code>, and <code>takewhile</code> to take everything until the first 7 thereafter. Then just merge the two</p>
<pre><code>import itertools
L = [1,2,3,2,4,2,3,3,5,7,5,3,6,8,7]
answer = list(itertools.takewhile(lambda x: x!=7, itertools.dropwhile(lambda x: x!=3, L)))
answer.append(7)
In [49]: answer
Out[49]: [3, 2, 4, 2, 3, 3, 5, 7]
</code></pre>
| 0 | 2016-10-13T03:13:00Z | [
"python",
"tuples"
] |
How to select all values from one threshold to another? | 40,011,617 | <p>I have an ordered tuple of data:</p>
<pre><code>my_data = (1,2,3,2,4,2,3,3,5,7,5,3,6,8,7)
</code></pre>
<p>How can I subset the tuple items such that all items including and after the first instance of 3 are kept until the first value == 7? For example, the result should be:</p>
<pre><code>desired_output = (3,2,4,2,3,3,5,7)
</code></pre>
| -1 | 2016-10-13T03:04:14Z | 40,011,685 | <pre><code>found_three = False
res = []
for d in data:
if d == 3:
found_three = True
if found_three:
res.append(d)
if d == 7;
break
</code></pre>
| 0 | 2016-10-13T03:13:09Z | [
"python",
"tuples"
] |
How to select all values from one threshold to another? | 40,011,617 | <p>I have an ordered tuple of data:</p>
<pre><code>my_data = (1,2,3,2,4,2,3,3,5,7,5,3,6,8,7)
</code></pre>
<p>How can I subset the tuple items such that all items including and after the first instance of 3 are kept until the first value == 7? For example, the result should be:</p>
<pre><code>desired_output = (3,2,4,2,3,3,5,7)
</code></pre>
| -1 | 2016-10-13T03:04:14Z | 40,011,689 | <p>my_data.index(my_data.index(min_thre):my_data.index(max_thre)+1)</p>
| 2 | 2016-10-13T03:13:22Z | [
"python",
"tuples"
] |
Running total won't print properly | 40,011,678 | <pre><code>def load():
global name
global count
global shares
global pp
global sp
global commission
name=input("Enter stock name OR -999 to Quit: ")
count =0
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
calc()
display()
name=input("\nEnter stock name OR -999 to Quit: ")
def calc():
totalpr=0
global amount_paid
global amount_sold
global profit_loss
global commission_paid_sale
global commission_paid_purchase
global totalpr
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
totalpr=totalpr+profit_loss
def display():
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
def main():
load()
main()
print("\nTotal Profit is $", format(totalpr, '10,.2f'))
</code></pre>
<p>The last line of code is indicative of the problem. The display for "totalpr" is not a running tally of, say, 3 entered stocks. It's merely the profit_loss restated. How do I get it to accurately display the running total for however many times someone decides to enter stock data? The way it works: someone enters the sentinel '-999' then the program adds up all the profit_loss from every instance and prints it out. That's it. </p>
| 0 | 2016-10-13T03:12:42Z | 40,011,832 | <p>You are resetting <code>totalpr</code> every time <code>calc</code> is called.</p>
<pre><code>def calc():
totalpr=0 # resets to zero every time
# ...
totalpr=totalpr+profit_loss # same as `totalpr = 0 + profit_loss`
</code></pre>
<p>Instead, you have to initialize <code>totalpr</code> outside of <code>calc</code>:</p>
<pre><code>totalpr = 0 # set to zero only once
def calc():
# ...
totalpr = totalpr + profit_loss # same as `totalpr += profit_loss`
</code></pre>
| 0 | 2016-10-13T03:29:04Z | [
"python",
"python-3.x",
"printing"
] |
Self is not defined? | 40,011,755 | <p>I am attempting to make a basic study clock as a learning exercise for Tkinter but I get an error when attempting run it saying self is not defined. Here is the error message.</p>
<pre><code>Traceback (most recent call last):
File "productivityclock.py", line 6, in <module>
class gui(object):
File "productivityclock.py", line 113, in gui
while 0 < self.z:
NameError: name 'self' is not defined
</code></pre>
<p>Here is my code, I would really appreciate if someone could help me out, Thanks</p>
<pre><code>from Tkinter import *
import time
root = Tk()
class gui(object):
def __init__(self, master):
self.frame = Frame(master)
self.frame.pack()
t_int = 0
b_int = 0
reps = 0
self.menu()
def menu(self):
self.button1 = Button(
self.frame, text="Set Time", command = self.set_time)
self.button2 = Button(
self.frame, text="Set Breaks", command = self.set_break)
self.button3 = Button(
self.frame, text="Set Intervals", command = self.set_reps)
self.button4 = Button(
self.frame, text="Start", command = self.timer)
self.button1.pack(side = LEFT)
self.button2.pack(side = LEFT)
self.button3.pack(side = LEFT)
self.button4.pack(side = LEFT)
def set_time(self):
self.button1.pack_forget()
self.button2.pack_forget()
self.button3.pack_forget()
self.button4.pack_forget()
self.l = Label(self.frame, text = "Enter the time of each study session (minutes)")
self.button = Button(
self.frame, text="Get", command=self.on_button1)
self.entry = Entry(self.frame)
self.button.pack(side = RIGHT)
self.entry.pack(side = LEFT)
self.l.pack(side = LEFT)
def set_break(self):
self.button1.pack_forget()
self.button2.pack_forget()
self.button3.pack_forget()
self.button4.pack_forget()
self.l = Label(self.frame, text = "Enter the time of each break (minutes)")
self.button = Button(
self.frame, text="Get", command=self.on_button2)
self.entry = Entry(self.frame)
self.button.pack(side = RIGHT)
self.entry.pack(side = LEFT)
self.l.pack(side = LEFT)
def set_reps(self):
self.button1.pack_forget()
self.button2.pack_forget()
self.button3.pack_forget()
self.button4.pack_forget()
self.l = Label(self.frame, text = "Enter the amount of study sessions (minutes)")
self.button = Button(
self.frame, text="Get", command=self.on_button3)
self.entry = Entry(self.frame)
self.button.pack(side = RIGHT)
self.entry.pack(side = LEFT)
self.l.pack(side = LEFT)
def on_button1(self):
x = self.entry.get()
self.t_int = x
print self.t_int
self.button.pack_forget()
self.entry.pack_forget()
self.l.pack_forget()
self.menu()
def on_button2(self):
x = self.entry.get()
self.b_int = x
print self.b_int
self.button.pack_forget()
self.entry.pack_forget()
self.l.pack_forget()
self.menu()
def on_button3(self):
x = self.entry.get()
self.reps = x
print self.reps
self.button.pack_forget()
self.entry.pack_forget()
self.l.pack_forget()
self.menu()
def timer(self):
x = self.t_int
y = self.b_int
self.z = self.reps
while 0 < self.z:
while x > 0:
time.sleep(60)
n = Label(self.frame, text = "You have %r minutes left in your session") % x
n.pack(side = LEFT)
x = x - 1
n.pack_forget
while y > 0:
time.sleep(60)
self.e = Label(self.frame, text = "You have %r minutes left in your break") % y
self.e.pack(side = LEFT)
self.y = self.y - 1
self.e.pack_forget()
z = z - 1
x = self.t_int
y = self.b_int
app = gui(root)
root.mainloop()
</code></pre>
| -1 | 2016-10-13T03:21:53Z | 40,011,828 | <p>Yes, at line 113, <code>while 0 < self.z:</code> is not properly indented, and all the lines below it.</p>
| 0 | 2016-10-13T03:28:40Z | [
"python",
"python-2.7",
"tkinter"
] |
How to convert a selenium webelement to string variable in python | 40,011,816 | <pre><code>from selenium import webdriver
from time import sleep
from selenium.common.exceptions import NoSuchAttributeException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get('https://www.linkedin.com/jobs/search?locationId=sg%3A0&f_TP=1%2C2&orig=FCTD&trk=jobs_jserp_posted_one_week')
jobtitlebutton = driver.find_elements_by_class_name('job-title-link')
print(jobtitlebutton)
</code></pre>
<p>The output is a selenium webelement in the form of a list. I want to convert it into a string variable so that the list can contain all the jobtitles in text format.
If I can get assistance in this it will be great. Thanks in advance.</p>
| 1 | 2016-10-13T03:27:33Z | 40,012,512 | <p>In case, if you need a list of links to each job:</p>
<pre><code>job_list = []
jobtitlebuttons = driver.find_elements_by_class_name('job-title-link')
for job in jobtitlebuttons:
job_list.append(job.get_attribute('href'))
</code></pre>
<p>In case, if you want just a job titles list:</p>
<pre><code>job_list = []
jobtitlebuttons = driver.find_elements_by_class_name('job-title-text')
for job in jobtitlebuttons:
job_list.append(job.text)
</code></pre>
<p>Don't forget to accept answer if it solves your problem :) </p>
| 1 | 2016-10-13T04:50:22Z | [
"python",
"selenium"
] |
python modifying a variable with a function | 40,011,826 | <p>I am trying to write a function for a basic python course that I am taking. We are at the point where we join as a group and make one program as a team. I have assigned each member to write their portion as a function in the hopes that I can just call each function to perform the overall program. It has been a while since I played in object programing and this is above the class requirements but I want to try and make this work.</p>
<p>I am having difficulty passing a variable into a function then retrieving the changed variable from the function. </p>
<p>I have tried reading on multiple sites and deep search on here but I am missing something and any assistance would be greatly appreciated.</p>
<p>Here is the first sample of code I tried</p>
<pre><code>import random
MOBhp=100
def ATTACK(TYPEatck,MOBhp):
# global MOBhp
print ('the type attack chosen was ',TYPEatck,'the MOB has ',MOBhp)
if TYPEatck =='M'or TYPEatck =='m':
print ('the ',PLAYER,' used melee to attack',MOB)
MOBhp=MOBhp-10
elif TYPEatck =='R'or TYPEatck =='r':
print ('the ',PLAYER,' used range to attack',MOB)
MOBhp=MOBhp-5
else:
print ('please choose a valid attack')
print ('the MOB hitpoints are ',MOBhp)
return MOBhp;
PLAYER='HERO'
MOB='Dragon'
AC=12
while MOBhp > 0:
TYPEatck=random.choice('RM')
ATTACK(TYPEatck,MOBhp)
print('really the MOB hitpoints are ', MOBhp)
print(MOB,'was slain by ',PLAYER)
</code></pre>
<p>This gives a repeating result that I have to break with cntrl+c</p>
<pre><code>the type attack chosen was R the MOB has 100
the HERO used range to attack Dragon
the MOB hitpoints are 95
the type attack chosen was M the MOB has 100
the HERO used melee to attack Dragon
the MOB hitpoints are 90
the type attack chosen was R the MOB has 100
the HERO used range to attack Dragon
the MOB hitpoints are 95
</code></pre>
<p>Where as if I do the following</p>
<pre><code>enter code here
#while MOBhp > 0:
TYPEatck=random.choice('RM')
ATTACK(TYPEatck,MOBhp)
print('really the MOB hitpoints are ', MOBhp)
print(MOB,'was slain by ',PLAYER)
</code></pre>
<p>I get the following results</p>
<pre><code>the type attack chosen was R the MOB has 100
the HERO used range to attack Dragon
the MOB hitpoints are 95
really the MOB hitpoints are 100
Dragon was slain by HERO
</code></pre>
<p>I have tried to play with global variables as well and can't seem to get that to work either.</p>
| -1 | 2016-10-13T03:28:26Z | 40,011,968 | <p>As it is right now, you are throwing away the result of your calculation. You have to store it an use it as input for the next calculation.</p>
<pre><code>while MOBhp > 0:
TYPEatck=random.choice('RM')
MOBhp = ATTACK(TYPEatck,MOBhp)
</code></pre>
| 2 | 2016-10-13T03:45:43Z | [
"python",
"function",
"variables"
] |
python modifying a variable with a function | 40,011,826 | <p>I am trying to write a function for a basic python course that I am taking. We are at the point where we join as a group and make one program as a team. I have assigned each member to write their portion as a function in the hopes that I can just call each function to perform the overall program. It has been a while since I played in object programing and this is above the class requirements but I want to try and make this work.</p>
<p>I am having difficulty passing a variable into a function then retrieving the changed variable from the function. </p>
<p>I have tried reading on multiple sites and deep search on here but I am missing something and any assistance would be greatly appreciated.</p>
<p>Here is the first sample of code I tried</p>
<pre><code>import random
MOBhp=100
def ATTACK(TYPEatck,MOBhp):
# global MOBhp
print ('the type attack chosen was ',TYPEatck,'the MOB has ',MOBhp)
if TYPEatck =='M'or TYPEatck =='m':
print ('the ',PLAYER,' used melee to attack',MOB)
MOBhp=MOBhp-10
elif TYPEatck =='R'or TYPEatck =='r':
print ('the ',PLAYER,' used range to attack',MOB)
MOBhp=MOBhp-5
else:
print ('please choose a valid attack')
print ('the MOB hitpoints are ',MOBhp)
return MOBhp;
PLAYER='HERO'
MOB='Dragon'
AC=12
while MOBhp > 0:
TYPEatck=random.choice('RM')
ATTACK(TYPEatck,MOBhp)
print('really the MOB hitpoints are ', MOBhp)
print(MOB,'was slain by ',PLAYER)
</code></pre>
<p>This gives a repeating result that I have to break with cntrl+c</p>
<pre><code>the type attack chosen was R the MOB has 100
the HERO used range to attack Dragon
the MOB hitpoints are 95
the type attack chosen was M the MOB has 100
the HERO used melee to attack Dragon
the MOB hitpoints are 90
the type attack chosen was R the MOB has 100
the HERO used range to attack Dragon
the MOB hitpoints are 95
</code></pre>
<p>Where as if I do the following</p>
<pre><code>enter code here
#while MOBhp > 0:
TYPEatck=random.choice('RM')
ATTACK(TYPEatck,MOBhp)
print('really the MOB hitpoints are ', MOBhp)
print(MOB,'was slain by ',PLAYER)
</code></pre>
<p>I get the following results</p>
<pre><code>the type attack chosen was R the MOB has 100
the HERO used range to attack Dragon
the MOB hitpoints are 95
really the MOB hitpoints are 100
Dragon was slain by HERO
</code></pre>
<p>I have tried to play with global variables as well and can't seem to get that to work either.</p>
| -1 | 2016-10-13T03:28:26Z | 40,014,125 | <p>MisterMiyagi's answer is helpful.
If you want to use global variables ,you may use it like this:</p>
<pre><code>import random
MOBhp=100
def ATTACK(TYPEatck, hp):
global MOBhp
MOBhp = hp
print('the type attack chosen was ',TYPEatck,'the MOB has ',MOBhp)
if TYPEatck == 'M' or TYPEatck == 'm':
print('the ',PLAYER,' used melee to attack',MOB)
MOBhp = MOBhp - 10
elif TYPEatck == 'R' or TYPEatck == 'r':
print('the ',PLAYER,' used range to attack',MOB)
MOBhp = MOBhp - 5
else:
print('please choose a valid attack')
print('the MOB hitpoints are ',MOBhp)
return MOBhp;
PLAYER = 'HERO'
MOB = 'Dragon'
AC = 12
while MOBhp > 0:
TYPEatck = random.choice('RM')
ATTACK(TYPEatck,MOBhp)
print('really the MOB hitpoints are ', MOBhp)
print(MOB,'was slain by ',PLAYER)
</code></pre>
<p>Or,you can use class:</p>
<pre><code>import random
class Game():
def __init__(self, player, mob):
self.player = player
self.mob = mob
self.mobhp = 100
def ATTACK(self, TYPEatck):
print('the type attack chosen was ',TYPEatck,'the MOB has ',self.mobhp)
if TYPEatck == 'M' or TYPEatck == 'm':
print('the ',self.player,' used melee to attack',self.mob)
self.mobhp -= 10
elif TYPEatck == 'R' or TYPEatck == 'r':
print('the ',self.player,' used range to attack',self.mob)
self.mobhp -= 5
else:
print('please choose a valid attack')
print('the MOB hitpoints are ',self.mobhp)
return self.mobhp;
def get_MOBhp(self):
return self.mobhp
PLAYER = 'HERO'
MOB = 'Dragon'
AC = 12
game = Game(PLAYER, MOB)
while game.get_MOBhp() > 0:
TYPEatck = random.choice('RM')
game.ATTACK(TYPEatck)
print('really the MOB hitpoints are ', game.get_MOBhp())
print(MOB,'was slain by ',PLAYER)
</code></pre>
| 0 | 2016-10-13T06:49:57Z | [
"python",
"function",
"variables"
] |
python modifying a variable with a function | 40,011,826 | <p>I am trying to write a function for a basic python course that I am taking. We are at the point where we join as a group and make one program as a team. I have assigned each member to write their portion as a function in the hopes that I can just call each function to perform the overall program. It has been a while since I played in object programing and this is above the class requirements but I want to try and make this work.</p>
<p>I am having difficulty passing a variable into a function then retrieving the changed variable from the function. </p>
<p>I have tried reading on multiple sites and deep search on here but I am missing something and any assistance would be greatly appreciated.</p>
<p>Here is the first sample of code I tried</p>
<pre><code>import random
MOBhp=100
def ATTACK(TYPEatck,MOBhp):
# global MOBhp
print ('the type attack chosen was ',TYPEatck,'the MOB has ',MOBhp)
if TYPEatck =='M'or TYPEatck =='m':
print ('the ',PLAYER,' used melee to attack',MOB)
MOBhp=MOBhp-10
elif TYPEatck =='R'or TYPEatck =='r':
print ('the ',PLAYER,' used range to attack',MOB)
MOBhp=MOBhp-5
else:
print ('please choose a valid attack')
print ('the MOB hitpoints are ',MOBhp)
return MOBhp;
PLAYER='HERO'
MOB='Dragon'
AC=12
while MOBhp > 0:
TYPEatck=random.choice('RM')
ATTACK(TYPEatck,MOBhp)
print('really the MOB hitpoints are ', MOBhp)
print(MOB,'was slain by ',PLAYER)
</code></pre>
<p>This gives a repeating result that I have to break with cntrl+c</p>
<pre><code>the type attack chosen was R the MOB has 100
the HERO used range to attack Dragon
the MOB hitpoints are 95
the type attack chosen was M the MOB has 100
the HERO used melee to attack Dragon
the MOB hitpoints are 90
the type attack chosen was R the MOB has 100
the HERO used range to attack Dragon
the MOB hitpoints are 95
</code></pre>
<p>Where as if I do the following</p>
<pre><code>enter code here
#while MOBhp > 0:
TYPEatck=random.choice('RM')
ATTACK(TYPEatck,MOBhp)
print('really the MOB hitpoints are ', MOBhp)
print(MOB,'was slain by ',PLAYER)
</code></pre>
<p>I get the following results</p>
<pre><code>the type attack chosen was R the MOB has 100
the HERO used range to attack Dragon
the MOB hitpoints are 95
really the MOB hitpoints are 100
Dragon was slain by HERO
</code></pre>
<p>I have tried to play with global variables as well and can't seem to get that to work either.</p>
| -1 | 2016-10-13T03:28:26Z | 40,028,856 | <p>Thank you all for you assistance! I figured it out and was able to write my program to completion. </p>
<p><a href="https://www.reddit.com/r/Python/comments/578b6e/0300/" rel="nofollow">Here is the code formatted and shared on Reddit</a></p>
| 0 | 2016-10-13T18:56:27Z | [
"python",
"function",
"variables"
] |
Jumping simulation stop falling when returned to ground | 40,011,860 | <p>I am trying to simulate a jump in a Rect.</p>
<p>I set the KEYDOWN and KEYUP events and K_SPACE button to simulate the jump. </p>
<p>My difficulty is stopping the returning fall when the rect reaches the ground (using cordX).</p>
<p>I realize that will not work and comment it out in the GAME_BEGIN statement.</p>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("shield hacking")
JogoAtivo = True
GAME_BEGIN = False
# Speed in pixels per frame
speedX = 0
speedY = 0
cordX = 10
cordY = 100
jumping=False;
run=False;
def draw():
screen.fill((0, 0, 0))
quadrado = pygame.draw.rect(screen, (255, 0, 0), (cordX, cordY ,50, 52))
pygame.display.flip();
while JogoAtivo:
for evento in pygame.event.get():
print(evento)
#verifica se o evento que veio eh para fechar a janela
if evento.type == pygame.QUIT:
JogoAtivo = False
pygame.quit();
if evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_a:
print('GAME BEGIN')
GAME_BEGIN = True
draw();
if evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_LEFT:
speedX=-0.006
run= True;
if evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_RIGHT:
speedX=0.006
run= True;
if evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_SPACE:
speedY=-0.090
jumping= True;
if evento.type == pygame.KEYUP:
if evento.key == pygame.K_SPACE:
speedY=+0.090
jumping= True;
if GAME_BEGIN:
if not jumping:
gravity = cordX;
"""if gravity == cordY:
speedY=0;"""
cordX+=speedX
cordY+=speedY
draw()
</code></pre>
<blockquote>
<blockquote>
<blockquote>
<p>UPDATED BELOW</p>
</blockquote>
</blockquote>
</blockquote>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("shield hacking")
JogoAtivo = True
GAME_BEGIN = False
# Speed in pixels per frame
speedX = 0
speedY = 0
cordX = 10
cordY = 100
groundX=0;
groundY=150;
jumping=False;
run=False;
def draw():
screen.fill((0, 0, 0))
ground = pygame.draw.rect(screen, (0, 255, 0), (groundX, groundY,400, 10))
quadrado = pygame.draw.rect(screen, (255, 0, 0), (cordX, cordY ,50, 52))
pygame.display.flip();
while JogoAtivo:
for evento in pygame.event.get():
print(evento)
#verifica se o evento que veio eh para fechar a janela
if evento.type == pygame.QUIT:
JogoAtivo = False
pygame.quit();
if evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_a:
print('GAME BEGIN')
GAME_BEGIN = True
draw();
if evento.key == pygame.K_LEFT:
speedX=-0.006
run= True;
if evento.key == pygame.K_RIGHT:
speedX=0.006
run= True;
if evento.key == pygame.K_SPACE:
speedY=-0.090
jumping= True;
if evento.type == pygame.KEYUP:
if evento.key == pygame.K_SPACE:
speedY=+0.090
jumping= True;
if GAME_BEGIN:
cordX+=speedX
cordY+=speedY
draw();
if cordY +50>= groundY:
speedY=0
jumping=False;
</code></pre>
| 0 | 2016-10-13T03:32:27Z | 40,012,254 | <p>Tks, i have done what you said, here is my code</p>
<pre><code> import pygame
pygame.init()
screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("shield hacking")
JogoAtivo = True
GAME_BEGIN = False
# Speed in pixels per frame
speedX = 0
speedY = 0
cordX = 10
cordY = 100
groundX=0;
groundY=150;
jumping=False;
run=False;
def draw():
screen.fill((0, 0, 0))
ground = pygame.draw.rect(screen, (0, 255, 0), (groundX, groundY,400, 10))
quadrado = pygame.draw.rect(screen, (255, 0, 0), (cordX, cordY ,50, 52))
pygame.display.flip();
while JogoAtivo:
for evento in pygame.event.get():
print(evento)
#verifica se o evento que veio eh para fechar a janela
if evento.type == pygame.QUIT:
JogoAtivo = False
pygame.quit();
if evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_a:
print('GAME BEGIN')
GAME_BEGIN = True
draw();
if evento.key == pygame.K_LEFT:
speedX=-0.006
run= True;
if evento.key == pygame.K_RIGHT:
speedX=0.006
run= True;
if evento.key == pygame.K_SPACE:
speedY=-0.090
jumping= True;
if evento.type == pygame.KEYUP:
if evento.key == pygame.K_SPACE:
speedY=+0.090
jumping= True;
if GAME_BEGIN:
cordX+=speedX
cordY+=speedY
draw();
if cordY +50>= groundY:
speedY=0
jumping=False;
</code></pre>
<blockquote>
<blockquote>
<blockquote>
<p>Really appreciate the help.</p>
</blockquote>
</blockquote>
</blockquote>
| 0 | 2016-10-13T04:23:44Z | [
"python",
"pygame"
] |
If value true but null not work | 40,011,874 | <p>I made program is input number and delete data in mysql. but run program error then report <code>sql1</code> Syntax Error\i change true</p>
<pre><code>#!/usr/bin/python
import mysql.connector
conn = mysql.connector.connect(host="",user="",passwd="",db="")
cursor = conn.cursor()
try:
num = int(input("InputNumber 1-10 : "))
if num <= 10:
if num == null: //if null print false
sql1 = "SELECT user1 FROM dt WHERE user1 = '%d' " %(num)
cursor.execute(sql1)
data = cursor.fetchall()
print(data[0])
sqlde = "DELETE FROM dt WHERE user1 = '%d' " %(num)
cursor.execute(sqlde, (num))
print "DELETE SUCESS"
conn.commit()
else:
print "Data Empty"
except:
conn.rollback()
conn.close()
</code></pre>
| 1 | 2016-10-13T03:33:24Z | 40,012,032 | <p>num = int(input("InputNumber: ")<code>)</code> <- don't forguet to close it</p>
<p>I'm not sure about the <code>%i</code>, I always see using <code>%d</code> for Integer and <code>%s</code> to strings</p>
<p>But, you also have one problem into your query, <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">SQL Injection</a></p>
<p>So to avoid this, try something like this</p>
<pre><code>sql1 = "DELETE FROM dt WHERE user1 = ?"
try:
cursor.execute(sql1, (num))
print "DELETE SUCECC"
conn.commit()
except:
conn.rollback()
print "ERROR DELETE"
</code></pre>
<p>you can check about <a href="http://www.sqlite.org/c3ref/bind_blob.html" rel="nofollow">question mark here</a> or <a href="https://en.wikipedia.org/wiki/Prepared_statement#Parameterized_statements" rel="nofollow">here</a> and understand why you should bind your values</p>
| 3 | 2016-10-13T03:54:21Z | [
"python",
"mysql"
] |
Debug tensorflow unit tests | 40,011,891 | <p>I find the <a href="http://stackoverflow.com/questions/34204551/run-tensorflow-unit-tests">link</a> which shows how to run the unit tests.</p>
<p>And I think it could get a better understanding about the source code by debug the unit tests.</p>
<p>I can debug the source code as the tensorflow python application run. But I don't know how to debug the unit test. I am new to bazel and gdb debug.</p>
| 0 | 2016-10-13T03:35:57Z | 40,099,717 | <p>To summarize:</p>
<ul>
<li>you have to make sure the test binary is built first: either by running <code>bazel test <target></code> or with <code>bazel build <target></code> or with <code>bazel build -c dbg <target></code>. The last one gives fully debuggable executables that give you line numbers in gdb backtrace.</li>
<li>The binary is in the same directory as the BUILD file (ie, if you have <code>tensorflow/core/BUILD</code>, then the binary will be under <code>bazel-bin/tensorflow/core</code>)</li>
<li>You can find the name of bazel that includes given <code>.cc</code> file by using bazel query. IE, for <code>common_shape_fns_test</code> you can find that target name is <code>//tensorflow/core:framework_common_shape_fns_test</code> by using command below</li>
</ul>
<p>.</p>
<pre><code>fullname=$(bazel query tensorflow/core/framework/common_shape_fns_test.cc)
bazel query "attr('srcs', $fullname, ${fullname//:*/}:*)"
</code></pre>
| 0 | 2016-10-18T04:47:42Z | [
"python",
"c++",
"machine-learning",
"gdb",
"tensorflow"
] |
NLTK vs Stanford NLP | 40,011,896 | <p>I have recently started to use NLTK toolkit for creating few solutions using Python.</p>
<p>I hear a lot of community activity regarding using stanford NLP.
Can anyone tell me what is the difference between NLTK and Stanford NLP ? Are they 2 different libraries ? i know that NLTK has an interface to stanford NLP but can anyone throw some light on few basic differences or even more in detail.</p>
<p>Can stanford NLP be used using Python ?</p>
| 0 | 2016-10-13T03:36:31Z | 40,028,128 | <blockquote>
<p>Can anyone tell me what is the difference between NLTK and Stanford NLP? Are they 2 different libraries ? I know that NLTK has an interface to Stanford NLP but can anyone throw some light on few basic differences or even more in detail.</p>
</blockquote>
<p>(I'm assuming you mean "<a href="http://stanfordnlp.github.io/CoreNLP/" rel="nofollow">Stanford CoreNLP</a>".)</p>
<p>They are two different libraries.</p>
<ul>
<li><strong>Stanford CoreNLP</strong> is written in Java</li>
<li><strong>NLTK</strong> is a Python library</li>
</ul>
<p>The main functional difference is that NLTK has multiple versions or interfaces to other versions of NLP tools, while Stanford CoreNLP only has their version. NLTK also supports installing third-party Java projects, and even includes <a href="https://github.com/nltk/nltk/wiki/Installing-Third-Party-Software#stanford-tagger-ner-tokenizer-and-parser" rel="nofollow">instructions for installing some Stanford NLP packages on the wiki</a>.</p>
<p>Both have good support for English, but if you are dealing with other languages:</p>
<ul>
<li><strong>Stanford CoreNLP</strong> comes with <a href="http://stanfordnlp.github.io/CoreNLP/human-languages.html" rel="nofollow">models for English, Chinese, French, German, Spanish, and Arabic</a>.</li>
<li><strong>NLTK</strong> comes with <a href="http://www.nltk.org/nltk_data/" rel="nofollow">corpora in additional languages like Portugese, Russian, and Polish</a>. Individual tools may support even more languages (e.g. no Danish corpora, but has a <a href="http://www.nltk.org/api/nltk.stem.html#nltk.stem.snowball.DanishStemmer" rel="nofollow">DanishStemmer</a>).</li>
</ul>
<p>That said, which one is "best" will depend on your specific application and required performance (what features you are using, language, vocabulary, desired speed, etc.).</p>
<blockquote>
<p>Can Stanford NLP be used using Python?</p>
</blockquote>
<p><a href="http://stanfordnlp.github.io/CoreNLP/other-languages.html#python" rel="nofollow">Yes, there are a number of interfaces and packages for using Stanford CoreNLP in Python</a> (independent of NLTK).</p>
| 2 | 2016-10-13T18:13:06Z | [
"python",
"nltk",
"stanford-nlp"
] |
Join two dataframes on values within the second dataframe | 40,011,943 | <p>I am trying to join two dataframes off of values within the dataset:</p>
<pre><code>df1 t0 t1 text0 text1
ID
2133 7.0 3.0 NaN NaN
1234 10.0 8.0 NaN NaN
7352 9.0 7.0 NaN NaN
2500 7.0 6.0 NaN NaN
3298 10.0 8.0 NaN NaN
</code></pre>
<p>df1 (seen above)</p>
<pre><code>df2 score text_org
ID
2133 7.0 asdf
2500 7.0 cccc
3298 8.0 ytyt
2133 3.0 qwer
1234 10.0 pois
7352 9.0 ijsd
7352 7.0 bdcs
3298 10.0 swed
1234 8.0 zzzz
2500 6.0 erer
</code></pre>
<p>and df2 (seen above)</p>
<p>I am trying to combine the two dataframes so that the NaNs in df1 are replaced with the text_org from df2. As you can see, we get the text by matching the ID with the score from either t0 or t1. Ideally it would look something like this:</p>
<pre><code> df1 t0 t1 text0 text1
ID
2133 7.0 3.0 asdf qwer
1234 10.0 8.0 pois zzzz
7352 9.0 7.0 ijsd bdcs
2500 7.0 6.0 cccc erer
3298 10.0 8.0 swed ytyt
</code></pre>
<p>I was trying to use pd.merge - doing to joins, but I haven't been getting anywhere. Thanks for any help! </p>
| 2 | 2016-10-13T03:42:53Z | 40,013,126 | <p>You can use first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> for reshaping with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a> empty columns <code>text0</code> and <code>text1</code>:</p>
<pre><code>df = pd.melt(df1.drop(['text0','text1'], axis=1), id_vars='ID', value_name='score')
print (df)
ID variable score
0 2133 t0 7.0
1 1234 t0 10.0
2 7352 t0 9.0
3 2500 t0 7.0
4 3298 t0 10.0
5 2133 t1 3.0
6 1234 t1 8.0
7 7352 t1 7.0
8 2500 t1 6.0
9 3298 t1 8.0
</code></pre>
<p>Then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> by inner join (parameter <code>how='inner'</code> is by default, so it is omit) and also is omit <code>on=['ID','score']</code> because in both <code>DataFrames</code> are only common this 2 columns:</p>
<pre><code>df = pd.merge(df2, df)
print (df)
ID score text_org variable
0 2133 7.0 asdf t0
1 2500 7.0 cccc t0
2 3298 8.0 ytyt t1
3 2133 3.0 qwer t1
4 1234 10.0 pois t0
5 7352 9.0 ijsd t0
6 7352 7.0 bdcs t1
7 3298 10.0 swed t0
8 1234 8.0 zzzz t1
9 2500 6.0 erer t1
</code></pre>
<p>Last reshape again by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a> and set column names by <code>df1</code> without first column (<code>[1:]</code>):</p>
<pre><code>df = df.set_index(['ID','variable']).unstack()
df.columns = df1.columns[1:]
print (df)
t0 t1 text0 text1
ID
1234 10.0 8.0 pois zzzz
2133 7.0 3.0 asdf qwer
2500 7.0 6.0 cccc erer
3298 10.0 8.0 swed ytyt
7352 9.0 7.0 ijsd bdcs
</code></pre>
<p>EDIT by comment:</p>
<p>You get:</p>
<blockquote>
<p>ValueError: Index contains duplicate entries, cannot reshape</p>
</blockquote>
<p>Problem is if <code>df2</code> have duplicates by column <code>ID</code> and <code>score</code>.</p>
<p>e.g. new row is added to the end and it has same <code>ID</code> and <code>score</code> as first row (<code>2133</code> and <code>7.0</code>) - so get duplicates:</p>
<pre><code>print (df2)
ID score text_org
0 2133 7.0 asdf
1 2500 7.0 cccc
2 3298 8.0 ytyt
3 2133 3.0 qwer
4 1234 10.0 pois
5 7352 9.0 ijsd
6 7352 7.0 bdcs
7 3298 10.0 swed
8 1234 8.0 zzzz
9 2500 6.0 erer
10 2133 7.0 new_val
</code></pre>
<p>After merge you can check first and second column - for same <code>ID</code> with <code>score</code> you get 2 values - <code>asdf</code> and <code>new_val</code>, so get error:</p>
<pre><code>df = pd.merge(df2, df)
print (df)
ID score text_org variable
0 2133 7.0 asdf t0
1 2133 7.0 new_val t0
2 2500 7.0 cccc t0
3 3298 8.0 ytyt t1
4 2133 3.0 qwer t1
5 1234 10.0 pois t0
6 7352 9.0 ijsd t0
7 7352 7.0 bdcs t1
8 3298 10.0 swed t0
9 1234 8.0 zzzz t1
10 2500 6.0 erer t1
</code></pre>
<p>Solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> with some aggreagate function or remove duplicates in <code>df2</code> (e.g. use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a>):</p>
<pre><code>#aggregate function is first
df3 = df.pivot_table(index='ID', columns='variable', aggfunc='first')
df3.columns = df1.columns[1:]
print (df3)
t0 t1 text0 text1
ID
1234 10 8 pois zzzz
2133 7 3 asdf qwer
2500 7 6 cccc erer
3298 10 8 swed ytyt
7352 9 7 ijsd bdcs
#aggregate function is last
df4 = df.pivot_table(index='ID', columns='variable', aggfunc='last')
df4.columns = df1.columns[1:]
print (df4)
t0 t1 text0 text1
ID
1234 10 8 pois zzzz
2133 7 3 new_val qwer
2500 7 6 cccc erer
3298 10 8 swed ytyt
7352 9 7 ijsd bdcs
</code></pre>
<p>Better explanation with another sample in <a class='doc-link' href="http://stackoverflow.com/documentation/pandas/1463/reshaping-and-pivoting/4771/pivoting-with-aggregating#t=201610130747216681484">SO documentation</a>.</p>
| 3 | 2016-10-13T05:41:58Z | [
"python",
"python-3.x",
"pandas",
"join",
"dataframe"
] |
Anaconda - HTTPError when Updating | 40,011,948 | <p>I'm getting the following error when I try to run <code>conda update numpy</code> (also when running <code>conda update conda</code>)</p>
<pre><code>Fetching package metadata ............CondaHTTPError: HTTP Error: Could not find URL: https://conda.anaconda.org/condaforge/linux-64/
</code></pre>
<p>The person in <a href="http://stackoverflow.com/questions/36095385/conda-error-could-not-found-url">this thread</a> had a similar issue, but I didn't find any mistakes in my .condarc similar to theirs.</p>
<p>Here is what my .condarc looks like</p>
<pre><code>channels:
- condaforge
- bioconda
- r
- defaults
</code></pre>
<p>And the output of <code>conda info</code></p>
<pre><code>Current conda install:
platform : linux-64
conda version : 4.2.9
conda is private : False
conda-env version : 4.2.9
conda-build version : not installed
python version : 3.5.2.final.0
requests version : 2.9.1
root environment : /home/axolotl/miniconda3 (writable)
default environment : /home/axolotl/miniconda3
envs directories : /home/axolotl/miniconda3/envs
package cache : /home/axolotl/miniconda3/pkgs
channel URLs : https://conda.anaconda.org/condaforge/linux-64/
https://conda.anaconda.org/condaforge/noarch/
https://conda.anaconda.org/bioconda/linux-64/
https://conda.anaconda.org/bioconda/noarch/
https://conda.anaconda.org/r/linux-64/
https://conda.anaconda.org/r/noarch/
https://repo.continuum.io/pkgs/free/linux-64/
https://repo.continuum.io/pkgs/free/noarch/
https://repo.continuum.io/pkgs/pro/linux-64/
https://repo.continuum.io/pkgs/pro/noarch/
config file : /home/axolotl/.condarc
offline mode : False
</code></pre>
| 0 | 2016-10-13T03:43:23Z | 40,022,617 | <p>The correct channel name is <code>conda-forge</code>. You should</p>
<pre><code>conda config --remove channels condaforge
conda config --add channels conda-forge
</code></pre>
| 0 | 2016-10-13T13:38:19Z | [
"python",
"anaconda",
"conda"
] |
How to handle 0 entries in book crossing dataset | 40,012,035 | <p>I am working with book <a href="http://www2.informatik.uni-freiburg.de/~cziegler/BX/" rel="nofollow">crossing Data-set</a> , It have a file which given user X's rating for book Y, but a lot of entries contains value 0 that means user X liked the book Y but did not give rating to it. I am using collaborative filtering hence these 0 entries are creating problems for me as if taken an 0 they decrease overall rating of the book.</p>
<p>I am new to Data science field can some one help how to handle this ?</p>
<p>What I can think of is replace 0 rating by user's average book rating but than again I don't any argument to support my Idea.</p>
| 0 | 2016-10-13T03:55:12Z | 40,014,658 | <p>ISBN codes are very messy, contain a lot of incorrect ISBNs, and are not unified.</p>
<p>Here are just a few examples:</p>
<pre><code>"User-ID";"ISBN";"Book-Rating"
"11676";" 9022906116";"7"
"11676";"\"0432534220\"";"6"
"11676";"\"2842053052\"";"7"
"11676";"0 7336 1053 6";"0"
"11676";"0=965044153";"7"
"11676";"0000000000";"9"
"11676";"00000000000";"8"
"146859";"01402.9182(PB";"7"
"158509";"0672=630155(P";"0"
"194500";"(THEWINDMILLP";"0"
</code></pre>
<p>So i would suggest to clean it up a little bit first:</p>
<pre><code>df.ISBN = df.ISBN.str.replace(r'[^\w\d]+', '')
</code></pre>
<p>then calculate average ratings:</p>
<pre><code>avg_ratings = df.groupby('ISBN')['Book-Rating'].mean().round().astype(np.int8)
</code></pre>
<p>and finally set average ratings to those books, having zero rating:</p>
<pre><code>df.ix[df['Book-Rating'] == 0, 'Book-Rating'] = df.ix[df['Book-Rating'] == 0, 'ISBN'].map(avg_ratings)
</code></pre>
| 0 | 2016-10-13T07:19:39Z | [
"python",
"pandas",
"machine-learning",
"data-science"
] |
Uncapitalizing first letter of a name | 40,012,062 | <p>To code a name like DeAnna you type:</p>
<pre><code>name = "de\aanna"
</code></pre>
<p>and </p>
<pre><code>print(name.title())
</code></pre>
<p>In this code <code>\a</code> capitalizes a normally uncapitalized letter. What do you code to produce a name like <code>"George von Trapp"</code> where I want to uncapitalize a normally capitalized letter?</p>
| 3 | 2016-10-13T03:59:43Z | 40,012,160 | <p>The <code>\a</code> does not capitalize a letter - it is the <a href="https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals" rel="nofollow">bell escape sequence</a>.</p>
<p>The <a href="https://docs.python.org/3/library/stdtypes.html#textseq" rel="nofollow"><code>str.title</code></a> simply capitalizes the first letter of any group of letters. Since the bell is not a letter, it has the same meaning as a space. The following produces equivalent capitalization:</p>
<pre><code>name = "de anna"
print(name.title())
</code></pre>
<p>Anyways, there are no capitalize/uncapitalize magic characters in python. Simply write the name properly. If you want both a proper and a lower-case version, create the <em>later</em> via <code>str.lower</code>:</p>
<pre><code>name = "George von Trapp"
print(name, ':', name.lower())
</code></pre>
<hr>
<p>If you <strong>really</strong> want to go from <code>"georg van trapp"</code> (I'm just pretending the discussion about <code>\a</code> is over) to <code>"Georg van Trapp"</code> - welcome to having-to-decide-about-the-semantics-of-the-language-you-are-emulating.</p>
<ul>
<li><p>A simple approach is to upper-case every word, but fix some known ones.</p>
<pre><code>name = "georg van trapp"
proper_name = name.title()
proper_name.replace(' Von ', ' von ').replace(' Zu ', ' zu ').replace(' De ', ' de ')
print(name, ':', proper_name)
</code></pre></li>
<li><p>You can do that with a <code>list</code>-and-loop approach for less headache as well:</p>
<pre><code>lc_words = ['von', 'van', 'zu', 'von und zu', 'de', "d'", 'av', 'af', 'der', 'Teer', "'t", "'n", "'s"]
name = "georg van trapp"
proper_name = name.title()
for word in lc_words:
proper_name = proper_name.replace(' %s ' % word.title(), ' %s ' % word)
print(name, ':', proper_name)
</code></pre></li>
<li><p>If names are of the form <code>First Second byword Last</code>, you can capitalize everything but the second-to-last word:</p>
<pre><code>name = "georg fritz ferdinand hannibal van trapp"
proper_name = name.title().split() # gets you the *individual* words, capitalized
proper_name = ' '.join(proper_name[:-2] + [proper_name[-2].lower(), proper_name[-1]])
print(name, ':', proper_name)
</code></pre></li>
<li><p>Any words that are shorter than four letters (warning, not feasible for some names!!!)</p>
<pre><code>name = "georg fritz theodores ferdinand markus hannibal von und zu trapp"
proper_name = ' '.join(word.title() if len(word) > 3 else word.lower() for word in name.split())
print(name, ':', proper_name)
</code></pre></li>
</ul>
| 5 | 2016-10-13T04:11:16Z | [
"python",
"string",
"python-3.x"
] |
Uncapitalizing first letter of a name | 40,012,062 | <p>To code a name like DeAnna you type:</p>
<pre><code>name = "de\aanna"
</code></pre>
<p>and </p>
<pre><code>print(name.title())
</code></pre>
<p>In this code <code>\a</code> capitalizes a normally uncapitalized letter. What do you code to produce a name like <code>"George von Trapp"</code> where I want to uncapitalize a normally capitalized letter?</p>
| 3 | 2016-10-13T03:59:43Z | 40,012,240 | <blockquote>
<p>What do you code to produce a name like <code>"George von Trapp"</code> where I
want to uncapitalize a normally capitalized letter?</p>
</blockquote>
<p>Letters are not auto-capitalized in Python. In your case, <code>"de\aanna"</code>(I think you should use <code>"de anna"</code> instead) is capitalised because you called <code>title()</code> on it. If I didn't misunderstand your question, what you want is simply to disable such "auto-capitalizing".</p>
<p>Just don't call <code>title()</code>:</p>
<pre><code>name = "George von Trapp"
print(name.lower())
</code></pre>
| 0 | 2016-10-13T04:21:55Z | [
"python",
"string",
"python-3.x"
] |
Uncapitalizing first letter of a name | 40,012,062 | <p>To code a name like DeAnna you type:</p>
<pre><code>name = "de\aanna"
</code></pre>
<p>and </p>
<pre><code>print(name.title())
</code></pre>
<p>In this code <code>\a</code> capitalizes a normally uncapitalized letter. What do you code to produce a name like <code>"George von Trapp"</code> where I want to uncapitalize a normally capitalized letter?</p>
| 3 | 2016-10-13T03:59:43Z | 40,012,496 | <p>Why not just roll your own function for it?</p>
<pre><code> def capitalizeName(name):
#split the name on spaces
parts = name.split(" ")
# define a list of words to not capitalize
do_not_cap = ['von']
# for each part of the name,
# force the word to lowercase
# then check if it is a word in our forbidden list
# if it is not, then go ahead and capitalize it
# this will leave words in that list in their uncapitalized state
for i,p in enumerate(parts):
parts[i] = p.lower()
if p.lower() not in do_not_cap:
parts[i] = p.title()
# rejoin the parts of the word
return " ".join(parts)
</code></pre>
<p>The point to the <code>do_not_cap</code> list is that allows you to further define parts you may not want to capitalize very easily. For example, some names may have a "de" in it you may not want capitalized.</p>
<p>This is what it looks like with an example:</p>
<pre><code>name = "geOrge Von Trapp"
capitalizeName(name)
# "George von Trapp"
</code></pre>
| 1 | 2016-10-13T04:49:09Z | [
"python",
"string",
"python-3.x"
] |
elementTree is not opening and parsing my xml file | 40,012,110 | <p>seems like <code>vehicles.write(cars_file)</code> and <code>vehicles = cars_Etree.parse(cars_file)</code> are having a problem with the file name:</p>
<pre><code>import argparse
import xml.etree.ElementTree as cars_Etree
# elementTree not reading xml file properly
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
dest='file_name',
action='store',
help='File name',
metavar='FILE'
)
parser.add_argument(
'car_make', help='car name')
args = parser.parse_args()
with open(args.file_name, 'r') as cars_file:
vehicles = cars_Etree.parse(cars_file)
cars = vehicles.getroot()
for make in cars.findall(args.car_make):
name = make.get('name')
if name != args.car_make:
cars.remove(make)
with open(args.file_name, 'w') as cars_file:
vehicles.write(cars_file)
</code></pre>
<p>Error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/benbitdiddle/PycharmProjects/VehicleFilter/FilterTest.py", line 23, in <module>
vehicles = cars_Etree.parse(cars_file)
File "/Applications/anaconda/lib/python3.5/xml/etree/ElementTree.py", line 1184, in parse
tree.parse(source, parser)
File "/Applications/anaconda/lib/python3.5/xml/etree/ElementTree.py", line 596, in parse
self._root = parser._parse_whole(source)
xml.etree.ElementTree.ParseError: syntax error: line 1, column 0
</code></pre>
<p>XML file, which I am trying to filter, is in the same project folder. I tried supplying the path with the file name and it still didn't work.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<cars>
<make name="toyota">
<model name="tacoma" />
<model name="tundra" />
</make>
<make name="ford">
<model name="escort" />
<model name="taurus" />
</make>
<make name="chevy">
<model name="silverado" />
<model name="volt" />
</make>
</cars>
</code></pre>
| 0 | 2016-10-13T04:05:50Z | 40,038,333 | <p>works fine now but im still improving it. thank you </p>
<p>I made this modification in main.py:</p>
<pre><code>path = "/Users/benbitdiddle/PycharmProjects/VehicleFilter/"
CF = CarFilter(path+args.file_name, args.car_make)
CF.filterCar()
</code></pre>
<p>And changed 'w' to wb' in CarFilter.py class file:</p>
<pre><code> with open(self.file_name, 'wb') as car_file:
self.vehicles.write(car_file)
</code></pre>
| 0 | 2016-10-14T08:19:14Z | [
"python",
"xml",
"argparse",
"elementtree"
] |
How to have one script call and run another one concurrently in python? | 40,012,128 | <p>What I am trying to accomplish is to stream tweets from Twitter for an hour, write the list of tweets to a file, clean and run analysis on the most recent hour of tweets, and then repeat the process indefinitely. </p>
<p>The problem I am running into is that if I run the cleaning and analysis of the tweets in the same script that's handling the streaming - by either hard-coding it or importing the functionality from a module - the whole script waits until these procedures are complete, and then begins again with the streaming. Is there a way to call the cleaning and analysis module within the streaming script so they run concurrently and the streaming doesn't stop while the cleaning and analysis is happening?</p>
<p>I've tried to achieve this by using <code>subprocess.call('python cleaner.py', shell=True)</code> and <code>subprocess.Popen('python cleaner.py', shell=True)</code>, but I don't really know how to use these tools properly, and the two examples above have resulted in the streaming being stopped, <code>cleaner.py</code> being run, and then the streaming resumed.</p>
| 0 | 2016-10-13T04:07:42Z | 40,013,698 | <h2>Subprocess</h2>
<p>You can use <code>subprocess.Popen</code>, as you tried, to run a different script concurrently:</p>
<pre><code>the_other_process = subprocess.Popen(['python', 'cleaner.py'])
</code></pre>
<p>That line alone does what you want. What you <strong>don't want to</strong> do is:</p>
<pre><code>the_other_process.communicate()
# or
the_other_process.wait()
</code></pre>
<p>Those would stop current process and wait for the other one to finish. A very useful feature in other circumstances.</p>
<p>If you want to know whether the subprocess is finished (but not wait for it):</p>
<pre><code>result = the_other_process.poll()
if result is not None:
print('the other process has finished and retuned %s' % result)
</code></pre>
<h2>Thread</h2>
<p>Concurrency can also be achieved using threads. In that case, you are not running a new process, you are just splitting the current process into concurrent parts. Try this:</p>
<pre><code>def function_to_be_executed_concurrently():
for i in range(5):
time.sleep(1)
print('running in separate thread', i)
thread = threading.Thread(target=function_to_be_executed_concurrently)
thread.start()
for i in range(5):
time.sleep(1)
print('running in main thread', i)
</code></pre>
<p>The above code should result with mixed outputs of <code>running in separate thread</code> and <code>running in main thread</code>.</p>
<h2>Thread vs process</h2>
<ul>
<li>Using <code>subprocess</code>, you can run anything which could be run standalone from the shell. It does not have to be python.</li>
<li>Using <code>threading</code>, you can run any function in a concurrent thread of execution.</li>
<li>Threads share the same memory, so it is easy to share data between them (although there are issues when synchronization is needed). With processes, sharing data can become a problem. If a lot of data has to be shared, susbprocesses can be much slower.</li>
<li>Starting a new process is slower and consumes more resources than running a thread</li>
<li>Since threads run in the same process, they share are bound to the same <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">GIL</a>, which means most things will run on the same CPU core. If very slow CPU-consuming tasks need to be sped up, running them in separate processes my be faster.</li>
</ul>
<h2>Multiprocessing</h2>
<p><code>multiprocessing</code> module provides an interface similar to <code>threading</code>, but it runs subprocesses instead. This is useful when you need to take full advantage of all CPU cores.</p>
<hr>
<p>** Note that <code>subprocess.Popen(['python', 'cleaner.py'])</code> is the same thing as <code>subprocess.Popen('python cleaner.py', shell=True)</code>, but the former is better practice to learn.</p>
<p>For example, if there is a space in the path, this will fail:</p>
<pre><code>subprocess.Popen('python My Documents\\cleaner.py', shell=True)
</code></pre>
<p>It fails because it interprets <code>My</code> and <code>Documents\cleaner.py</code> as two separate arguments.</p>
<p>On the other hand, this will work as expected:</p>
<pre><code>subprocess.Popen(['python', 'My Documents\\cleaner.py'])
</code></pre>
<p>It works, because the arguments are explicitly separated by using a list.</p>
<p>The latter is especially superior if one of the arguments is in a variable:</p>
<pre><code>subprocess.Popen(['python', path_to_file])
</code></pre>
| 1 | 2016-10-13T06:24:08Z | [
"python",
"concurrency",
"subprocess"
] |
url encoding in python and sqlite web app | 40,012,153 | <p>am new to python and am trying to build a blog kind of web app, my major problem is that I want the title of the each post to be its link which I would store in my database. I am using the serial number of each post as the url, but it doesn't meet my needs. Any help is appreciated.</p>
| 0 | 2016-10-13T04:10:22Z | 40,012,208 | <p>If I understand your right what you are looking for is to store a slug. There's a package that can help you with this.</p>
<p><a href="https://github.com/un33k/python-slugify" rel="nofollow">https://github.com/un33k/python-slugify</a></p>
<p>Hope it helps!</p>
| 0 | 2016-10-13T04:17:31Z | [
"python",
"url",
"web-applications"
] |
Parsing through JSON file with python and selecting multiple values on certain conditions | 40,012,289 | <p>I have this JSON file. </p>
<pre><code>{
"reviewers":[
{
"user":{
"name":"keyname",
"emailAddress":"John@email",
"id":3821,
"displayName":"John Doe",
"active":true,
"slug":"jslug",
"type":"NORMAL",
"link":{
"url":"/users/John",
"rel":"self"
},
},
"role":"REVIEWER",
"approved":true
},
{
"user":{
"name":"keyname2",
"emailAddress":"Harry@email",
"id":6306,
"displayName":"Harry Smith",
"active":true,
"slug":"slug2",
"link":{
"type":"NORMAL",
"url":"/users/Harry",
"rel":"self"
},
},
"role":"REVIEWER",
"approved":false
}
],
}
</code></pre>
<p>Initially, I was using a snippet of code that would go through and grab the full names of the reviewers. </p>
<pre><code>def get_reviewers(json):
reviewers = ""
for key in json["reviewers"]:
reviewers += key["user"]["displayName"] + ", "
reviewers = reviewers[:-2]
return reviewers
</code></pre>
<p>which would return <code>"John Doe, Harry Smith"</code>. However, now I'm trying to get it so that the script will return a (A) next to the name of the user if their tag equals true <code>"approved"=true</code>.</p>
<p>So for example the code above would get the names, then see that John's approved tag is true and Harry's is false, then return <code>"John Doe(A), Harry Smith"</code>. I'm just not sure where to even begin to do this. Can anyone point me in the right direction?</p>
<p>This is what I've been trying so far but obviously it isn't working as I'd like it to. </p>
<pre><code>def get_reviewers(stash_json):
reviewers = ""
for key in stash_json["reviewers"]:
if stash_json["reviewers"][0]["approved"] == true:
reviewers += key["user"]["displayName"] + "(A)" + ", "
else:
reviewers += key["user"]["displayName"] + ", "
reviewers = reviewers[:-2]
return reviewers
</code></pre>
<p>which outputs <code>Jason Healy(A), Joan Reyes(A)</code></p>
<p>This is what my <code>stash_json</code> outputs when put through pprint. </p>
| 0 | 2016-10-13T04:26:57Z | 40,012,381 | <p>You probably want something along the lines of this:</p>
<pre><code>def get_reviewers(stash_json):
reviewers = ""
for item in stash_json["reviewers"]:
if item["approved"]:
reviewers += item["user"]["displayName"] + "(A)" + ", "
else:
reviewers += item["user"]["displayName"] + ", "
reviewers = reviewers[:-2]
return reviewers
</code></pre>
<p>I think part of your confusion comes from the fact that "reviewers" is a <code>list</code> of <code>dict</code> elements, and each <code>dict</code> element has a key-value <code>approved</code>, but also a key "user" which value itself is another <code>dict</code>.</p>
<hr>
<p>Read the JSON file carefully, and for debugging purposes, use plenty of</p>
<pre><code>print(...)
print(type(...)) # whether something is a dict, list, str, bool etc
</code></pre>
<p>or</p>
<pre><code>from pprint import pprint # pretty printing
pprint(...)
</code></pre>
| 2 | 2016-10-13T04:36:19Z | [
"python",
"json"
] |
Parsing through JSON file with python and selecting multiple values on certain conditions | 40,012,289 | <p>I have this JSON file. </p>
<pre><code>{
"reviewers":[
{
"user":{
"name":"keyname",
"emailAddress":"John@email",
"id":3821,
"displayName":"John Doe",
"active":true,
"slug":"jslug",
"type":"NORMAL",
"link":{
"url":"/users/John",
"rel":"self"
},
},
"role":"REVIEWER",
"approved":true
},
{
"user":{
"name":"keyname2",
"emailAddress":"Harry@email",
"id":6306,
"displayName":"Harry Smith",
"active":true,
"slug":"slug2",
"link":{
"type":"NORMAL",
"url":"/users/Harry",
"rel":"self"
},
},
"role":"REVIEWER",
"approved":false
}
],
}
</code></pre>
<p>Initially, I was using a snippet of code that would go through and grab the full names of the reviewers. </p>
<pre><code>def get_reviewers(json):
reviewers = ""
for key in json["reviewers"]:
reviewers += key["user"]["displayName"] + ", "
reviewers = reviewers[:-2]
return reviewers
</code></pre>
<p>which would return <code>"John Doe, Harry Smith"</code>. However, now I'm trying to get it so that the script will return a (A) next to the name of the user if their tag equals true <code>"approved"=true</code>.</p>
<p>So for example the code above would get the names, then see that John's approved tag is true and Harry's is false, then return <code>"John Doe(A), Harry Smith"</code>. I'm just not sure where to even begin to do this. Can anyone point me in the right direction?</p>
<p>This is what I've been trying so far but obviously it isn't working as I'd like it to. </p>
<pre><code>def get_reviewers(stash_json):
reviewers = ""
for key in stash_json["reviewers"]:
if stash_json["reviewers"][0]["approved"] == true:
reviewers += key["user"]["displayName"] + "(A)" + ", "
else:
reviewers += key["user"]["displayName"] + ", "
reviewers = reviewers[:-2]
return reviewers
</code></pre>
<p>which outputs <code>Jason Healy(A), Joan Reyes(A)</code></p>
<p>This is what my <code>stash_json</code> outputs when put through pprint. </p>
| 0 | 2016-10-13T04:26:57Z | 40,012,524 | <p>This looks like a good place to use <code>join</code> and list comprehension:</p>
<pre><code>def get_reviewers(stash_json):
return ", ".join([item['user']['displayName'] + ('(A)' if item['approved'] else '') for item in stash_json['reviewers']])
</code></pre>
| 0 | 2016-10-13T04:51:03Z | [
"python",
"json"
] |
Authenticate via XMLRPC in Odoo from a PHP system | 40,012,293 | <p>I would like to authenticate into Odoo via xmlrpc but as a SSO kind of implementation. The credentials of the users will be the same in both Odoo and PHP, so basically there will be a redirection to Odoo from the php system when the user is logged in there. The thing is since the passwords are hashed at both the PHP and Odoo side, there is no way to pass the password from php to odoo. I know that authentication can be done if the username and password is passed, but this isnt the case here, so is there any way to implement an SSO for the above scenario?</p>
<p>Thanks And Regards,</p>
<p>Yaseen Shareef</p>
| 0 | 2016-10-13T04:27:14Z | 40,014,473 | <p>Odoo supports other authentication mechanisms than local passwords, out-of-the-box:</p>
<ul>
<li>LDAP authentication is provided by the built-in <a href="https://www.odoo.com/apps/modules/8.0/auth_ldap/" rel="nofollow"><code>auth_ldap</code></a> module. It requires an external LDAP service, such as <a href="http://www.openldap.org" rel="nofollow">openldap</a> or a Microsoft Active Directory. It works at the XML-RPC level as well, because it is a password-based mechanism.</li>
<li>OAuth2 authentication is provided by the built-in <a href="https://www.odoo.com/apps/modules/8.0/auth_oauth/" rel="nofollow"><code>auth_oauth</code></a> module. It requires an external OAuth2 provider, such as Google or Facebook accounts. This does not work transparently at the XML-RPC level, because it is not strictly password-based. You need to do the OAuth authentication of an HTTP session first, and then you can use the JSON-RPC API to remotely access Odoo as you would with XML-RPC.</li>
<li>Odoo 8 also includes built-in support for OpenID integration, via the <a href="https://www.odoo.com/apps/modules/8.0/auth_openid/" rel="nofollow"><code>auth_openid</code></a> module. This requires an external OpenID service, but has been deprecated as of Odoo 9 in favor of the equivalent OAuth services. Similarly to OAuth, it is not password-based so it will not work at the XML-RPC level directly.</li>
</ul>
<p>The Odoo API is fully accessible through either XML-RPC or JSON-RPC, these are strictly equivalent. There are RPC libraries for each in most languages, and popular languages often have dedicated Odoo RPC libraries.</p>
<p>You can easily achieve SSO on Odoo and your PHP application by using one of these external authentication mechanisms, as there are PHP libraries for each of them. You just need to choose a suitable provider for your case.</p>
<p>In addition third-party community modules exist for other authentication mechanism (look <a href="https://github.com/OCA/server-tools/tree/8.0" rel="nofollow">here</a> for starters). For example, for version 7.0 there was a module that would authenticate in Odoo based on the HTTP Basic authentication (<code>auth_from_http_basic</code>), allowing for SSO based on the web server' pluggable authentication. I don't think it was ported for version 8, but you can perhaps contact the authors and help get it done.</p>
| 0 | 2016-10-13T07:09:33Z | [
"php",
"python",
"openerp",
"odoo-8",
"xml-rpc"
] |
How to add numbers to x axis instead of year in morris line chart? | 40,012,355 | <p>I have added morris line chart in my python project. I want x-axis in the interval of 5-10-15-20-15-30. And not in the year format. How to do it?</p>
<pre><code>$(document).ready(function(){
Morris.Line({
element: 'line-example',
data: [
{ y: '5', a: {{count5}}, b: {{count11}} },
{ y: '10', a: {{count6}} , b: {{count12}} },
{ y: '15', a: {{count7}}, b: {{count13}} },
{ y: '20', a: {{count8}}, b: {{count14}} },
{ y: '25', a: {{count9}}, b: {{count15}} },
{ y: '30', a: {{count10}} , b: {{count16}} }
],
xkey: 'y',
ykeys: ['a','b'],
labels: ['Customer Added','Reqest Received']
});
});
</code></pre>
| 0 | 2016-10-13T04:34:15Z | 40,015,984 | <p>Simply set the <code>parseTime</code> parameter to <code>false</code>:</p>
<pre><code>parseTime: false
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Morris.Line({
element: 'line-example',
data: [
{ y: '5', a: 2, b: 3 },
{ y: '10', a: 5, b: 15 },
{ y: '15', a: 30, b: 8 },
{ y: '20', a: 100, b: 35 },
{ y: '25', a: 50, b: 10 },
{ y: '30', a: 20, b: 30 }
],
xkey: 'y',
ykeys: ['a', 'b'],
labels: ['Customer Added', 'Reqest Received'],
parseTime: false
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://cdn.oesmith.co.uk/morris-0.5.1.min.js"></script>
<link href="http://cdn.oesmith.co.uk/morris-0.5.1.css" rel="stylesheet"/>
<div id="line-example"></div></code></pre>
</div>
</div>
</p>
| 1 | 2016-10-13T08:31:03Z | [
"python",
"html",
"jquery-ui",
"morris.js"
] |
django models manager for content type models | 40,012,394 | <p>I am currently writing a Django Application to contain all the Content Type Models(generic relations)</p>
<pre><code>from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core.validators import RegexValidator
class AddressManager(models.Manager) :
def create_address(self, content_obj, address1, address2, postal_code):
address = Address(content_object = content_obj,
address1 = address1,
address2 = address2,
postal_code = postal_code)
address.save()
return address
class Address(models.Model):
address1 = models.CharField(max_length=100, default=None)
address2 = models.CharField(max_length=100, default=None)
postal_code = models.TextField(default=None)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,
default=None, null=True)
object_id = models.PositiveIntegerField(default=None, null=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = AddressManager()
</code></pre>
<p>When I use this on local server, it serves its purpose well.</p>
<p>However, when I run</p>
<p>python manage.py test</p>
<p>This error occurs</p>
<pre><code>======================================================================
ERROR: test_address__custom_methods (genericmodels.tests.test_models.TestBasic)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/path/genericmodels/tests/test_models.py", line 15, in test_address__custom_methods
"t_postal_code")
File "/path/genericmodels/models.py", line 11, in create_address
postal_code = postal_code)
File "/path/env3/lib/python3.5/site-packages/django/db/models/base.py", line 555, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'content_object' is an invalid keyword argument for this function
----------------------------------------------------------------------
Ran 1 test in 0.310s
FAILED (errors=1)
Destroying test database for alias 'default'...
</code></pre>
<p>The test code is as follows :</p>
<pre><code>from django.test import TestCase
from unittest.mock import MagicMock
from genericmodels.models import *
from anotherapp.models import User_Info
class TestBasic(TestCase):
""" Basic tests for Address model"""
def test_address__custom_methods(self):
user_info = MagicMock(User_Info)
address = Address.objects.create_address(user_info,
"t_address1",
"t_address2",
"t_postal_code")
self.assertEqual(Address.objects.count(), 1)
self.assertEqual(address.address1, "t_address1")
</code></pre>
| 0 | 2016-10-13T04:38:09Z | 40,012,923 | <p>Thanks to <a href="http://stackoverflow.com/users/5662309/ticktomp">TickTomp</a> I was able to figure out that instead of making a MagicMock(User_Info), I should have actually made an instance of User_Info class to test. The test ran fine afterwards...</p>
| 0 | 2016-10-13T05:27:22Z | [
"python",
"django",
"django-models",
"django-testing"
] |
Append to a list of dictionaries in python | 40,012,415 | <pre><code>self.LOG_DIR_LIST_BACKEND = [AMPLI_LOG, VAR_LOG, CORE_DUMP_LOG]
backend_nodes = [backend-1, backend-2, backend-3]
self.log_in_nodes = []
log_file = {}
for LOG_DIR_BACKEND in self.LOG_DIR_LIST_BACKEND:
for node_backend in backend_nodes:
log_in_nodes 'find %s -type f -name \"*log.*.gz\"' % LOG_DIR_BACKEND
log_file[node_backend] = log_in_nodes
self.log_in_nodes.append(log_file)
print "Logs are ", self.log_in_nodes
</code></pre>
<p>Expected output : </p>
<pre><code>[{backend-1: AMPLI_LOG, VAR_LOG, CORE_DUMP_LOG, backend-2: AMPLI_LOG, VAR_LOG, CORE_DUMP_LOG, backend-3: AMPLI_LOG, VAR_LOG, CORE_DUMP_LOG}]
</code></pre>
<p>When I print self.log_in_nodes, the output is everytime new, it is not appending. What am i doing wrong?</p>
| -1 | 2016-10-13T04:39:46Z | 40,012,793 | <p>Every time you run this method, it will reset <code>self.log_in_nodes</code>, because you are doing:</p>
<pre><code>self.log_in_nodes = []
</code></pre>
<p>If you want to append stuff to that list, either make this like a class variable or put it outside the class, and initialize only once.</p>
<p>Option one:</p>
<pre><code> class Foo
log_in_nodes = []
def your_method(self ...):
log_file = {}
for LOG_DIR_BACKEND in self.LOG_DIR_LIST_BACKEND:
for node_backend in backend_nodes:
....
self.log_in_nodes.append(log_file)
</code></pre>
<p>Option 2:
LOG_IN_NODES = []</p>
<pre><code> class Foo
def your_method(self ...):
log_file = {}
for LOG_DIR_BACKEND in self.LOG_DIR_LIST_BACKEND:
for node_backend in backend_nodes:
....
LOG_IN_NODES.append(log_file)
</code></pre>
<p>In both cases the list is initialized once, and appended every time you call the method.</p>
<h3>side notes:</h3>
<p>What is this: </p>
<pre><code>log_in_nodes 'find %s -type f -name \"*log.*.gz\"' % LOG_DIR_BACKEND`
^^^^^^^^^^^^ Did you miss type this? forget an assignment?
</code></pre>
<p>probably you meant:</p>
<pre><code>log_in_nodes = 'find %s -type f -name \"*log.*.gz\"' % LOG_DIR_BACKEND
</code></pre>
<p>Instead of:</p>
<pre><code>backend_nodes = [backend-1, backend-2, backend-3]
</code></pre>
<p>You can do:</p>
<pre><code>backend_nodes = range(backend - 1, backend - 4, -1)
</code></pre>
<p>although not really shorter, it is immediately clear what it is doing, compared to the way you wrote the code.</p>
| 0 | 2016-10-13T05:15:04Z | [
"python"
] |
python : cant open file 'hw.py': [Errno 2] No such file or directory | 40,012,445 | <p><a href="https://i.stack.imgur.com/HyEHd.png" rel="nofollow">here my output looks like, please see this image</a>as I m new in this programing world, I m trying to do some python code, but it seems like my raspberry pi doesn't recognise my folder
here it looks like
python : cant open file 'hw.py': [Errno 2] No such file or directory
my path and folder is existed, and I save the file by .py extension still it shows not found , please help me guys....</p>
<pre><code>pi@raspberrypi :~/codes $ ls
hello hw.py
pi@raspberrypi :~/codes $ python hw.py
python : cant open file 'hw.py': [Errno 2] No such file or directory
</code></pre>
<p>hw.py file contains:-
print "hello world"</p>
<p>IT CLEARLY SHOWS MY FILE "HW.PY" IS IN THAT FOLDER, BUT STILL RASPBERRY PI DOESN'TRECOGNIZING IT ? HELP ME GUYS </p>
| -1 | 2016-10-13T04:42:59Z | 40,012,468 | <p>Okay so you need to save the file in the same directory as your IDE.</p>
| 0 | 2016-10-13T04:46:23Z | [
"python",
"opencv",
"raspberry-pi",
"raspberry-pi3"
] |
replace values in list of python dictionaries | 40,012,502 | <p>So I have a huge list of dictionaries and I want to: </p>
<ul>
<li>change asterixs into the integer "4"</li>
<li>change all spaces "" to the integer "0"</li>
<li>change all other numbers to integers</li>
</ul>
<p>(this is only a portion of the list)</p>
<pre><code> clean_dict= [{'origin': 'Various/Unknown', 'idps': '', 'year': '1951', 'total': '180000', 'stateless': '', 'ret_refugees': '', 'asylum': '', 'country': 'Australia', 'others': '', 'ret_idps': '', 'refugees': '180000'}, {'origin': 'Various/Unknown', 'idps': '', 'year': '1951', 'total': '282000', 'stateless': '', 'ret_refugees': '', 'asylum': '', 'country': 'Austria', 'others': '', 'ret_idps': '', 'refugees': '282000'}]
</code></pre>
<p>I tried this code but nothing happened, any help is very appreciated! </p>
<p>Also <code>pandas</code> library is not allowed for this assignment.</p>
<pre><code> for name, datalist in clean_data.iteritems():
for datadict in datalist:
for key, value in datadict.items():
if value == "*":
datadict[key] = int(4)
elif value == "":
datadict[key]= int(0)
else:
value == int(value)
</code></pre>
| 0 | 2016-10-13T04:49:25Z | 40,012,963 | <p>I guess this is what you want.</p>
<pre><code>clean_dict= [{'origin': 'Various/Unknown', 'idps': '', 'year': '1951', 'total': '180000', 'stateless': '', 'ret_refugees': '', 'asylum': '', 'country': 'Australia', 'others': '', 'ret_idps': '', 'refugees': '180000'}, {'origin': 'Various/Unknown', 'idps': '', 'year': '1951', 'total': '282000', 'stateless': '', 'ret_refugees': '', 'asylum': '', 'country': 'Austria', 'others': '', 'ret_idps': '', 'refugees': '282000'}]
for datadict in clean_dict:
for key, value in datadict.items():
if value == '*':
datadict[key] = 4
elif value == '':
datadict[key] = 0
else:
try:
datadict[key] = int(value)
except:
continue
</code></pre>
<p>Changes explained:</p>
<ul>
<li><code>int(4)</code> or <code>int(0)</code> is unneccessary. </li>
<li><code>value == int(value)</code> does nothing, i.e, it doesn't update your list or dictionary.</li>
<li><code>for name, datalist in clean_data.iteritems():</code> name is unused and also this does not help to update your list.</li>
<li><code>try</code> and <code>except:</code> is used because string value such as <code>Australia</code> cannot be converted to <code>int</code> type.</li>
</ul>
| 0 | 2016-10-13T05:30:43Z | [
"python",
"list",
"dictionary",
"replace"
] |
replace values in list of python dictionaries | 40,012,502 | <p>So I have a huge list of dictionaries and I want to: </p>
<ul>
<li>change asterixs into the integer "4"</li>
<li>change all spaces "" to the integer "0"</li>
<li>change all other numbers to integers</li>
</ul>
<p>(this is only a portion of the list)</p>
<pre><code> clean_dict= [{'origin': 'Various/Unknown', 'idps': '', 'year': '1951', 'total': '180000', 'stateless': '', 'ret_refugees': '', 'asylum': '', 'country': 'Australia', 'others': '', 'ret_idps': '', 'refugees': '180000'}, {'origin': 'Various/Unknown', 'idps': '', 'year': '1951', 'total': '282000', 'stateless': '', 'ret_refugees': '', 'asylum': '', 'country': 'Austria', 'others': '', 'ret_idps': '', 'refugees': '282000'}]
</code></pre>
<p>I tried this code but nothing happened, any help is very appreciated! </p>
<p>Also <code>pandas</code> library is not allowed for this assignment.</p>
<pre><code> for name, datalist in clean_data.iteritems():
for datadict in datalist:
for key, value in datadict.items():
if value == "*":
datadict[key] = int(4)
elif value == "":
datadict[key]= int(0)
else:
value == int(value)
</code></pre>
| 0 | 2016-10-13T04:49:25Z | 40,013,033 | <p>Assuming you're using Python 3 try this. For Python 2.x the main difference is to use <code>iteritems()</code> instead of <code>items()</code> but the rest should remain the same.</p>
<pre><code>for dict in clean_dict:
for k,v in dict.items():
if v == '*':
dict[k] = 4
elif v == '':
dict[k]= 0
else:
# not necessarily an integer so handle exception
try:
dict[k] = int(v)
except ValueError:
pass
</code></pre>
| 0 | 2016-10-13T05:36:21Z | [
"python",
"list",
"dictionary",
"replace"
] |
Extract keys from elasticsearch result and store in other list | 40,012,550 | <p>I have a ES returned list stored in a dict </p>
<pre><code>res = es.search(index="instances-i*",body=doc)
</code></pre>
<p>The result returned by res looks like: </p>
<pre><code>{
"took": 34,
"timed_out": false,
"_shards": {
"total": 1760,
"successful": 1760,
"failed": 0
},
"hits": {
"total": 551,
"max_score": 0.30685282,
"hits": [
{
"_index": "instances-i-0034438e-2016.10.10-08:23:51",
"_type": "type_name",
"_id": "1",
"_score": 0.30685282,
"_source": {
"ansible.isv_alias": "ruiba",
"ansible": {
"isv_alias": "ruiba",
"WEB_URL": "sin01-cloud.trial.sentinelcloud.com/ruiba"
}
}
}
,
{
"_index": "instances-i-0034438e-2016.10.11-08:23:54",
"_type": "type_name",
"_id": "1",
"_score": 0.30685282,
"_source": {
"ansible.isv_alias": "aike3",
"ansible": {
"isv_alias": "aike3",
"WEB_URL": "sin01-cloud.trial.cloud.com/aike3"
}
}
}
,
{
"_index": "instances-i-883sf38e-2016.10.12-08:23:45",
"_type": "type_name",
"_id": "1",
"_score": 0.30685282,
"_source": {
"ansible.isv_alias": "beijing",
"ansible": {
"isv_alias": "beijing",
"WEB_URL": "sin01-cloud.trial.cloud.com/beijing"
}
}
}
.
.
.
.
so on
</code></pre>
<p>I need to extract the WEB_URL from the returned dict and store it in a LIST. </p>
<p>Also i am curious if we can actually make sure that there is no DUPLICATE ENTRY OF The value of WEB_URL in the LIST being populated {This is 2nd part though}</p>
| 0 | 2016-10-13T04:53:17Z | 40,013,118 | <p>To store the value of <code>WEB_URL</code> you need to iterate over the dictionary-</p>
<pre><code>data = response_from_es['hits']
list_of_urls = []
for item in data['hits']:
list_of_urls.append(item['_source']['ansible']['WEB_URL'])
print list_of_urls
</code></pre>
<p>And to make the <code>list_of_urls unique</code> -> <code>set(list_of_urls)</code></p>
| 3 | 2016-10-13T05:41:28Z | [
"python",
"dictionary"
] |
Trouble sending np.zeros through to tf.placeholder | 40,012,599 | <p>I've been learning tensorflow recently and I'm having trouble sending the appropriately sized and typed numerical data through to the placeholder in tensorflow. This code has been adapted from <a href="https://github.com/SullyChen/Nvidia-Autopilot-TensorFlow" rel="nofollow">https://github.com/SullyChen/Nvidia-Autopilot-TensorFlow</a>.</p>
<p>My model file:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import scipy
from tensorflow.python.ops import rnn, rnn_cell
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W, stride):
return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding='VALID')
class AutopilotRCNModel(object):
"""
Use Recurrent Neural Networks in combination with Convolutional Neural
Networks to predict steering wheel angle.
"""
def __init__(self, n_hidden=50):
# Create a state variable to be passed in through feed_dict
self.c_state = tf.placeholder(tf.float32, shape=[1, n_hidden])
self.h_state = tf.placeholder(tf.float32, shape=[1, n_hidden])
# Do the same with the input x and the target variable y_
self.x = tf.placeholder(tf.float32, shape=[None, 66, 200, 3])
self.y_ = tf.placeholder(tf.float32, shape=[None, 1])
x_image = self.x
# First convolutional layer.
W_conv1 = weight_variable([5, 5, 3, 24])
b_conv1 = bias_variable([24])
# Stride is 2.
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1, 2) + b_conv1)
# Second convolutional layer.
W_conv2 = weight_variable([5, 5, 24, 36])
b_conv2 = bias_variable([36])
# Stride still set to 2.
h_conv2 = tf.nn.relu(conv2d(h_conv1, W_conv2, 2) + b_conv2)
# Third convolutional layer.
W_conv3 = weight_variable([5, 5, 36, 48])
b_conv3 = bias_variable([48])
# Stride still 2.
h_conv3 = tf.nn.relu(conv2d(h_conv2, W_conv3, 2) + b_conv3)
# Fourth convolutional layer.
W_conv4 = weight_variable([3, 3, 48, 64])
b_conv4 = bias_variable([64])
# Stride now set to 1.
h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4, 1) + b_conv4)
# Fifth convolutional layer.
W_conv5 = weight_variable([3, 3, 64, 64])
b_conv5 = bias_variable([64])
# Stride of 1.
h_conv5 = tf.nn.relu(conv2d(h_conv4, W_conv5, 1) + b_conv5)
# Fully connected layer 1.
W_fc1 = weight_variable([1152, 1164])
b_fc1 = bias_variable([1164])
# Requires flattening out the activations.
h_conv5_flat = tf.reshape(h_conv5, [-1, 1152])
h_fc1 = tf.nn.relu(tf.matmul(h_conv5_flat, W_fc1) + b_fc1)
self.keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, self.keep_prob)
# Fully connected layer 2.
W_fc2 = weight_variable([1164, 100])
b_fc2 = bias_variable([100])
h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
h_fc2_drop = tf.nn.dropout(h_fc2, self.keep_prob)
print(h_fc2_drop.get_shape())
# LSTM layer 1
# Create weight matrix and bias to map from output of LSTM
# to steering wheel angle in radians.
# Input gate input weights, recurrent weights, and bias.
W_i = weight_variable([100, n_hidden])
U_i = weight_variable([n_hidden, n_hidden])
b_i = bias_variable([n_hidden])
# Forget gate input weights, recurrent weights, and bias.
W_f = weight_variable([100,n_hidden])
U_f = weight_variable([n_hidden, n_hidden])
b_f = bias_variable([n_hidden])
# Candidate gate input weights, recurrent weights, and bias.
W_c = weight_variable([100, n_hidden])
U_c = weight_variable([n_hidden,n_hidden])
b_c = bias_variable([n_hidden])
# Output gate input weights, recurrent weights and bias.
W_o = weight_variable([100, n_hidden])
U_o = weight_variable([n_hidden, n_hidden])
b_o = bias_variable([1])
V_o = weight_variable([n_hidden, n_hidden])
ingate = tf.nn.sigmoid(tf.matmul(h_fc2_drop, W_i) + tf.matmul(self.h_state, U_i) + b_i)
cgate = tf.nn.tanh(tf.matmul(h_fc2_drop, W_c) + tf.matmul(self.h_state, U_c) + b_c)
fgate = tf.nn.sigmoid(tf.matmul(h_fc2_drop, W_f) + tf.matmul(self.h_state, U_f) + b_f)
self.c_state = tf.mul(ingate, cgate) + tf.mul(fgate, self.c_state)
h_rnn1 = tf.nn.sigmoid(tf.matmul(h_fc2_drop, W_o) + \
tf.matmul(self.h_state, U_o) + tf.matmul(self.c_state, V_o) + b_o)
self.h_state = tf.mul(h_rnn1, tf.nn.tanh(self.c_state))
W_out = weight_variable([n_hidden,1])
b_out = bias_variable([1])
self.y = tf.mul(tf.atan(tf.matmul(h_rnn1, W_out) + b_out), 2)
self.loss = tf.square(tf.sub(self.y, self.y_))
</code></pre>
<p>First tester code is here:</p>
<pre class="lang-py prettyprint-override"><code>import model
import driving_data
import tensorflow as tf
import numpy as np
n_hidden = 65
rcn = model.AutopilotRCNModel(n_hidden=n_hidden)
xs, ys = driving_data.LoadTrainBatch(1)
c_state = np.zeros((1,n_hidden),dtype=np.float32)
h_state = np.zeros((1,n_hidden),dtype=np.float32)
sess = tf.InteractiveSession()
train_step = tf.train.AdamOptimizer().minimize(rcn.loss)
sess.run(tf.initialize_all_variables())
train_step.run(
feed_dict = {
rcn.x: xs,
rcn.y_: ys,
rcn.keep_prob: 0.8,
rcn.c_state: c_state,
rcn.h_state: h_state
}
)
</code></pre>
<p>and I'm getting this error:</p>
<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
File "test.py", line 28, in <module>
rcn.h_state: h_state
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1621, in run
_run_using_default_session(self, feed_dict, self.graph, session)
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3804, in _run_using_default_session
session.run(operation, feed_dict)
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 717, in run
run_metadata_ptr)
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 915, in _run
feed_dict_string, options, run_metadata)
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 965, in _do_run
target_list, options, run_metadata)
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 985, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [1,65]
[[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[1,65], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
[[Node: _recv_add_13_0 = _Recv[client_terminated=true, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=7747556615882019196, tensor_name="add_13:0", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op u'Placeholder', defined at:
File "test.py", line 9, in <module>
rcn = model.AutopilotRCNModel(n_hidden=n_hidden)
File "/home/thomas/projects/lstm_autopilot/model.py", line 27, in __init__
self.c_state = tf.placeholder(tf.float32, shape=[1, n_hidden])
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.py", line 1330, in placeholder
name=name)
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1762, in _placeholder
name=name)
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 748, in apply_op
op_def=op_def)
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2388, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/thomas/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1300, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [1,65]
[[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[1,65], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
[[Node: _recv_add_13_0 = _Recv[client_terminated=true, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=7747556615882019196, tensor_name="add_13:0", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code></pre>
<p>My actual numeric feed_dict data is the same shape and type as the placeholder requires. Not really sure what's wrong here. I would think <code>np.zeros((1,n_hidden), dtype=np.float32)</code> should feed the <code>tf.placeholder(tf.float32,size=[1,n_hidden])</code> quite well.</p>
| 0 | 2016-10-13T04:57:28Z | 40,013,261 | <p>My problem was that I was updating the placeholder inside the class, a definite no-no. I just changed </p>
<pre><code>self.c_state = tf.mul(ingate, cgate) + tf.mul(fgate, self.c_state)
</code></pre>
<p>to</p>
<pre><code>self.new_c_state = tf.mul(ingate, cgate) + tf.mul(fgate, self.c_state)
</code></pre>
<p>and</p>
<pre><code>self.h_state = tf.mul(h_rnn1, tf.nn.tanh(self.c_state))
</code></pre>
<p>to</p>
<pre><code>self.new_h_state = tf.mul(h_rnn1, tf.nn.tanh(self.new_c_state))
</code></pre>
<p>!!! It all makes sense. Placeholders are placeholders for data. Don't do update operations on them or things get all screwy.</p>
| 0 | 2016-10-13T05:51:51Z | [
"python",
"numpy",
"tensorflow"
] |
Generate meaningful text from random letters | 40,012,656 | <p>Is there's someway to generate a meaningful text from random letters
as ex. if I type </p>
<blockquote>
<p>sbras</p>
</blockquote>
<p>the program should give this or something similar </p>
<blockquote>
<p>saber</p>
</blockquote>
<p>if the above request can't get a good answer , then</p>
<p>I like the generated text and/or numbers on screens in hack & technologies movies</p>
<p>is there's someway to generate a text or numbers , I mean with typing animations</p>
<p>I can use my own text and numbers in python <code>print</code> but won't give me the typing animations like movies </p>
<p>if the above requests can done in python ,that will be great</p>
<p>but if can done in other language , I will be thankful too</p>
| -1 | 2016-10-13T05:03:41Z | 40,013,325 | <p>As for your first question: Well, that depends on how specifically you want it. If you want to do it real-time, i.e. you want proper words to appear as you type random stuff, well, good luck with that. If you have a text with random letters, you could afterwards look for proper anagrams of every word in the text. You will require a list of proper words to see if they are anagrams, however. </p>
<p>Note that also "a sentence with proper words" is a completely different thing than "a proper sentence". The former is done relatively easy with enough time and effort, while the latter is (close to) impossible to do, as you require your program to have knowledge of both grammar and the type of words (i.e. noun, verb, preposition...).</p>
<p>As for your second question, print is indeed instant. However, you could use the <code>time</code> module to get the wanted effect. One example:</p>
<pre><code>import time
import sys
sentence = "The quick brown fox jumps over the lazy dog"
for c in sentence:
sys.stdout.write(c)
time.sleep(0.1)
</code></pre>
<p>You can adjust the 0.1 to your liking - it's the sleep time in seconds. You could even make it random within some interval. For the reason I used <code>sys.stdout.write</code> as opposed to <code>print c</code> or <code>print c,</code> see <a href="http://stackoverflow.com/questions/255147/how-do-i-keep-python-print-from-adding-newlines-or-spaces">this question</a>.</p>
| 0 | 2016-10-13T05:57:52Z | [
"python",
"random",
"programming-languages",
"dynamically-generated"
] |
Problems while installing StanfordCoreNLP in OSX: How to set up the environment variables for jupyter/pycharm? | 40,012,711 | <p>I downloaded and installed the <a href="http://nlp.stanford.edu/software/CRF-NER.shtml" rel="nofollow">StanfordCoreNLP</a> as <a href="https://gist.github.com/alvations/e1df0ba227e542955a8a" rel="nofollow">follows</a>:</p>
<pre><code>$ cd
$ wget http://nlp.stanford.edu/software/stanford-ner-2015-12-09.zip
$ unzip stanford-ner-2015-12-09.zip
$ ls stanford-ner-2015-12-09/
build.xml LICENSE.txt ner-gui.bat ner.sh sample.ner.txt stanford-ner-3.6.0.jar stanford-ner.jar
classifiers ner.bat ner-gui.command README.txt sample.txt stanford-ner-3.6.0-javadoc.jar
lib NERDemo.java ner-gui.sh sample-conll-file.txt sample-w-time.txt stanford-ner-3.6.0-sources.jar
$ export STANFORDTOOLSDIR=$HOME
$ export CLASSPATH=$STANFORDTOOLSDIR/stanford-ner-2015-12-09/stanford-ner.jar
$ export STANFORD_MODELS=$STANFORDTOOLSDIR/stanford-ner-2015-12-09/classifiers
</code></pre>
<p>Then let's try if it actually worked:</p>
<pre><code>$ python3
>>>import nltk
>>> nltk.__version__
'3.1'
>>> from nltk.tag import StanfordNERTagger
>>> st = StanfordNERTagger('english.all.3class.distsim.crf.ser.gz')
>>> st.tag('Rami Eid is studying at Stony Brook University in NY'.split())
[('Rami', 'PERSON'), ('Eid', 'PERSON'), ('is', 'O'), ('studying', 'O'), ('at', 'O'), ('Stony', 'ORGANIZATION'), ('Brook', 'ORGANIZATION'), ('University', 'ORGANIZATION'), ('in', 'O'), ('NY', 'O')]
</code></pre>
<p>So, upon here everything works perfect. The problem is when I close the terminal and start working in the jupyter notebook (or pycharm):</p>
<p>In:</p>
<pre><code>from nltk.tag import StanfordNERTagger
st = StanfordNERTagger('english.all.3class.distsim.crf.ser.gz')
st.tag('Rami Eid is studying at Stony Brook University in NY'.split())
</code></pre>
<p>Out:</p>
<pre><code>---------------------------------------------------------------------------
LookupError Traceback (most recent call last)
<ipython-input-2-118c7edca797> in <module>()
1 from nltk.tag import StanfordNERTagger
----> 2 st = StanfordNERTagger('english.all.3class.distsim.crf.ser.gz')
3 st.tag('Rami Eid is studying at Stony Brook University in NY'.split())
/usr/local/lib/python3.5/site-packages/nltk/tag/stanford.py in __init__(self, *args, **kwargs)
166
167 def __init__(self, *args, **kwargs):
--> 168 super(StanfordNERTagger, self).__init__(*args, **kwargs)
169
170 @property
/usr/local/lib/python3.5/site-packages/nltk/tag/stanford.py in __init__(self, model_filename, path_to_jar, encoding, verbose, java_options)
51 self._JAR, path_to_jar,
52 searchpath=(), url=_stanford_url,
---> 53 verbose=verbose)
54
55 self._stanford_model = find_file(model_filename,
/usr/local/lib/python3.5/site-packages/nltk/__init__.py in find_jar(name_pattern, path_to_jar, env_vars, searchpath, url, verbose, is_regex)
717 searchpath=(), url=None, verbose=True, is_regex=False):
718 return next(find_jar_iter(name_pattern, path_to_jar, env_vars,
--> 719 searchpath, url, verbose, is_regex))
720
721
/usr/local/lib/python3.5/site-packages/nltk/__init__.py in find_jar_iter(name_pattern, path_to_jar, env_vars, searchpath, url, verbose, is_regex)
712 (name_pattern, url))
713 div = '='*75
--> 714 raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))
715
716 def find_jar(name_pattern, path_to_jar=None, env_vars=(),
LookupError:
===========================================================================
NLTK was unable to find stanford-ner.jar! Set the CLASSPATH
environment variable.
For more information, on stanford-ner.jar, see:
<http://nlp.stanford.edu/software>
===========================================================================
</code></pre>
<p><strong>So, my question is how to set the environment variables correctly?</strong>, I also tried to add this to my bash profile:</p>
<pre><code>#StanfordCORENLP
export STANFORDTOOLSDIR=$HOME
export CLASSPATH=$STANFORDTOOLSDIR/stanford-ner-2015-12-09/stanford-ner.jar
export STANFORD_MODELS=$STANFORDTOOLSDIR/stanford-ner-2015-12-09/classifiers
</code></pre>
<p><strong>Update</strong></p>
<p>Based on @alexis answer, this is what I tried:</p>
<pre><code>user@MacBook-Pro:~$ % jupyter notebook /Users/user/Jupyter/Project1/Version1 &
-bash: bg: %: no such job
-bash: bg: jupyter: no such job
-bash: bg: notebook: no such job
-bash: bg: /Users/user/Jupyter/Project1/Version1: no such job
</code></pre>
<p>And this:</p>
<pre><code>user@MacBook-Pro-de-User:~$ sudo mate /etc/launchd.conf
Password:
path::entries: scandir("/Applications/TextMate.app/Contents/Resources/PrivilegedTool"): Not a directory
</code></pre>
<p>Then:</p>
<pre><code>user@MacBook-Pro-de-User:~$ sudo mate /etc/launchd.conf
Password:
path::entries: scandir("/Applications/TextMate.app/Contents/Resources/PrivilegedTool"): Not a directory
</code></pre>
<p>Then in the text editor:</p>
<pre><code>#StanfordCORENLP
setenv export STANFORDTOOLSDIR=$HOME
setenv export CLASSPATH=$STANFORDTOOLSDIR/stanford-ner-2015-12-09/stanford-ner.jar
setenv export STANFORD_MODELS=$STANFORDTOOLSDIR/stanford-ner-2015-12-09/classifiers
</code></pre>
<p><strong>Update2</strong></p>
<p>I tried the following:</p>
<pre><code>user@MacBook-Pro-de-User:~$ jupyter notebook /Users/user/Jupyter/Project1/Version1 & /Users/user/stanford-ner-2015-12-09
</code></pre>
<p>Then:</p>
<pre><code>---------------------------------------------------------------------------
LookupError Traceback (most recent call last)
<ipython-input-1-215fd2418c10> in <module>()
1 from nltk.tag import StanfordNERTagger
----> 2 st = StanfordNERTagger('english.all.3class.distsim.crf.ser.gz')
3 #st = StanfordNERTagger('/home/me/stanford/stanford-postagger-full-2015-04-20/classifier/tagger.ser.gz',\
4 #'/home/me/stanford/stanford-spanish-corenlp-2015-01-08-models.jar')
5 st.tag('Rami Eid is studying at Stony Brook University in NY'.split())
/usr/local/lib/python3.5/site-packages/nltk/tag/stanford.py in __init__(self, *args, **kwargs)
166
167 def __init__(self, *args, **kwargs):
--> 168 super(StanfordNERTagger, self).__init__(*args, **kwargs)
169
170 @property
/usr/local/lib/python3.5/site-packages/nltk/tag/stanford.py in __init__(self, model_filename, path_to_jar, encoding, verbose, java_options)
51 self._JAR, path_to_jar,
52 searchpath=(), url=_stanford_url,
---> 53 verbose=verbose)
54
55 self._stanford_model = find_file(model_filename,
/usr/local/lib/python3.5/site-packages/nltk/__init__.py in find_jar(name_pattern, path_to_jar, env_vars, searchpath, url, verbose, is_regex)
717 searchpath=(), url=None, verbose=True, is_regex=False):
718 return next(find_jar_iter(name_pattern, path_to_jar, env_vars,
--> 719 searchpath, url, verbose, is_regex))
720
721
/usr/local/lib/python3.5/site-packages/nltk/__init__.py in find_jar_iter(name_pattern, path_to_jar, env_vars, searchpath, url, verbose, is_regex)
712 (name_pattern, url))
713 div = '='*75
--> 714 raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))
715
716 def find_jar(name_pattern, path_to_jar=None, env_vars=(),
LookupError:
===========================================================================
NLTK was unable to find stanford-ner.jar! Set the CLASSPATH
environment variable.
For more information, on stanford-ner.jar, see:
<http://nlp.stanford.edu/software>
===========================================================================
</code></pre>
| 1 | 2016-10-13T05:07:52Z | 40,019,383 | <p>Look like you're starting the notebook server from the GUI. The problem is that in OS X, the GUI does not inherit the environment of the shell. You can immediately get it to work by starting the notebook server from the terminal:</p>
<pre><code>jupyter notebook <path-to-notebook-folder> &
</code></pre>
<p>This should let you run with the same environment that your successful <code>python3</code> invocation used. </p>
<p>There <em>are</em> ways to modify the environment of applications launched by the GUI; if you don't mind setting <code>CLASSPATH</code> system-wide, you can set it in <code>/etc/launchd.conf</code> as described <a href="http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x/588442#588442">here</a>. (Log out or restart your system after editing <code>launchd.conf</code>). You could also try <a href="http://stackoverflow.com/questions/7501678/set-environment-variables-on-mac-os-x-lion">this</a> (not sure if it'll still work), or google around for other alternatives.</p>
| 2 | 2016-10-13T11:10:33Z | [
"python",
"osx",
"environment-variables",
"nltk",
"stanford-nlp"
] |
Operations in multi index dataframe pandas | 40,012,740 | <p>I need to process geographic and statistical data from a big data csv. It contains data from geographical administrative and geostatistical. Municipality, Location, geostatistical basic division and block constitute the hierarchical indexes.</p>
<p>I have to create a new column ['data2'] for every element the max value of the data in the geo index, and divide each block value by that value. For each index level, and the index level value must be different from 0, because the 0 index level value accounts for other types of info not used in the calculation.</p>
<pre><code> data1 data2
mun loc geo block
1 0 0 0 20 20
1 1 0 0 10 10
1 1 1 0 10 10
1 1 1 1 3 3/4
1 1 1 2 4 4/4
1 1 2 0 30 30
1 1 2 1 1 1/3
1 1 2 2 3 3/3
1 2 1 1 10 10/12
1 2 1 2 12 12/12
2 1 1 1 123 123/123
2 1 1 2 7 7/123
2 1 2 1 6 6/6
2 1 2 2 1 1/6
</code></pre>
<p>Any ideas? I have tried with for loops, converting the indexes in columns with reset_index() and iterating by column and row values but the computation is taking forever and I think that is not the correct way to do this kind of operations.</p>
<p>Also, what if I want to get my masks like this, so I can run my calculations to every level. </p>
<pre><code>mun loc geo block
1 0 0 0 False
1 1 0 0 False
1 1 1 0 True
1 1 1 1 False
1 1 1 2 False
1 1 2 0 True
1 1 2 1 False
1 1 2 2 False
mun loc geo block
1 0 0 0 False
1 1 0 0 True
1 1 1 0 False
1 1 1 1 False
1 1 1 2 False
1 2 0 0 True
1 2 2 0 False
1 2 2 1 False
mun loc geo block
1 0 0 0 True
1 1 0 0 False
1 1 1 0 False
1 1 1 1 False
1 1 1 2 False
2 0 0 0 True
2 1 1 0 False
2 1 2 1 False
</code></pre>
| 1 | 2016-10-13T05:10:39Z | 40,014,671 | <p>You can first create <code>mask</code> from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.html" rel="nofollow"><code>MultiIndex</code></a>, compare with <code>0</code> and check at least one <code>True</code> (at least one <code>0</code>) by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow"><code>any</code></a>:</p>
<pre><code>mask = (pd.DataFrame(df.index.values.tolist(), index=df.index) == 0).any(axis=1)
print (mask)
mun loc geo block
1 0 0 0 True
1 0 0 True
1 0 True
1 False
2 False
2 0 True
1 False
2 False
2 1 1 False
2 False
2 1 1 1 False
2 False
2 1 False
2 False
dtype: bool
</code></pre>
<p>Then get <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.max.html" rel="nofollow"><code>max</code></a> values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> per first, second and third index, but before filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> only values where are not <code>True</code> in <code>mask</code>:</p>
<pre><code>df1 = df.ix[~mask, 'data1'].groupby(level=['mun','loc','geo']).max()
print (df1)
mun loc geo
1 1 1 4
2 3
2 1 12
2 1 1 123
2 6
</code></pre>
<p>Then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> <code>df1</code> by <code>df.index</code>, remove last level of <code>Multiindex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow"><code>mask</code></a> values where no change by <code>mask</code> (also is necessary remove last level) and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a> by <code>1</code>, because dividing return same value.</p>
<pre><code>df1 = df1.reindex(df.reset_index(level=3, drop=True).index)
.mask(mask.reset_index(level=3, drop=True)).fillna(1)
print (df1)
Name: data1, dtype: int64
mun loc geo
1 0 0 1.0
1 0 1.0
1 1.0
1 4.0
1 4.0
2 1.0
2 3.0
2 3.0
2 1 12.0
1 12.0
2 1 1 123.0
1 123.0
2 6.0
2 6.0
Name: data1, dtype: float64
</code></pre>
<p>Last divide by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a>:</p>
<pre><code>print (df['data1'].div(df1.values,axis=0))
mun loc geo block
1 0 0 0 20.000000
1 0 0 10.000000
1 0 10.000000
1 0.750000
2 1.000000
2 0 30.000000
1 0.333333
2 1.000000
2 1 1 0.833333
2 1.000000
2 1 1 1 1.000000
2 0.056911
2 1 1.000000
2 0.166667
dtype: float64
</code></pre>
| 1 | 2016-10-13T07:20:25Z | [
"python",
"pandas"
] |
How to save a previous command line argument | 40,012,745 | <p>I'm writing my first python command line tool using docopt and have run into an issue. </p>
<p>My structure is like this:</p>
<pre><code>Usage:
my-tool configure
my-tool [(-o <option> | --option <option>)]
...
</code></pre>
<p>I'm trying to find a way to run <code>my-tool -o foo-bar</code> first, and then optionally pass the value 'foo-bar' into my configure function if I run <code>my-tool configure</code> next. </p>
<p>In pseduocode, that translates to this:</p>
<pre><code>def configure(option=None):
print option # With the above inputs this should print 'foo-bar'
def main():
if arguments['configure']:
configure(option=arguments['<option>'])
return
...
</code></pre>
<p>Is there a way to get this working without changing the argument structure?
I'm looking for a way to avoid <code>my-tool configure [(-o <option> | --option <option>)]</code></p>
| 3 | 2016-10-13T05:11:01Z | 40,013,319 | <p>Since you run this on 2 different instances it might be best to store the values in some sort of config/json file that will be cleared each time you run "configure".</p>
<pre><code>import json
def configure(config_file):
print config_file[opt_name] # do something with options in file
# clear config file
with open("CONFIG_FILE.JSON", "wb") as f: config = json.dump([], f)
def main():
# load config file
with open("CONFIG_FILE.JSON", "rb") as f: config = json.load(f)
# use the configure opt only when called and supply the config json to it
if sys.argv[0] == ['configure']:
configure(config)
return
# parse options example (a bit raw, and should be done in different method anyway)
parser = OptionParser()
parser.add_option("-q", action="store_false", dest="verbose")
config_file["q"] = OPTION_VALUE
</code></pre>
| 1 | 2016-10-13T05:57:22Z | [
"python",
"python-2.7",
"command-line-interface",
"docopt"
] |
How to save a previous command line argument | 40,012,745 | <p>I'm writing my first python command line tool using docopt and have run into an issue. </p>
<p>My structure is like this:</p>
<pre><code>Usage:
my-tool configure
my-tool [(-o <option> | --option <option>)]
...
</code></pre>
<p>I'm trying to find a way to run <code>my-tool -o foo-bar</code> first, and then optionally pass the value 'foo-bar' into my configure function if I run <code>my-tool configure</code> next. </p>
<p>In pseduocode, that translates to this:</p>
<pre><code>def configure(option=None):
print option # With the above inputs this should print 'foo-bar'
def main():
if arguments['configure']:
configure(option=arguments['<option>'])
return
...
</code></pre>
<p>Is there a way to get this working without changing the argument structure?
I'm looking for a way to avoid <code>my-tool configure [(-o <option> | --option <option>)]</code></p>
| 3 | 2016-10-13T05:11:01Z | 40,018,475 | <p>I tried writing some script to help you but it was a bit beyond my (current) Newbie skill level.
However, the tools/approach I started taking may be able to help. Try using <code>sys.argv</code> (which generates a list of all arguments from when the script is run), and then using some regular expressions (<code>import re</code>...).</p>
<p>I hope this helps someone else help you. (:</p>
| 0 | 2016-10-13T10:28:41Z | [
"python",
"python-2.7",
"command-line-interface",
"docopt"
] |
Divide values divided by tab, in their own variable | 40,012,853 | <p>I create an output file in a different process, which has 2 values with a tab separating each other. Each line has 2 values and newline, so you always have 2 values per line.</p>
<p>I would like to get the first and second value in 2 different variables, and use them; but I am having hard time to split them.</p>
<p>I do not know the lenght of each string, I just know that there is a tab in between, so I can't count the characters and slice. How do you accomplish this in Python?</p>
| 0 | 2016-10-13T05:20:03Z | 40,012,873 | <p>Assuming all your lines are stored in a list called <code>my_lines</code> you can do:</p>
<pre><code>for line in my_lines:
val1, val2 = line.strip().split("\t", 1)
</code></pre>
| 1 | 2016-10-13T05:22:36Z | [
"python",
"file",
"split"
] |
Divide values divided by tab, in their own variable | 40,012,853 | <p>I create an output file in a different process, which has 2 values with a tab separating each other. Each line has 2 values and newline, so you always have 2 values per line.</p>
<p>I would like to get the first and second value in 2 different variables, and use them; but I am having hard time to split them.</p>
<p>I do not know the lenght of each string, I just know that there is a tab in between, so I can't count the characters and slice. How do you accomplish this in Python?</p>
| 0 | 2016-10-13T05:20:03Z | 40,012,931 | <p>You can try:</p>
<pre><code>>>> s = """This is demo string"""
>>> s.split("\t")
['This ', 'is ', 'demo ', 'string']
</code></pre>
| 1 | 2016-10-13T05:27:58Z | [
"python",
"file",
"split"
] |
Divide values divided by tab, in their own variable | 40,012,853 | <p>I create an output file in a different process, which has 2 values with a tab separating each other. Each line has 2 values and newline, so you always have 2 values per line.</p>
<p>I would like to get the first and second value in 2 different variables, and use them; but I am having hard time to split them.</p>
<p>I do not know the lenght of each string, I just know that there is a tab in between, so I can't count the characters and slice. How do you accomplish this in Python?</p>
| 0 | 2016-10-13T05:20:03Z | 40,012,970 | <p>you can do like:</p>
<pre><code>with open("file.txt", "r") as f:
for line in f:
value1, value2 = line.strip().split("\t", maxsplit=1)
#print(value1, value2)
</code></pre>
<p><code>maxsplit=1</code> keyword argument ensures that you split only once since you said you only have two values which are tab separated.</p>
| 1 | 2016-10-13T05:31:04Z | [
"python",
"file",
"split"
] |
Flask app is not start over twisted 16.4.X as wsgi | 40,012,956 | <p>I have simple Flask app test.py:</p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route('/')
def test():
return 'Hello world!'
if __name__ == '__main__':
app.run()
</code></pre>
<p>Run over twisted 16.3.0 work fine:</p>
<pre><code>twistd -n web --port 5000 --wsgi test.app
</code></pre>
<p>After upgrade twisted to 16.4.0 i have got error on start:</p>
<pre><code>No such WSGI application: 'test.app'
</code></pre>
<p>What is mean?</p>
| 0 | 2016-10-13T05:30:08Z | 40,013,084 | <p>Your are likely picking up the <code>test</code> module which is part of the Python standard library. Rename your code file (module) to something else. You also may need to set <code>PYTHONPATH</code> so it looks in the directory where code module is.</p>
| 0 | 2016-10-13T05:39:01Z | [
"python",
"flask",
"twisted",
"wsgi"
] |
Importing packages causes Unicode error in Anaconda | 40,013,060 | <p>In my program when I type: import matplotlib as pt, I get the following error:</p>
<pre><code> File "C:\Users\hh\Anaconda3\lib\site-packages\numpy\__config__.py", line 5
blas_mkl_info={'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'library_dirs': ['C:\Users\hh\Anaconda3\\Library\\lib'], 'include_dirs': ['C:\Users\hh\Anaconda3\\Library\\include'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]}
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
</code></pre>
<p>Any ideas why this is happening and what I can do to change this?</p>
<p>This is the file that it is referring to: </p>
<pre><code># This file is generated by C:\Minonda\conda-bld\numpy-1.11_1475607650950\work\numpy-1.11.2\setup.py
# It contains system_info results at the time of building this package.
__all__ = ["get_info","show"]
blas_mkl_info={'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'library_dirs': ['C:\Users\hh\Anaconda3\\Library\\lib'], 'include_dirs': ['C:\Users\hh\Anaconda3\\Library\\include'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]}
openblas_lapack_info={}
blas_opt_info={'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'library_dirs': ['C:\Users\hh\Anaconda3\\Library\\lib'], 'include_dirs': ['C:\Users\hh\Anaconda3\\Library\\include'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]}
lapack_opt_info={'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'library_dirs': ['C:\Users\hh\Anaconda3\\Library\\lib'], 'include_dirs': ['C:\Users\hh\Anaconda3\\Library\\include'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]}
lapack_mkl_info={'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'library_dirs': ['C:\Users\hh\Anaconda3\\Library\\lib'], 'include_dirs': ['C:\Users\hh\Anaconda3\\Library\\include'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]}
def get_info(name):
g = globals()
return g.get(name, g.get(name + "_info", {}))
def show():
for name,info_dict in globals().items():
if name[0] == "_" or type(info_dict) is not type({}): continue
print(name + ":")
if not info_dict:
print(" NOT AVAILABLE")
for k,v in info_dict.items():
v = str(v)
if k == "sources" and len(v) > 200:
v = v[:60] + " ...\n... " + v[-60:]
print(" %s = %s" % (k,v))
</code></pre>
| 0 | 2016-10-13T05:37:41Z | 40,013,834 | <p>You're missing (several) escape-backslashes in your path strings:</p>
<pre><code>'C:\Users\hh\Anaconda3\\Library\\lib'
</code></pre>
<p>Here python will attempt to interprete <code>\U</code> as the start of a unicode escape sequence (see e.g. <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">https://docs.python.org/2/reference/lexical_analysis.html#string-literals</a>).</p>
<p>As you already did in parts of this string, you should replace <code>\</code> with a <code>\\</code>:</p>
<pre><code>'C:\\Users\\hh\\Anaconda3\\Library\\lib'
</code></pre>
<p>or use raw strings:</p>
<pre><code>r'C:\Users\hh\Anaconda3\Library\lib'
</code></pre>
<p><strong>EDIT:</strong>
I only now realized, that's a file created by numpy/anaconda not by yourself. So that might be worth a ticket for them I guess...</p>
| 1 | 2016-10-13T06:33:28Z | [
"python",
"anaconda"
] |
convert an unfair coin into a fair coin in Python 2.7 | 40,013,074 | <p>Using Python 2.7. Suppose I have an unfair coin and I want to turn it into a fair coin using the following way,</p>
<ol>
<li>Probability of generating head is equal for unfair coin;</li>
<li>Flip unfair coin and only accept head;</li>
<li>When a head is appearing, treat it as 1 (head for virtual fair coin), when another head is appearing, treat it as 0 (tail for virtual fair coin), next time when head appears, treat it as 1, next time treat as 0, ..., and so on.</li>
</ol>
<p>Not sure if this method works? Actually I am not quite confident about the method above and also how to use <code>equalCoinHelper()</code> correctly (I mark my question in my code).</p>
<p>If anyone have any good ideas, it will be great.</p>
<pre><code>from __future__ import print_function
import random
counter = 0
# 0.3 probability return head as 1
# 0.7 probability return tail as 0
def unFairCoin():
if random.random() < 0.3:
return 1
else:
return 0
# probability of generating 1 is equal, so keep 1 only
def equalCoinHelper():
result = 0
while result == 0:
result = unFairCoin()
def equalDistribution():
global counter
# not think about how to leverage this better
equalCoinHelper()
counter += 1
if counter % 2 == 0:
return 1
else:
return 0
if __name__ == "__main__":
# generate 10 random 0/1 with equal probability
print ([equalDistribution() for _ in range(10)])
</code></pre>
| 1 | 2016-10-13T05:38:30Z | 40,013,248 | <p><a href="http://www.billthelizard.com/2009/09/getting-fair-toss-from-biased-coin.html" rel="nofollow">Getting a Fair Toss From a Biased Coin</a> explains a simple algorithm for turning a biased coin into a fair coin:</p>
<ol>
<li>Flip the coin twice.</li>
<li>If both tosses are the same (heads-heads or tails-tails), repeat step 1.</li>
<li>If the tosses come up heads-tails, count the toss as heads. If the tosses come up tails-heads, count it as tails.</li>
</ol>
<p>In Python this would be:</p>
<pre><code>def fairCoin():
coin1 = unfairCoin()
coin2 = unfairCoin()
if coin1 == coin2:
return fairCoin() # both are the same, so repeat it
elif coin1 == 1 and coin2 == 0:
return 1
else:
return 0
</code></pre>
<p>The <code>elif</code> and <code>else</code> blocks can be simplified to just:</p>
<pre><code> else:
return coin1
</code></pre>
| 2 | 2016-10-13T05:51:08Z | [
"python",
"algorithm",
"python-2.7",
"probability",
"coin-flipping"
] |
convert an unfair coin into a fair coin in Python 2.7 | 40,013,074 | <p>Using Python 2.7. Suppose I have an unfair coin and I want to turn it into a fair coin using the following way,</p>
<ol>
<li>Probability of generating head is equal for unfair coin;</li>
<li>Flip unfair coin and only accept head;</li>
<li>When a head is appearing, treat it as 1 (head for virtual fair coin), when another head is appearing, treat it as 0 (tail for virtual fair coin), next time when head appears, treat it as 1, next time treat as 0, ..., and so on.</li>
</ol>
<p>Not sure if this method works? Actually I am not quite confident about the method above and also how to use <code>equalCoinHelper()</code> correctly (I mark my question in my code).</p>
<p>If anyone have any good ideas, it will be great.</p>
<pre><code>from __future__ import print_function
import random
counter = 0
# 0.3 probability return head as 1
# 0.7 probability return tail as 0
def unFairCoin():
if random.random() < 0.3:
return 1
else:
return 0
# probability of generating 1 is equal, so keep 1 only
def equalCoinHelper():
result = 0
while result == 0:
result = unFairCoin()
def equalDistribution():
global counter
# not think about how to leverage this better
equalCoinHelper()
counter += 1
if counter % 2 == 0:
return 1
else:
return 0
if __name__ == "__main__":
# generate 10 random 0/1 with equal probability
print ([equalDistribution() for _ in range(10)])
</code></pre>
| 1 | 2016-10-13T05:38:30Z | 40,014,058 | <p>An alternative implementation of @Barmar's answer that avoids the recursive call (even though it may be harmless)</p>
<pre><code>def fairCoin():
coin1 = 0
coin2 = 0
while coin1 == coin2:
coin1 = unfairCoin()
coin2 = unfairCoin()
return coin1
</code></pre>
| 2 | 2016-10-13T06:45:21Z | [
"python",
"algorithm",
"python-2.7",
"probability",
"coin-flipping"
] |
File's Data keeps getting overwritten by function | 40,013,190 | <p>for some reason I am running into an issue where my function call seems to be overwriting the data read in from the file without me asking it to. I am trying to get the sum of the original list but I keep getting the sum of the squared list. </p>
<p><strong>CODE:</strong></p>
<pre><code>def toNumbers(strList):
for i in range(len(strList)):
strList[i] = strList [int(i)]
return strList
def squareEach(nums):
for i in range(len(nums)):
nums[i] = eval(nums[i])
nums[i] = nums[i]**2
return nums
def sumList(nums):
b = sum(nums)
return b
def main():
file=open("numbers.txt","r").readline().split(" ")
print(str(squareEach(file)))
print(str(sumList(file)))
</code></pre>
| 0 | 2016-10-13T05:46:21Z | 40,013,307 | <p>Your squareEach function modifies the original list which is passed to it.
To see what's going, consider adding a print between your function calls.
<code>
def main():
file=open("numbers.txt","r").readline().split(" ")
print(str(squareEach(file)))
print(str(file))
print(str(sumList(file))
</code></p>
<p>EDIT:
The simplest fix would be to use a different list for storing your square numbers inside squareEach function</p>
<pre><code>def squareEach(nums):
squares = []
for i in range(len(nums)):
num = eval(nums[i])
squares[i] = num**2
return squares
</code></pre>
<p>There are more efficient ways as suggested in other answers, but in your case, this appears to be the simplest fix.</p>
| 2 | 2016-10-13T05:56:38Z | [
"python",
"file-io"
] |
File's Data keeps getting overwritten by function | 40,013,190 | <p>for some reason I am running into an issue where my function call seems to be overwriting the data read in from the file without me asking it to. I am trying to get the sum of the original list but I keep getting the sum of the squared list. </p>
<p><strong>CODE:</strong></p>
<pre><code>def toNumbers(strList):
for i in range(len(strList)):
strList[i] = strList [int(i)]
return strList
def squareEach(nums):
for i in range(len(nums)):
nums[i] = eval(nums[i])
nums[i] = nums[i]**2
return nums
def sumList(nums):
b = sum(nums)
return b
def main():
file=open("numbers.txt","r").readline().split(" ")
print(str(squareEach(file)))
print(str(sumList(file)))
</code></pre>
| 0 | 2016-10-13T05:46:21Z | 40,013,641 | <p>I am not sure whether i am helping . But whatever you are trying to do can be done as follows</p>
<pre><code>file=open("numbers.txt","r").readline().split(" ")
print ([int (m)**2 for m in file])
print (sum([int(m) for m in file]))
</code></pre>
<p>And if you want functions</p>
<pre><code>def squareEach(file):
print ([int (m)**2 for m in file])
def sumList(file):
print (sum([int(m) for m in file]))
file=open("numbers.txt","r").readline().split(" ")
squareEach(file)
sumList(file)
</code></pre>
| 0 | 2016-10-13T06:19:34Z | [
"python",
"file-io"
] |
File's Data keeps getting overwritten by function | 40,013,190 | <p>for some reason I am running into an issue where my function call seems to be overwriting the data read in from the file without me asking it to. I am trying to get the sum of the original list but I keep getting the sum of the squared list. </p>
<p><strong>CODE:</strong></p>
<pre><code>def toNumbers(strList):
for i in range(len(strList)):
strList[i] = strList [int(i)]
return strList
def squareEach(nums):
for i in range(len(nums)):
nums[i] = eval(nums[i])
nums[i] = nums[i]**2
return nums
def sumList(nums):
b = sum(nums)
return b
def main():
file=open("numbers.txt","r").readline().split(" ")
print(str(squareEach(file)))
print(str(sumList(file)))
</code></pre>
| 0 | 2016-10-13T05:46:21Z | 40,013,680 | <p>The list <code>nums</code> is modified in <code>squareEach</code> method. Consider storing the results in a different list variable of the below sort:</p>
<pre><code>def squareEach(nums):
sq = list()
for i in range(len(nums)):
sq.append(str(int(nums[i])**2))
# nums[i] = str(int(nums[i])**2)
return sq
</code></pre>
| 0 | 2016-10-13T06:22:58Z | [
"python",
"file-io"
] |
I can't delete data multiple in mysql from python | 40,013,196 | <p><strong>I made input 2 value row and num when input data so program throw Rollback not work if-else and thank for help</strong></p>
<pre><code>#!/usr/bin/python
import mysql.connector
conn = mysql.connector.connect(host="",user="",passwd="",db="")
cursor = conn.cursor()
try:
row = raw_input("InputNameRow : ")
num = int(input("InputNumber 1-10 : "))
if num <= 10:
sql1 = "SELECT * FROM dt WHERE '%s' = '%d' " %(row,num)
cursor.execute(sql1)
data = cursor.fetchall()
print(data[0])
sqlde = "DELETE FROM dt WHERE '%s' = '%d' " %(row,num)
cursor.execute(sqlde, (num))
print "DELETE SUCESS"
conn.commit()
else:
print "Data Empty"
except:
conn.rollback()
print "Input Error"
conn.close()
</code></pre>
| 0 | 2016-10-13T05:46:58Z | 40,013,464 | <p>Try :</p>
<pre><code>cursor.execute(sqlde)
</code></pre>
<p>instead of </p>
<pre><code>cursor.execute(sqlde, (num))
</code></pre>
| 2 | 2016-10-13T06:06:49Z | [
"python",
"mysql"
] |
calling virtualenv bundled pip wuth subprocess.call fails on long path to venv directory on Linux | 40,013,347 | <p>The following line throws strange exceptions in Linux (several Ubuntu 14.04 installations and one Arch linux installation with all updates installed):</p>
<pre><code>subprocess.call(['/home/vestnik/Development/test/python/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/venv/bin/pip','install','httpbin'])
</code></pre>
<p>python2.7:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 523, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
</code></pre>
<p>python3.5:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: '/home/vestnik/Development/test/python/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/venv/bin/pip'
</code></pre>
<p>pip executable I'm trying to run is valid existing file created by virtualenv bootstrap script. The problem appears when path length to pip becomes larger then 120 characters (approximatelly). If I remove one "subdir" element in the middle of the path everyting works well. Original source of this issue is jenkins build failing on virtualenv creation due to long workspace names.</p>
<p>Are there any limitations on executable path length in subprocess module (I haven't find it in the function docs) or is it an implementation bug? Are there good ways to workaround it?</p>
| 0 | 2016-10-13T05:58:59Z | 40,014,028 | <p>When I've tried to call pip in venv from bash I got bad interpretator error.</p>
<p>The real source of the problem is shebang string length limitation (the comment to accepted answer <a href="http://stackoverflow.com/questions/10813538/shebang-line-limit-in-bash-and-linux-kernel">here</a> claims default limit to be equal to 127 bytes):</p>
<pre><code>$ head -n1 /home/vestnik/Development/test/python/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/venv/bin/pip
#!/home/vestnik/Development/test/python/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/venv/bin/python3.5
$ head -n1 /home/vestnik/Development/test/python/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/subdir/venv/bin/pip | wc -c
129
</code></pre>
<p>the problem source is not subprocess module. It only producess confusing error.</p>
<p>The following code works:</p>
<pre><code>subprocess.call([
'/home/...lonl long venv path.../venv/bin/python3.5',
'/home/...lonl long venv path.../venv/bin/pip',
'install',
'httpbin'
])
</code></pre>
| 0 | 2016-10-13T06:43:51Z | [
"python",
"linux",
"subprocess",
"virtualenv"
] |
selenium python webscrape fails after first iteration | 40,013,400 | <p>Im iterating through tripadvisor to save comments(non-translated, original) and translated comments (from portuguese to english).
So the scraper first selects portuguese comments to be displayed , then as usual it converts them into english one by one and saves the translated comments in com_, whereas the expanded non-translated comments in expanded_comments.</p>
<p>The code works fine with first page but from second page onward it fails to save translated comments. Strangely it just translates only first comment from each of the pages and doesnt even save them.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
com_=[]
expanded_comments=[]
date_=[]
driver = webdriver.Chrome("C:\Users\shalini\Downloads\chromedriver_win32\chromedriver.exe")
driver.maximize_window()
from bs4 import BeautifulSoup
def expand_reviews(driver):
# TRYING TO EXPAND REVIEWS (& CLOSE A POPUP)
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err"
try:
driver.find_element_by_class_name("ui_close_x").click()
except:
print "err2"
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err3"
def save_comments(driver):
expand_reviews(driver)
# SELECTING ALL EXPANDED COMMENTS
#xpanded_com_elements=driver.find_elements_by_class_name("entry")
time.sleep(3)
#or i in expanded_com_elements:
# expanded_comments.append(i.text)
spi=driver.page_source
sp=BeautifulSoup(spi)
for t in sp.findAll("div",{"class":"entry"}):
if not t.findAll("p",{"class":"partial_entry"}):
#print t
expanded_comments.append(t.getText())
# Saving review date
for d in sp.findAll("span",{"class":"recommend-titleInline"}) :
date=d.text
date_.append(date_)
# SELECTING ALL GOOGLE-TRANSLATOR links
gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation>.link")
# NOW PRINTING TRANSLATED COMMENTS
for i in gt:
try:
driver.execute_script("arguments[0].click()",i)
#com=driver.find_element_by_class_name("ui_overlay").text
com= driver.find_element_by_xpath(".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")
com_.append(com.text)
time.sleep(5)
driver.find_element_by_class_name("ui_close_x").click().perform()
time.sleep(5)
except Exception as e:
pass
# ITERATING THROIGH ALL 200 tripadvisor webpages and saving comments & translated comments
for i in range(200):
page=i*10
url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or"+str(page)+"-TAP-Portugal#REVIEWS"
driver.get(url)
wait = WebDriverWait(driver, 10)
if i==0:
# SELECTING PORTUGUESE COMMENTS ONLY # Run for one time then iterate over pages
try:
langselction = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.sprite-date_picker-triangle")))
langselction.click()
driver.find_element_by_xpath("//div[@class='languageList']//li[normalize-space(.)='Portuguese first']").click()
time.sleep(5)
except Exception as e:
print e
save_comments(driver)
</code></pre>
| 1 | 2016-10-13T06:02:24Z | 40,019,493 | <p>There are 3 problems in your code</p>
<ol>
<li>Inside method <code>save_comments()</code>, at the <code>driver.find_element_by_class_name("ui_close_x").click().perform()</code>, the method <code>click()</code> of a webelement is not an ActionChain so you cannot call <code>perform()</code>. Therefore, that line should be like this:</li>
</ol>
<pre><code>driver.find_element_by_class_name("ui_close_x").click()
</code></pre>
<ol start="2">
<li>Inside method <code>save_comments()</code>, at the <code>com= driver.find_element_by_xpath(".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")</code>, you find the element when it doesn't appear yet. So you have to add wait before this line. Your code should be like this:</li>
</ol>
<pre><code>wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, ".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")))
com= driver.find_element_by_xpath(".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")
</code></pre>
<ol start="3">
<li>There are 2 buttons which can open the review, one is displayed and one is hidden. So you have to skip the hidden button.</li>
</ol>
<pre><code>if not i.is_displayed():
continue
driver.execute_script("arguments[0].click()",i)
</code></pre>
| 1 | 2016-10-13T11:16:46Z | [
"python",
"selenium",
"web-scraping"
] |
StopValidation() In route without raiseing wsgi debuger flask wtf | 40,013,443 | <p>I need to overwrite the Vlaidator in the form and apply my own validator this specific route.
When the image uploaded is not a jpg then it will not pass the form.validate_on_submit() check and the template will render the errors in the html. When i try to use</p>
<pre><code> raise StopValidation("image1 jpg only")
</code></pre>
<p><br>
It raises it debuger and it prevents me from seeing the route. I just want it display as a field.error with the other errors.</p>
<pre><code> @app.route('/test',methods=['GET','POST'])
def test():
form.image1.validators=[]
if request.method == "POST" and str(request.files['image1'].filename) != "":
if request.files['image1'].filename.split('.',1)[1] != "jpg" :
raise StopValidation("image1 jpg only")
print "image 1 not jpg"
if form.validate_on_submit():
# do stuff
return render_template('test.html')
</code></pre>
| 0 | 2016-10-13T06:05:24Z | 40,035,652 | <p>If you want to validate only jpg file, then make a custom validation instead of using StopValidation and just define in your form.</p>
<pre><code>def customvalidatorForImage(form, field):
allowed_file = ['jpg','jpeg','png','gif'] # you can modify your valid file list here
if form.image.data:
if form.image.data.split('.',1)[1] not in allowed_file:
raise ValidationError("Please enter a valid image file")
class MyForm(Form):
image = FileField("Image" , [customvalidatorForImage, validators.DataRequired("Image is required")])
</code></pre>
| 0 | 2016-10-14T05:37:41Z | [
"python",
"wtforms",
"flask-wtforms"
] |
I am not able get the sorted values from the input | 40,013,529 | <p>problem with sorting</p>
<pre><code>a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
while i <= n:
s = input()
total = total + int(s)
i = i + 1
s.sort()
print s
print('The sum is ' + str(total))
</code></pre>
| 0 | 2016-10-13T06:10:37Z | 40,013,811 | <pre><code>n = int(input("Enter the number of inputs : "))
total = 0
i = 1
array = []
while i <= n:
s = int(input())
array.append(s)
total = total + int(s)
i = i + 1
array.sort()
print(array)
print('The sum is ' + str(total))
</code></pre>
<p>this will solve your problem, sort applies on list not on str object</p>
| 0 | 2016-10-13T06:31:45Z | [
"python"
] |
I am not able get the sorted values from the input | 40,013,529 | <p>problem with sorting</p>
<pre><code>a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
while i <= n:
s = input()
total = total + int(s)
i = i + 1
s.sort()
print s
print('The sum is ' + str(total))
</code></pre>
| 0 | 2016-10-13T06:10:37Z | 40,013,815 | <p>Because you are trying to <code>sort</code> on input. <code>sort</code> only work on iterating like list and tuples. </p>
<p>I just rewrite your code,</p>
<pre><code>a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
inputs = []
for i in range(n):
s = input()
inputs.append(int(s))
inputs.sort()
print inputs
print('The sum is ',sum(inputs))
</code></pre>
<p><strong><em>Edit</em></strong></p>
<p>Just change whole operation into a function and put yes/no question in a while loop, And for wrong entry exit from program.</p>
<pre><code>def foo():
n = int(input("Enter the number of inputs : "))
inputs = []
for i in range(n):
s = input()
inputs.append(int(s))
inputs.sort()
print inputs
print('The sum is ',sum(inputs))
while True:
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
foo()
elif a == 'n':
print 'We are giving one more option.'
continue
else:
print 'Wrong entry'
break
</code></pre>
| 0 | 2016-10-13T06:32:03Z | [
"python"
] |
I am not able get the sorted values from the input | 40,013,529 | <p>problem with sorting</p>
<pre><code>a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
while i <= n:
s = input()
total = total + int(s)
i = i + 1
s.sort()
print s
print('The sum is ' + str(total))
</code></pre>
| 0 | 2016-10-13T06:10:37Z | 40,013,985 | <p>Store the numbers in a list. Then use sum(list) to get the sum of elements in the list, and sorted(list) to get the list sorted in ascending order.</p>
<pre><code> n = int(input("Enter the number of inputs: "))
l=[]
for i in range(n):
s = input()
l.append(int(s))
print('The sum is', sum(l))
print('Sorted values', sorted(l))
</code></pre>
<p>Were you looking for this?</p>
| 0 | 2016-10-13T06:41:50Z | [
"python"
] |
Python Adding 2 list with common keys to dictionary | 40,013,642 | <p>I am new to python. I'm extracting two rows from a csvfile.</p>
<pre><code>Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, orange, carrot']
</code></pre>
<p>And the quantity list corresponds to each of the items in its sequence.</p>
<pre><code>Quantity = ['1,2,1','2,5','1,2']
</code></pre>
<p>How can i merge the two list with common keys into a dictionary? I tried splitting and joining but the quantity gets overwritten due to the common keys. </p>
<p>I am trying to output: </p>
<pre><code>{'Apple: totalquantity','Banana: totalquantity',
'Carrot: totalquantity','Chocolate: totalquantity',
'orange: totalquantity', 'strawberry: totalquantity'}
</code></pre>
<p>Please help! </p>
<p>Will there be anyway where i can extract the csvfile row for the food items and assign its values in a dictionary? </p>
<p>for cvs file is as follows:</p>
<p>row 1:
apple, carrot, banana
chocolate, apple
strawberry, orange, carrot</p>
<p>row 2:
1,2,1
2,5
1,2</p>
| 0 | 2016-10-13T06:20:02Z | 40,013,884 | <p>You can use <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> to aggregate the result:</p>
<pre><code>from collections import Counter
Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, orange, carrot']
Quantity = ['1,2,1','2,5','1,2']
res = Counter()
for f_list, q_list in zip(Foodlist, Quantity):
for f, q in zip(f_list.split(', '), q_list.split(',')):
res[f] += int(q)
print(res)
</code></pre>
<p>Output:</p>
<pre><code>Counter({'apple': 6, 'chocolate': 2, 'carrot': 2, 'orange': 2, 'strawberry': 1, 'banana': 1})
</code></pre>
| 1 | 2016-10-13T06:36:51Z | [
"python",
"list",
"csv",
"dictionary",
"key"
] |
Python Adding 2 list with common keys to dictionary | 40,013,642 | <p>I am new to python. I'm extracting two rows from a csvfile.</p>
<pre><code>Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, orange, carrot']
</code></pre>
<p>And the quantity list corresponds to each of the items in its sequence.</p>
<pre><code>Quantity = ['1,2,1','2,5','1,2']
</code></pre>
<p>How can i merge the two list with common keys into a dictionary? I tried splitting and joining but the quantity gets overwritten due to the common keys. </p>
<p>I am trying to output: </p>
<pre><code>{'Apple: totalquantity','Banana: totalquantity',
'Carrot: totalquantity','Chocolate: totalquantity',
'orange: totalquantity', 'strawberry: totalquantity'}
</code></pre>
<p>Please help! </p>
<p>Will there be anyway where i can extract the csvfile row for the food items and assign its values in a dictionary? </p>
<p>for cvs file is as follows:</p>
<p>row 1:
apple, carrot, banana
chocolate, apple
strawberry, orange, carrot</p>
<p>row 2:
1,2,1
2,5
1,2</p>
| 0 | 2016-10-13T06:20:02Z | 40,013,887 | <p>Use collections.default_dict to set up a dictionary to count your items in.</p>
<pre><code>In [1]: from collections import defaultdict
In [2]: items = defaultdict(int)
In [3]: Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, or
...: ange, carrot']
In [4]: Quantity = ['1,2,1','2,5','1,2']
In [5]: for which, counts in zip(Foodlist, Quantity):
...: foods = [w.strip() for w in which.split(',')] # Split the foods and remove trailing spaces
...: nums = [int(c) for c in counts.split(',')] # Split the counts are convert to ints
...: for f, n in zip(foods, nums):
...: items[f] += n
...:
In [6]: items
Out[6]:
defaultdict(int,
{'apple': 6,
'banana': 1,
'carrot': 2,
'chocolate': 2,
'orange': 2,
'strawberry': 1})
In [7]:
</code></pre>
| 1 | 2016-10-13T06:37:00Z | [
"python",
"list",
"csv",
"dictionary",
"key"
] |
How to implement a message system? | 40,013,849 | <p>I am running a website where user can send in-site message (no instantaneity required) to other user, and the receiver will get a notification about the message.</p>
<p>Now I am using a simple system to implement that, detail below.</p>
<p>Table <code>Message</code>:</p>
<ul>
<li>id</li>
<li>content</li>
<li>receiver</li>
<li>sender</li>
</ul>
<p>Table <code>User</code>:</p>
<ul>
<li>some info</li>
<li>notification</li>
<li>some info</li>
</ul>
<p>When a User A send message to User B, a record will be add to <code>Message</code> and the <code>B.notification</code> will increase by 1. When B open the message box the notification will decrease to 0.</p>
<p>It's simple but does well.</p>
<p>I wonder how you/company implement message system like that.</p>
<p>No need to care about UE(like confirm which message is read by user), just the struct implement.</p>
<p>Thank a lot :D</p>
| 0 | 2016-10-13T06:34:34Z | 40,015,293 | <p>I think you will need to read about pub/sub for messaging services. For php, you can use libraries such as redis.</p>
<p>So for e.g, user1 subscribe to topic1, any user which publish to topic1, user1 will be notified, and you can implement what will happen to the user1.</p>
| 0 | 2016-10-13T07:54:43Z | [
"php",
"python",
"web",
"messagebox"
] |
parameters for google cloud natural language api | 40,013,944 | <p>I want to use pure http requests to get the result from google cloud natural language api, but their document does not specify the parameter names.</p>
<p>Here is my python code:</p>
<pre><code>import requests
url = "https://language.googleapis.com/v1beta1/documents:analyzeEntities"
d = {"document": {"content": "some text here", "type": "PLAIN_TEXT"}}
para = {"key": "my api key"}
r = requests.post(url, params=para, data=d)
</code></pre>
<p>Here is the error message:
<code>{u'error': {u'status': u'INVALID_ARGUMENT', u'message': u'Invalid JSON payload received. Unknown name "document": Cannot bind query parameter. \'document\' is a message type. Parameters can only be bound to primitive types.', u'code': 400, u'details': [{u'fieldViolations': [{u'description': u'Invalid JSON payload received. Unknown name "document": Cannot bind query parameter. \'document\' is a message type. Parameters can only be bound to primitive types.'}], u'@type': u'type.googleapis.com/google.rpc.BadRequest'}]}}
</code></p>
<p>how should I create the http request without using their python library?</p>
| 0 | 2016-10-13T06:39:24Z | 40,014,342 | <p>ok, I figured it out. I need to pass JSON-Encoded POST/PATCH data, so the request should be <code>r = requests.post(url, params=para, json=d)</code></p>
| 0 | 2016-10-13T07:02:18Z | [
"python",
"rest",
"google-api",
"google-cloud-platform"
] |
How to clean up upon a crash? | 40,013,946 | <p>I would like some clean-up activities to occur in case of crash of my program. I understand that some situations cannot be handled (a <code>SIGKILL</code> for instance) but I would like to cover as much as possible.</p>
<p>The <a href="https://docs.python.org/3.5/library/atexit.html#module-atexit" rel="nofollow"><code>atexit</code></a> module was a good candidate but the docs explicitely state that</p>
<blockquote>
<p>The functions registered via this module are not called when the
program is killed by a signal not handled by Python, when a Python
fatal internal error is detected, or when os._exit() is called.</p>
</blockquote>
<p>Are there functions or python features which allow to handle <code>sys.exit()</code> and unhandled exceptions program terminations? (these are the main one I am concerned with)</p>
| 0 | 2016-10-13T06:39:26Z | 40,014,076 | <p><code>SIGKILL</code> <a href="https://en.m.wikipedia.org/wiki/Unix_signal#SIGKILL" rel="nofollow">cannot be handled</a>, no matter what, your program is just terminated (killed violently), and you can do nothing about this. </p>
<p>The only thing you can do about <code>SIGKILL</code> is to look for data that needs to be cleaned up <em>during the next launch of your program</em>. </p>
<p>For other cases use <code>atexit</code> to handle Python's interpreter <em>normal</em> termination. If you've got some unhandled exceptions, see where they can occur and wrap these pieces of code in <code>try/except</code> blocks:</p>
<pre><code>try:
pass
except ValueError as e:
pass
except:
# catch other exceptions
pass
</code></pre>
<p>To deal with <code>sys.exit</code> calls, you can wrap <em>the entire program's starting point</em> in a <code>try/except</code> block and catch the <code>SystemExit</code> exception:</p>
<pre><code>try:
# your program goes here
# you're calling your functions from here, etc
except SystemExit:
# do cleanup
raise
</code></pre>
| 0 | 2016-10-13T06:46:32Z | [
"python",
"python-3.x",
"crash",
"code-cleanup"
] |
How to read csv file as dtype datetime64? | 40,013,975 | <p>Now I have csv file </p>
<pre><code> date
201605
201606
201607
201608
</code></pre>
<p>I wanna get dataframe like this</p>
<p>df</p>
<pre><code> date
0 2016-05-01
1 2016-06-01
2 2016-07-01
3 2016-08-01
</code></pre>
<p>so,I would like to read csvfile as datetime64.
and add the date 1.
How can I read and transform this csvfile?</p>
| 1 | 2016-10-13T06:41:28Z | 40,014,033 | <p>Maybe this answer will help you to convert your column to datetime object <a href="http://stackoverflow.com/a/26763793/5982925">http://stackoverflow.com/a/26763793/5982925</a></p>
| 1 | 2016-10-13T06:43:59Z | [
"python",
"csv",
"parsing",
"datetime",
"pandas"
] |
How to read csv file as dtype datetime64? | 40,013,975 | <p>Now I have csv file </p>
<pre><code> date
201605
201606
201607
201608
</code></pre>
<p>I wanna get dataframe like this</p>
<p>df</p>
<pre><code> date
0 2016-05-01
1 2016-06-01
2 2016-07-01
3 2016-08-01
</code></pre>
<p>so,I would like to read csvfile as datetime64.
and add the date 1.
How can I read and transform this csvfile?</p>
| 1 | 2016-10-13T06:41:28Z | 40,014,048 | <p>You can use parameter <code>date_parser</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p>
<pre><code>import sys
if sys.version_info.major<3:
from StringIO import StringIO
else:
from io import StringIO
import pandas as pd
temp=u"""date
201605
201606
201607
201608"""
dateparser = lambda x: pd.datetime.strptime(x, '%Y%m')
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(StringIO(temp), parse_dates=[0], date_parser=dateparser)
print (df)
date
0 2016-05-01
1 2016-06-01
2 2016-07-01
3 2016-08-01
print (df.dtypes)
date datetime64[ns]
dtype: object
</code></pre>
| 1 | 2016-10-13T06:44:41Z | [
"python",
"csv",
"parsing",
"datetime",
"pandas"
] |
Python-Flask not accepting custom fonts | 40,013,987 | <p>
Folder Blueprint <br></p>
<p>Templates</p>
<ul>
<li>File.html<br></li>
</ul>
<p>Static</p>
<ul>
<li>Fonts</li>
<li>Style</li>
</ul>
<p>In the css file , i tried :</p>
<pre><code>@font-face{
font-family:<Font_name>
src:{{ url_for('static',filename='fonts/<font_name>.ttf') }} ;
}
</code></pre>
<p>What changes are to be made to add custom fonts ?</p>
| 0 | 2016-10-13T06:41:57Z | 40,015,356 | <p>You can't use template tags in css. the Jinja template tags are only meant for html files and templates not css.</p>
<p>To use a css file, you have to insert the link manually there, something along the lines of:</p>
<pre><code>@font-face{
font-family:customfont
src:/static/Fonts/font.ttf') }} ;
}
</code></pre>
<p>The only way to get around this is to serve a template, that contains the css embedded in <code><style></style></code> tags that way flask would be able to interprete the template tags. so with that you should have something like this</p>
<pre><code><style>
@font-face{
font-family:<Font_name>
src:{{ url_for('static',filename='fonts/<font_name>.ttf') }} ;
}
</style>
</code></pre>
| 0 | 2016-10-13T07:58:04Z | [
"python",
"flask"
] |
Python 3.5.2 - How to detect a program running i.e "chrome.exe" using stock modules | 40,014,042 | <p>If I wanted to have a program that detects program running such as 'chrome.exe' then opens a program <code>message.txt</code> in this case</p>
<p>Psuedocode:</p>
<pre><code>import os
if "chrome.exe" is running:
os.startfile("message.txt")
</code></pre>
| 0 | 2016-10-13T06:44:22Z | 40,015,194 | <p>You could use wmi package to check running process in windows like below snippet.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import wmi
c = wmi.WMI()
for process in c.Win32_Process():
if process.Name == 'chrome.exe':
print('chrome is running now.')
# open your program in this position
else:
print(process.Name)</code></pre>
</div>
</div>
</p>
| 0 | 2016-10-13T07:48:51Z | [
"python"
] |
Python 3.5.2 - How to detect a program running i.e "chrome.exe" using stock modules | 40,014,042 | <p>If I wanted to have a program that detects program running such as 'chrome.exe' then opens a program <code>message.txt</code> in this case</p>
<p>Psuedocode:</p>
<pre><code>import os
if "chrome.exe" is running:
os.startfile("message.txt")
</code></pre>
| 0 | 2016-10-13T06:44:22Z | 40,015,344 | <p>You could you below too as <a href="http://stackoverflow.com/users/1832058/furas">furas</a> said. Thanks furas. :smile:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import psutil as psutil
for proc in psutil.process_iter():
proc_name = proc.name()
if proc_name == 'chrome.exe':
print('chrome is running now.')
# open your program in this position
else:
print(proc_name)</code></pre>
</div>
</div>
</p>
| 0 | 2016-10-13T07:57:29Z | [
"python"
] |
how can I plot values with big variance using matplotlib | 40,014,142 | <p>The values of Y are like <code>[0, 2, 38, 47, 123, 234, 1003, 100004, 50000003, 1000000004]</code></p>
<p>The figure I want to get is just as following:</p>
<p><a href="https://i.stack.imgur.com/SSHCO.png" rel="nofollow"><img src="https://i.stack.imgur.com/SSHCO.png" alt="logplot"></a></p>
| 0 | 2016-10-13T06:50:33Z | 40,014,190 | <p>From the examples <a href="http://matplotlib.org/examples/pylab_examples/log_demo.html" rel="nofollow">here</a></p>
<pre><code># log y axis
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.01, 20.0, 0.01)
plt.subplot(221)
plt.semilogy(t, np.exp(-t/5.0))
plt.title('semilogy')
plt.grid(True)
plt.show()
</code></pre>
<p>So use <code>plt.semilogy()</code>. If you want a X-axis with a log-scale, use <code>plt.semilogx()</code>. For both axis on a log-scale, use <code>plt.loglog()</code>.</p>
| 4 | 2016-10-13T06:52:59Z | [
"python",
"matplotlib",
"plot"
] |
Upload Image in Django ImageField | 40,014,178 | <p>I'm try to test my model with ImageField, for this purpose i'm reading .jpg file in binary mode and save in the model. I find a lot of question in StackOverflow, but nothing seems to work for me.</p>
<pre><code>testImagePath = os.path.join(settings.BASE_DIR, 'test_image_folder/test_image.jpg')
"image" : SimpleUploadedFile(name='test_image.jpg', content=open(testImagePath, 'rb').read(), content_type='image/jpeg')
</code></pre>
<p>error:</p>
<blockquote>
<p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position
0: invalid start byte</p>
</blockquote>
<p>test.py</p>
<pre><code>class Test(TestCase):
testUser = {
"username": "TestUser",
"email": "[email protected]",
"password": "TestUserPassword",
"confirm_password": "TestUserPassword"
}
testAlbum = {
"owner" : testUser['username'],
"name" : "Test Album"
}
testImagePath = os.path.join(settings.BASE_DIR, 'test_image_folder/test_image.jpg')
testPhoto = {
"owner" : testUser['username'],
"album" : testAlbum['name'],
"name" : "Test Photo",
"image" : SimpleUploadedFile(name='test_image.jpg', content=open(testImagePath, 'rb').read(), content_type='image/jpeg')
}
def setUp(self):
self.client = APIClient()
self.registerTestUser()
...
def test_photos_urls(self):
response = self.client.post('/api/photos/', self.testPhoto, format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED, msg=response.content)
</code></pre>
<p>serializer:</p>
<pre><code>class PhotoSerializer(serializers.HyperlinkedModelSerializer):
album = serializers.HyperlinkedRelatedField(view_name='album-detail', queryset=Album.objects)
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Photo
fields = ('pk', 'name', 'image', 'creation_date', 'owner', 'album',)
read_only_fields=('creation_date',)
</code></pre>
<p>view:</p>
<pre><code>class PhotoViewSet(viewsets.ModelViewSet):
queryset = Photo.objects.all()
serializer_class = PhotoSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
</code></pre>
<p>model:</p>
<pre><code>class Photo(models.Model):
album = models.ForeignKey(Album, related_name='photos', on_delete=models.CASCADE)
owner = models.ForeignKey(User, related_name='user_photos', on_delete=models.CASCADE)
name = models.CharField(max_length=80, default='New photo')
image = models.ImageField(name, upload_to=get_image_path)
creation_date = models.DateField(auto_now_add=True)
def __str__(self):
return self.name
class Meta:
ordering = ['creation_date', ]
</code></pre>
<p>Full traceback of error:</p>
<blockquote>
<p>Traceback (most recent call last): File
"D:\code\active\Python\Django\photo-hub\photo-hub\api\tests.py", line
66, in test_photos_urls
response = self.client.post('/api/photos/', self.testPhoto, format="json") File
"C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\test.py",
line 172, in post
path, data=data, format=format, content_type=content_type, **extra) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\test.py",
line 93, in post
data, content_type = self._encode_data(data, format, content_type) File
"C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\test.py",
line 65, in _encode_data
ret = renderer.render(data) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\renderers.py",
line 103, in render
separators=separators File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\json__init__.py",
line 237, in dumps
**kw).encode(obj) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\json\encoder.py",
line 198, in encode
chunks = self.iterencode(o, _one_shot=True) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\json\encoder.py",
line 256, in iterencode
return _iterencode(o, 0) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\utils\encoders.py",
line 54, in default
return obj.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte</p>
</blockquote>
| 2 | 2016-10-13T06:52:34Z | 40,050,146 | <p>ImageField need to obtain file, not data. This solve the problem:</p>
<pre><code>"image" : open(os.path.join(settings.BASE_DIR, 'test_image_folder/test_image.jpg'), 'rb')
</code></pre>
| 0 | 2016-10-14T18:49:18Z | [
"python",
"django"
] |
calling values from dict and changing values in a list | 40,014,191 | <p>I have a list of DNA sequences like this:
very small example:</p>
<pre><code>> seq = ['ATGGCGGCGCGA', 'GCCTCTGCCTTG', 'CTGAAAACG']
</code></pre>
<p>and if you divide the number of characters in each sequence by 3 you would get even number.
I also have this dictionary which is codons and amino acids. </p>
<pre><code>gencode = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'}
</code></pre>
<p>I want replace each codn (3 characters) with its amino acid(its value in the above dictionary).
the results for the small example would be like this:</p>
<pre><code>AA : ['MAAR', 'ASAL', 'LKT']
</code></pre>
<p>do you guys know how to do that?</p>
| 1 | 2016-10-13T06:53:01Z | 40,014,260 | <p>Sure (maybe there's a more pythonic way of doing that but that is simple and works):</p>
<pre><code>seq = ['ATGGCGGCGCGA', 'GCCTCTGCCTTG', 'CTGAAAACG']
gencode = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'}
total_result = []
for s in seq: # for each item
# listcomp to decompose & create char list
result = [gencode[s[i:i+3]] for i in range(0,len(s),3)]
total_result.append("".join(result)) # append as string
print(total_result)
</code></pre>
<p>result:</p>
<pre><code>['MAAR', 'ASAL', 'LKT']
</code></pre>
| 1 | 2016-10-13T06:57:13Z | [
"python"
] |
calling values from dict and changing values in a list | 40,014,191 | <p>I have a list of DNA sequences like this:
very small example:</p>
<pre><code>> seq = ['ATGGCGGCGCGA', 'GCCTCTGCCTTG', 'CTGAAAACG']
</code></pre>
<p>and if you divide the number of characters in each sequence by 3 you would get even number.
I also have this dictionary which is codons and amino acids. </p>
<pre><code>gencode = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'}
</code></pre>
<p>I want replace each codn (3 characters) with its amino acid(its value in the above dictionary).
the results for the small example would be like this:</p>
<pre><code>AA : ['MAAR', 'ASAL', 'LKT']
</code></pre>
<p>do you guys know how to do that?</p>
| 1 | 2016-10-13T06:53:01Z | 40,014,288 | <p>You can do one liner with list comprehension:</p>
<pre><code>seq = ['ATGGCGGCGCGA', 'GCCTCTGCCTTG', 'CTGAAAACG']
gencode = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'}
res = [''.join(gencode[s[i:i+3]] for i in range(0, len(s), 3)) for s in seq]
print(res)
</code></pre>
<p>Output:</p>
<pre><code>['MAAR', 'ASAL', 'LKT']
</code></pre>
| 2 | 2016-10-13T06:58:55Z | [
"python"
] |
calling values from dict and changing values in a list | 40,014,191 | <p>I have a list of DNA sequences like this:
very small example:</p>
<pre><code>> seq = ['ATGGCGGCGCGA', 'GCCTCTGCCTTG', 'CTGAAAACG']
</code></pre>
<p>and if you divide the number of characters in each sequence by 3 you would get even number.
I also have this dictionary which is codons and amino acids. </p>
<pre><code>gencode = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'}
</code></pre>
<p>I want replace each codn (3 characters) with its amino acid(its value in the above dictionary).
the results for the small example would be like this:</p>
<pre><code>AA : ['MAAR', 'ASAL', 'LKT']
</code></pre>
<p>do you guys know how to do that?</p>
| 1 | 2016-10-13T06:53:01Z | 40,014,441 | <p>Define a helper generator to split an iterable into chunks of length 3:</p>
<pre><code>def chunks(xs, n):
for i in range(0, len(xs), n):
yield xs[i:i + n]
</code></pre>
<p>Replace each chunk with its corresponding amino acid and group them back together:</p>
<pre><code>result = [''.join(gencode[c] for c in chunks(s, 3)) for s in seq]
</code></pre>
<p>This yields:</p>
<pre><code>In [1]: result
Out[1]: ['MAAR', 'ASAL', 'LKT']
</code></pre>
| 1 | 2016-10-13T07:07:48Z | [
"python"
] |
Is there a way to define function-dictionaries in android/Java like in python? | 40,014,231 | <p>In python it is possible to create a dictionary of functions (<code>foo,bar</code>) and call them by accessing the dictionaries element:</p>
<pre><code>d = {'a':foo, 'b':bar}
d[val]()
</code></pre>
<p>In this example if <code>var='a'</code> the function <code>foo</code> is called, and if <code>var='b'</code> the function <code>bar</code> is called (other choices lead to errors).</p>
<p>Can I do something like that in android/Java?</p>
| 0 | 2016-10-13T06:55:41Z | 40,014,286 | <p>In Java Dictionaries we will Call it as HashTable / HashMap.</p>
<p>Please have a look at this Classes.
<a href="https://developer.android.com/reference/java/util/Hashtable.html" rel="nofollow">https://developer.android.com/reference/java/util/Hashtable.html</a></p>
<p>Example of HashTable:
<a href="https://www.tutorialspoint.com/java/java_hashtable_class.htm" rel="nofollow">https://www.tutorialspoint.com/java/java_hashtable_class.htm</a></p>
<p><a href="https://developer.android.com/reference/java/util/HashMap.html" rel="nofollow">https://developer.android.com/reference/java/util/HashMap.html</a></p>
<p>Hope this will helps you :)</p>
| -1 | 2016-10-13T06:58:50Z | [
"java",
"android",
"python",
"dictionary"
] |
Is there a way to define function-dictionaries in android/Java like in python? | 40,014,231 | <p>In python it is possible to create a dictionary of functions (<code>foo,bar</code>) and call them by accessing the dictionaries element:</p>
<pre><code>d = {'a':foo, 'b':bar}
d[val]()
</code></pre>
<p>In this example if <code>var='a'</code> the function <code>foo</code> is called, and if <code>var='b'</code> the function <code>bar</code> is called (other choices lead to errors).</p>
<p>Can I do something like that in android/Java?</p>
| 0 | 2016-10-13T06:55:41Z | 40,014,313 | <p>This is easy in Python because methods are <a href="https://en.wikipedia.org/wiki/First-class_function" rel="nofollow">First-Class Citizens</a>. Whereas in Java, they are not.</p>
<p>In Java 8 -however- you can create a <code>Map</code> (in this case a <code>HashMap</code>) of <code>Runnable</code></p>
<pre><code>Map<Character, Runnable> methods= new HashMap<>();
methods.put('help', () -> System.out.println("Help"));
</code></pre>
<p>Then run it</p>
<pre><code>methods.get('help').run();
</code></pre>
<p>You can do it with reflection also but the code looks very much like this.</p>
| 0 | 2016-10-13T07:00:49Z | [
"java",
"android",
"python",
"dictionary"
] |
Is there a way to define function-dictionaries in android/Java like in python? | 40,014,231 | <p>In python it is possible to create a dictionary of functions (<code>foo,bar</code>) and call them by accessing the dictionaries element:</p>
<pre><code>d = {'a':foo, 'b':bar}
d[val]()
</code></pre>
<p>In this example if <code>var='a'</code> the function <code>foo</code> is called, and if <code>var='b'</code> the function <code>bar</code> is called (other choices lead to errors).</p>
<p>Can I do something like that in android/Java?</p>
| 0 | 2016-10-13T06:55:41Z | 40,014,319 | <pre><code>import java.util.*;
class HashMethod {
public void foo() {
System.out.println("foo");
}
public void bar() {
System.out.println("bar");
}
public static void main(String[] args) throws IllegalAccessException {
HashMethod obj = new HashMethod();
Map<Character, java.lang.reflect.Method> methods = new HashMap<Character, java.lang.reflect.Method>();
try {
Character val = 'a';
java.lang.reflect.Method method = obj.getClass().getMethod("foo");
methods.put(val, method);
Character val2 = 'b';
java.lang.reflect.Method method2 = obj.getClass().getMethod("bar");
methods.put(val2, method2);
} catch (SecurityException e) {
System.out.print("exc1" + e.toString());
} catch (NoSuchMethodException e) {
System.out.print("exc2" + e.toString());
}
Scanner s = new Scanner(System.in);
Character val = s.next().charAt(0);
try {
java.lang.reflect.Method methodToRun = ((java.lang.reflect.Method) methods.get(val));
methodToRun.invoke(obj, null);
} catch (Exception e) {
System.out.print("invalid input");
}
}
}
</code></pre>
| 0 | 2016-10-13T07:01:09Z | [
"java",
"android",
"python",
"dictionary"
] |
Momentum portfolio(trend following) quant simulation on pandas | 40,014,258 | <p>I am trying to construct trend following momentum portfolio strategy based on S&P500 index (momthly data)</p>
<p>I used Kaufmann's fractal efficiency ratio to filter out whipsaw signal
(<a href="http://etfhq.com/blog/2011/02/07/kaufmans-efficiency-ratio/" rel="nofollow">http://etfhq.com/blog/2011/02/07/kaufmans-efficiency-ratio/</a>)</p>
<p>I succeeded in coding, but it's very clumsy, so I need advice for better code.</p>
<p>Strategy </p>
<ol>
<li>Get data of S&P 500 index from yahoo finance</li>
<li>Calculate Kaufmann's efficiency ratio on lookback period X (1 , if close > close(n), 0)</li>
<li>Averages calculated value of 2, from 1 to 12 time period ---> Monthly asset allocation ratio, 1-asset allocation ratio = cash (3% per year)</li>
</ol>
<p>I am having a difficulty in averaging 1 to 12 efficiency ratio. Of course I know that it can be simply implemented by for loop and it's very easy task, but I failed.</p>
<p>I need more concise and refined code, anybody can help me?</p>
<p>a['meanfractal'] bothers me in the code below..</p>
<p>Thanks</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pandas_datareader.data as web
def price(stock, start):
price = web.DataReader(name=stock, data_source='yahoo', start=start)['Adj Close']
return price.div(price.iat[0]).resample('M').last().to_frame('price')
a = price('SPY','2000-01-01')
def fractal(a,p):
a['direction'] = np.where(a['price'].diff(p)>0,1,0)
a['abs'] = a['price'].diff(p).abs()
a['volatility'] = a.price.diff().abs().rolling(p).sum()
a['fractal'] = a['abs'].values/a['volatility'].values*a['direction'].values
return a['fractal']
def meanfractal(a):
a['meanfractal']= (fractal(a,1).values+fractal(a,2).values+fractal(a,3).values+fractal(a,4).values+fractal(a,5).values+fractal(a,6).values+fractal(a,7).values+fractal(a,8).values+fractal(a,9).values+fractal(a,10).values+fractal(a,11).values+fractal(a,12).values)/12
a['portfolio1'] = (a.price/a.price.shift(1).values*a.meanfractal.shift(1).values+(1-a.meanfractal.shift(1).values)*1.03**(1/12)).cumprod()
a['portfolio2'] = ((a.price/a.price.shift(1).values*a.meanfractal.shift(1).values+1.03**(1/12))/(1+a.meanfractal.shift(1))).cumprod()
a=a.dropna()
a=a.div(a.ix[0])
return a[['price','portfolio1','portfolio2']].plot()
print(a)
plt.show()
</code></pre>
| 0 | 2016-10-13T06:57:07Z | 40,016,938 | <p>You could simplify further by storing the values corresponding to <code>p</code> in a <code>DF</code> rather than computing for each series separately as shown:</p>
<pre><code>def fractal(a, p):
df = pd.DataFrame()
for count in range(1,p+1):
a['direction'] = np.where(a['price'].diff(count)>0,1,0)
a['abs'] = a['price'].diff(count).abs()
a['volatility'] = a.price.diff().abs().rolling(count).sum()
a['fractal'] = a['abs']/a['volatility']*a['direction']
df = pd.concat([df, a['fractal']], axis=1)
return df
</code></pre>
<p>Then, you could assign the repeating operations to a variable which reduces the re-computation time.</p>
<pre><code>def meanfractal(a, l=12):
a['meanfractal']= pd.DataFrame(fractal(a, l)).sum(1,skipna=False)/l
mean_shift = a['meanfractal'].shift(1)
price_shift = a['price'].shift(1)
factor = 1.03**(1/l)
a['portfolio1'] = (a['price']/price_shift*mean_shift+(1-mean_shift)*factor).cumprod()
a['portfolio2'] = ((a['price']/price_shift*mean_shift+factor)/(1+mean_shift)).cumprod()
a.dropna(inplace=True)
a = a.div(a.ix[0])
return a[['price','portfolio1','portfolio2']].plot()
</code></pre>
<p>Resulting plot obtained:</p>
<pre><code>meanfractal(a)
</code></pre>
<p><a href="https://i.stack.imgur.com/v4tp3.png" rel="nofollow"><img src="https://i.stack.imgur.com/v4tp3.png" alt="Image"></a></p>
<p>Note: If speed is not a major concern, you could perform the operations via the built-in methods present in <code>pandas</code> instead of converting them into it's corresponding <code>numpy</code> array values.</p>
| 1 | 2016-10-13T09:17:55Z | [
"python",
"pandas",
"quantitative-finance",
"momentum"
] |
Change Letters to numbers (ints) in python | 40,014,282 | <p>This might be python 101, but I am having a hard time changing letters into a valid integer.</p>
<p>The put what I am trying to do simply</p>
<p>char >> [ ] >> int</p>
<p>I created a case statement to give me a number depending on certain characters, so what I tried doing was</p>
<pre><code>def char_to_int(sometext):
return {
'Z':1,
'Y':17,
'X':8,
'w':4,
}.get(sometext, '')
</code></pre>
<p>Which converts the letter into a number, but when I try using that number into any argument that takes ints it doesn't work.</p>
<p>I've tried </p>
<pre><code>text_number = int(sometext)
</code></pre>
<p>But I get the message TypeError: int() argument must be a string or a number, not 'function'</p>
<p>So from there I returned the type of sometext using </p>
<pre><code>print(type(sometext))
</code></pre>
<p>And the return type is a function.</p>
<p>So my question is, is there a better way to convert letters into numbers, or a better way to setup my switch/def statement</p>
<p>Heres the full code where its call</p>
<p>if sometext:
for i in range ( 0, len(sometext)):
char_to_int(sometext[i])</p>
<p>I've managed to get it working, ultimately what I changed was the default of the definition, I now set the definition to a variable before instead of calling it in another function, and I recoded the section I was using it.</p>
<p>Originally my definition looked liked this</p>
<pre><code>def char_to_int(sometext):
return {
...
}.get(sometext, '')
</code></pre>
<p>But I changed the default to 0, so now it looks like</p>
<pre><code>def char_to_int(sometext):
return {
...
}.get(sometext, 0)
</code></pre>
<p>The old code that called the definition looked</p>
<pre><code>if sometext:
for i in range ( 0, len(sometext)):
C_T_I = int(char_to_int(sometext[i]))
</code></pre>
<p>I changed it to this.</p>
<pre><code>if sometext:
for i in range ( 0, len(sometext)):
C_T_I = char_to_int(sometext[i])
TEXTNUM = int(C_T_I)
</code></pre>
<p>Hopefully this clarifies the changes. Thanks for everyone's assistance.</p>
| -2 | 2016-10-13T06:58:37Z | 40,014,702 | <p>in the python console:</p>
<p><code>>>> type({ 'Z':1, 'Y':17, 'X':8, 'w':4, }.get('X', ''))
<class 'int'></code></p>
<p>so as cdarke suggested, you should look at how you are calling the function.</p>
| 0 | 2016-10-13T07:22:16Z | [
"python",
"switch-statement"
] |
Parse an Nginx log with Python | 40,014,283 | <p>I have this Log from Nginx server and I need to parse it with Python:</p>
<pre><code>2016/10/11 11:15:57 [debug] 44229#0: *45677 SSL_do_handshake: -1
2016/10/11 11:15:57 [debug] 44229#0: *45677 SSL_get_error: 2
2016/10/11 11:15:57 [debug] 44229#0: *45677 post event 0000000001449060
2016/10/11 11:15:57 [debug] 44229#0: *45677 delete posted event 0000000001449060
2016/10/11 11:15:57 [debug] 44229#0: *45677 SSL handshake handler: 0
2016/10/11 11:15:57 [debug] 44229#0: *45677 SSL_do_handshake: 1
2016/10/11 11:15:57 [debug] 44229#0: *45677 SSL: TLSv1.2, cipher:
2016/10/11 11:15:57 [debug] 44229#0: *45677 reusable connection: 1
2016/10/11 11:15:57 [debug] 44229#0: *45677 http wait request handler
2016/10/11 11:15:57 [debug] 44229#0: *45677 malloc: 00000000014456D0:1024
2016/10/11 11:15:57 [debug] 44229#0: *45677 SSL_read: -1
2016/10/11 11:15:57 [debug] 44229#0: *45677 SSL_get_error: 2
2016/10/11 11:15:57 [debug] 44229#0: *45677 free: 00000000014456D0
2016/10/11 11:15:57 [debug] 44229#0: *45677 post event 0000000001449060
2016/10/11 11:15:57 [debug] 44229#0: *45677 delete posted event 0000000001449060
2016/10/11 11:15:57 [debug] 44229#0: *45677 http wait request handler
2016/10/11 11:15:57 [debug] 44229#0: *45677 malloc: 00000000014456D0:1024
2016/10/11 11:15:57 [debug] 44229#0: *45677 SSL_read: 144
2016/10/11 11:15:57 [debug] 44229#0: *45677 SSL_read: -1
2016/10/11 11:15:57 [debug] 44229#0: *45677 SSL_get_error: 2
2016/10/11 11:15:57 [debug] 44229#0: *45677 reusable connection: 0
2016/10/11 11:15:57 [debug] 44229#0: *45677 posix_memalign: 00000000014974A0:4096 @16
2016/10/11 11:15:57 [debug] 44229#0: *45677 http process request line
2016/10/11 11:15:57 [debug] 44229#0: *45677 http request line: "POST / HTTP/1.1"
2016/10/11 11:15:57 [debug] 44229#0: *45677 http uri: "/"
2016/10/11 11:15:57 [debug] 44229#0: *45677 http args: ""
2016/10/11 11:15:57 [debug] 44229#0: *45677 http exten: ""
2016/10/11 11:15:57 [debug] 44229#0: *45677 http process request header line
2016/10/11 11:15:57 [debug] 44229#0: *45677 http header: "Host:"
2016/10/11 11:15:57 [debug] 44229#0: *45677 http header: "Transfer-Encoding: chunked"
2016/10/11 11:15:57 [debug] 44229#0: *45677 http header: "Accept: */*"
2016/10/11 11:15:57 [debug] 44229#0: *45677 http header: "content-type: application/json"
2016/10/11 11:15:57 [debug] 44229#0: *45677 posix_memalign: 00000000016689D0:4096 @16
2016/10/11 11:15:57 [debug] 44229#0: *45677 http header: "Content-Length: 149"
2016/10/11 11:15:58 [debug] 44229#0: *45677 post event 0000000001449060
2016/10/11 11:15:58 [debug] 44229#0: *45677 delete posted event 0000000001449060
2016/10/11 11:15:58 [debug] 44229#0: *45677 http process request header line
2016/10/11 11:15:58 [debug] 44229#0: *45677 SSL_read: 6
2016/10/11 11:15:58 [debug] 44229#0: *45677 SSL_read: 149
2016/10/11 11:15:58 [debug] 44229#0: *45677 SSL_read: 7
2016/10/11 11:15:58 [debug] 44229#0: *45677 SSL_read: -1
2016/10/11 11:15:58 [debug] 44229#0: *45677 SSL_get_error: 2
2016/10/11 11:15:58 [debug] 44229#0: *45677 http header done
2016/10/11 11:15:58 [debug] 44229#0: *45677 event timer del: 43: 1476177405011
2016/10/11 11:15:58 [debug] 44229#0: *45677 generic phase: 0
2016/10/11 11:15:58 [debug] 44229#0: *45677 rewrite phase: 1
2016/10/11 11:15:58 [debug] 44229#0: *45677 test location: "/"
2016/10/11 11:15:58 [debug] 44229#0: *45677 using configuration "/"
2016/10/11 11:15:58 [debug] 44229#0: *45677 http cl:-1 max:1048576
2016/10/11 11:15:58 [debug] 44229#0: *45677 rewrite phase: 3
2016/10/11 11:15:58 [debug] 44229#0: *45677 http set discard body
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 39 s:0
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 35 s:1
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 0D s:1
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 0A s:3
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 7B s:4
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 0D s:5
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 0A s:6
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 30 s:0
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 0D s:1
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 0A s:8
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 0D s:9
2016/10/11 11:15:58 [debug] 44229#0: *45677 http chunked byte: 0A s:10
2016/10/11 11:15:58 [debug] 44229#0: *45677 xslt filter header
2016/10/11 11:15:58 [debug] 44229#0: *45677 HTTP/1.1 200 OK
2016/10/11 11:15:58 [debug] 44229#0: *45677 write new buf t:1 f:0 0000000001668BF0, pos 0000000001668BF0, size: 160 file: 0, size: 0
2016/10/11 11:15:58 [debug] 44229#0: *45677 http write filter: l:0 f:0 s:160
2016/10/11 11:15:58 [debug] 44229#0: *45677 http output filter "/?"
2016/10/11 11:15:58 [debug] 44229#0: *45677 http copy filter: "/?"
2016/10/11 11:15:58 [debug] 44229#0: *45677 image filter
2016/10/11 11:15:58 [debug] 44229#0: *45677 xslt filter body
2016/10/11 11:15:58 [debug] 44229#0: *45677 http postpone filter "/?" 00007FFFADE3C4A0
2016/10/11 11:15:58 [debug] 44229#0: *45677 write old buf t:1 f:0 0000000001668BF0, pos 0000000001668BF0, size: 160 file: 0, size: 0
2016/10/11 11:15:58 [debug] 44229#0: *45677 write new buf t:0 f:0 0000000000000000, pos 0000000000000000, size: 0 file: 0, size: 0
2016/10/11 11:15:58 [debug] 44229#0: *45677 http write filter: l:1 f:0 s:160
2016/10/11 11:15:58 [debug] 44229#0: *45677 http write filter limit 0
2016/10/11 11:15:58 [debug] 44229#0: *45677 posix_memalign: 0000000001499DB0:256 @16
2016/10/11 11:15:58 [debug] 44229#0: *45677 malloc: 000000000175B750:16384
2016/10/11 11:15:58 [debug] 44229#0: *45677 SSL buf copy: 160
2016/10/11 11:15:58 [debug] 44229#0: *45677 SSL to write: 160
2016/10/11 11:15:58 [debug] 44229#0: *45677 SSL_write: 160
2016/10/11 11:15:58 [debug] 44229#0: *45677 http write filter 0000000000000000
2016/10/11 11:15:58 [debug] 44229#0: *45677 http copy filter: 0 "/?"
2016/10/11 11:15:58 [debug] 44229#0: *45677 http finalize request: 0, "/?" a:1, c:1
2016/10/11 11:15:58 [debug] 44229#0: *45677 set http keepalive handler
2016/10/11 11:15:58 [debug] 44229#0: *45677 http close request
2016/10/11 11:15:58 [debug] 44229#0: *45677 http log handler
2016/10/11 11:15:58 [debug] 44229#0: *45677 free: 00000000014974A0, unused: 1
2016/10/11 11:15:58 [debug] 44229#0: *45677 free: 00000000016689D0, unused: 3109
2016/10/11 11:15:58 [debug] 44229#0: *45677 free: 00000000014456D0
2016/10/11 11:15:58 [debug] 44229#0: *45677 hc free: 0000000000000000 0
2016/10/11 11:15:58 [debug] 44229#0: *45677 hc busy: 0000000000000000 0
2016/10/11 11:15:58 [debug] 44229#0: *45677 free: 000000000175B750
2016/10/11 11:15:58 [debug] 44229#0: *45677 tcp_nodelay
2016/10/11 11:15:58 [debug] 44229#0: *45677 reusable connection: 1
2016/10/11 11:15:58 [debug] 44229#0: *45677 event timer add: 43: 65000:1476177423255
2016/10/11 11:17:03 [debug] 44229#0: *45677 event timer del: 43: 1476177423255
2016/10/11 11:17:03 [debug] 44229#0: *45677 http keepalive handler
2016/10/11 11:17:03 [debug] 44229#0: *45677 close http connection: 43
2016/10/11 11:17:03 [debug] 44229#0: *45677 SSL_shutdown: 1
2016/10/11 11:17:03 [debug] 44229#0: *45677 reusable connection: 0
2016/10/11 11:17:03 [debug] 44229#0: *45677 free: 0000000000000000
2016/10/11 11:17:03 [debug] 44229#0: *45677 free: 0000000000000000
2016/10/11 11:17:03 [debug] 44229#0: *45677 free: 00000000014462C0, unused: 8
2016/10/11 11:17:03 [debug] 44229#0: *45677 free: 000000000149ACF0, unused: 8
2016/10/11 11:17:03 [debug] 44229#0: *45677 free: 0000000001499DB0, unused: 144
2016/10/11 11:19:22 [debug] 44231#0: *45709 event timer add: 8: 60000:1476177622411
2016/10/11 11:19:22 [debug] 44231#0: *45709 reusable connection: 1
2016/10/11 11:19:22 [debug] 44231#0: *45709 epoll add event: fd:8 op:1 ev:80002001
2016/10/11 11:19:23 [debug] 44231#0: *45709 post event 0000000001448EE0
2016/10/11 11:19:23 [debug] 44231#0: *45709 delete posted event 0000000001448EE0
2016/10/11 11:19:23 [debug] 44231#0: *45709 http check ssl handshake
2016/10/11 11:19:23 [debug] 44231#0: *45709 http recv(): 1
2016/10/11 11:19:23 [debug] 44231#0: *45709 https ssl handshake: 0x16
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL_do_handshake: -1
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL_get_error: 2
2016/10/11 11:19:23 [debug] 44231#0: *45709 reusable connection: 0
2016/10/11 11:19:23 [debug] 44231#0: *45709 post event 0000000001448EE0
2016/10/11 11:19:23 [debug] 44231#0: *45709 delete posted event 0000000001448EE0
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL handshake handler: 0
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL_do_handshake: -1
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL_get_error: 2
2016/10/11 11:19:23 [debug] 44231#0: *45709 post event 0000000001448EE0
2016/10/11 11:19:23 [debug] 44231#0: *45709 delete posted event 0000000001448EE0
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL handshake handler: 0
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL_do_handshake: 1
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL: TLSv1.2, cipher:
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL reused session
2016/10/11 11:19:23 [debug] 44231#0: *45709 reusable connection: 1
2016/10/11 11:19:23 [debug] 44231#0: *45709 http wait request handler
2016/10/11 11:19:23 [debug] 44231#0: *45709 malloc: 00000000014E16E0:1024
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL_read: -1
2016/10/11 11:19:23 [debug] 44231#0: *45709 SSL_get_error: 2
2016/10/11 11:19:23 [debug] 44231#0: *45709 free: 00000000014E16E0
2016/10/11 11:19:24 [debug] 44231#0: *45709 post event 0000000001448EE0
2016/10/11 11:19:24 [debug] 44231#0: *45709 delete posted event 0000000001448EE0
2016/10/11 11:19:24 [debug] 44231#0: *45709 http wait request handler
2016/10/11 11:19:24 [debug] 44231#0: *45709 malloc: 00000000014E16E0:1024
2016/10/11 11:19:24 [debug] 44231#0: *45709 SSL_read: 144
2016/10/11 11:19:24 [debug] 44231#0: *45709 SSL_read: 6
2016/10/11 11:19:24 [debug] 44231#0: *45709 SSL_read: 149
2016/10/11 11:19:24 [debug] 44231#0: *45709 SSL_read: 7
2016/10/11 11:19:24 [debug] 44231#0: *45709 SSL_read: -1
2016/10/11 11:19:24 [debug] 44231#0: *45709 SSL_get_error: 2
2016/10/11 11:19:24 [debug] 44231#0: *45709 reusable connection: 0
2016/10/11 11:19:24 [debug] 44231#0: *45709 posix_memalign: 00000000015541A0:4096 @16
2016/10/11 11:19:24 [debug] 44231#0: *45709 http process request line
2016/10/11 11:19:24 [debug] 44231#0: *45709 http request line: "POST / HTTP/1.1"
2016/10/11 11:19:24 [debug] 44231#0: *45709 http uri: "/"
2016/10/11 11:19:24 [debug] 44231#0: *45709 http args: ""
2016/10/11 11:19:24 [debug] 44231#0: *45709 http exten: ""
2016/10/11 11:19:24 [debug] 44231#0: *45709 http process request header line
2016/10/11 11:19:24 [debug] 44231#0: *45709 http header: "Host:"
2016/10/11 11:19:24 [debug] 44231#0: *45709 http header: "Transfer-Encoding: chunked"
2016/10/11 11:19:24 [debug] 44231#0: *45709 http header: "Accept: */*"
2016/10/11 11:19:24 [debug] 44231#0: *45709 http header: "content-type: application/json"
2016/10/11 11:19:24 [debug] 44231#0: *45709 posix_memalign: 0000000001466290:4096 @16
2016/10/11 11:19:24 [debug] 44231#0: *45709 http header: "Content-Length: 149"
2016/10/11 11:19:24 [debug] 44231#0: *45709 http header done
2016/10/11 11:19:24 [debug] 44231#0: *45709 event timer del: 8: 1476177622411
2016/10/11 11:19:24 [debug] 44231#0: *45709 generic phase: 0
2016/10/11 11:19:24 [debug] 44231#0: *45709 rewrite phase: 1
2016/10/11 11:19:24 [debug] 44231#0: *45709 test location: "/"
2016/10/11 11:19:24 [debug] 44231#0: *45709 using configuration "/"
2016/10/11 11:19:24 [debug] 44231#0: *45709 http cl:-1 max:1048576
2016/10/11 11:19:24 [debug] 44231#0: *45709 rewrite phase: 3
2016/10/11 11:19:24 [debug] 44231#0: *45709 http set discard body
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 39 s:0
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 35 s:1
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 0D s:1
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 0A s:3
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 7B s:4
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 0D s:5
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 0A s:6
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 30 s:0
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 0D s:1
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 0A s:8
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 0D s:9
2016/10/11 11:19:24 [debug] 44231#0: *45709 http chunked byte: 0A s:10
2016/10/11 11:19:24 [debug] 44231#0: *45709 xslt filter header
2016/10/11 11:19:24 [debug] 44231#0: *45709 HTTP/1.1 200 OK
2016/10/11 11:19:24 [debug] 44231#0: *45709 write new buf t:1 f:0 00000000014664B0, pos 00000000014664B0, size: 160 file: 0, size: 0
2016/10/11 11:19:24 [debug] 44231#0: *45709 http write filter: l:0 f:0 s:160
2016/10/11 11:19:24 [debug] 44231#0: *45709 http output filter "/?"
2016/10/11 11:19:24 [debug] 44231#0: *45709 http copy filter: "/?"
2016/10/11 11:19:24 [debug] 44231#0: *45709 image filter
2016/10/11 11:19:24 [debug] 44231#0: *45709 xslt filter body
2016/10/11 11:19:24 [debug] 44231#0: *45709 http postpone filter "/?" 00007FFFADE3C420
2016/10/11 11:19:24 [debug] 44231#0: *45709 write old buf t:1 f:0 00000000014664B0, pos 00000000014664B0, size: 160 file: 0, size: 0
2016/10/11 11:19:24 [debug] 44231#0: *45709 write new buf t:0 f:0 0000000000000000, pos 0000000000000000, size: 0 file: 0, size: 0
2016/10/11 11:19:24 [debug] 44231#0: *45709 http write filter: l:1 f:0 s:160
2016/10/11 11:19:24 [debug] 44231#0: *45709 http write filter limit 0
2016/10/11 11:19:24 [debug] 44231#0: *45709 posix_memalign: 00000000014672A0:256 @16
2016/10/11 11:19:24 [debug] 44231#0: *45709 malloc: 000000000151CF30:16384
2016/10/11 11:19:24 [debug] 44231#0: *45709 SSL buf copy: 160
2016/10/11 11:19:24 [debug] 44231#0: *45709 SSL to write: 160
2016/10/11 11:19:24 [debug] 44231#0: *45709 SSL_write: 160
2016/10/11 11:19:24 [debug] 44231#0: *45709 http write filter 0000000000000000
2016/10/11 11:19:24 [debug] 44231#0: *45709 http copy filter: 0 "/?"
2016/10/11 11:19:24 [debug] 44231#0: *45709 http finalize request: 0, "/?" a:1, c:1
2016/10/11 11:19:24 [debug] 44231#0: *45709 set http keepalive handler
2016/10/11 11:19:24 [debug] 44231#0: *45709 http close request
2016/10/11 11:19:24 [debug] 44231#0: *45709 http log handler
2016/10/11 11:19:24 [debug] 44231#0: *45709 free: 00000000015541A0, unused: 1
2016/10/11 11:19:24 [debug] 44231#0: *45709 free: 0000000001466290, unused: 3110
2016/10/11 11:19:24 [debug] 44231#0: *45709 free: 00000000014E16E0
2016/10/11 11:19:24 [debug] 44231#0: *45709 hc free: 0000000000000000 0
2016/10/11 11:19:24 [debug] 44231#0: *45709 hc busy: 0000000000000000 0
2016/10/11 11:19:24 [debug] 44231#0: *45709 free: 000000000151CF30
2016/10/11 11:19:24 [debug] 44231#0: *45709 tcp_nodelay
2016/10/11 11:19:24 [debug] 44231#0: *45709 reusable connection: 1
2016/10/11 11:19:24 [debug] 44231#0: *45709 event timer add: 8: 65000:1476177629112
2016/10/11 11:20:29 [debug] 44231#0: *45709 event timer del: 8: 1476177629112
2016/10/11 11:20:29 [debug] 44231#0: *45709 http keepalive handler
2016/10/11 11:20:29 [debug] 44231#0: *45709 close http connection: 8
2016/10/11 11:20:29 [debug] 44231#0: *45709 SSL_shutdown: 1
2016/10/11 11:20:29 [debug] 44231#0: *45709 reusable connection: 0
2016/10/11 11:20:29 [debug] 44231#0: *45709 free: 0000000000000000
2016/10/11 11:20:29 [debug] 44231#0: *45709 free: 0000000000000000
2016/10/11 11:20:29 [debug] 44231#0: *45709 free: 00000000014EA310, unused: 8
2016/10/11 11:20:29 [debug] 44231#0: *45709 free: 00000000014E9EA0, unused: 8
2016/10/11 11:20:29 [debug] 44231#0: *45709 free: 00000000014672A0, unused: 144
2016/10/11 12:20:38 [debug] 44231#0: *46332 event timer add: 4: 60000:1476181298580
2016/10/11 12:20:38 [debug] 44231#0: *46332 reusable connection: 1
2016/10/11 12:20:38 [debug] 44231#0: *46332 epoll add event: fd:4 op:1 ev:80002001
2016/10/11 12:20:39 [debug] 44231#0: *46332 post event 0000000001449120
2016/10/11 12:20:39 [debug] 44231#0: *46332 delete posted event 0000000001449120
2016/10/11 12:20:39 [debug] 44231#0: *46332 http check ssl handshake
2016/10/11 12:20:39 [debug] 44231#0: *46332 http recv(): 1
2016/10/11 12:20:39 [debug] 44231#0: *46332 https ssl handshake: 0x16
2016/10/11 12:20:39 [debug] 44231#0: *46332 SSL_do_handshake: -1
2016/10/11 12:20:39 [debug] 44231#0: *46332 SSL_get_error: 2
2016/10/11 12:20:39 [debug] 44231#0: *46332 reusable connection: 0
2016/10/11 12:20:39 [debug] 44231#0: *46332 post event 0000000001449120
2016/10/11 12:20:39 [debug] 44231#0: *46332 delete posted event 0000000001449120
2016/10/11 12:20:39 [debug] 44231#0: *46332 SSL handshake handler: 0
2016/10/11 12:20:39 [debug] 44231#0: *46332 SSL_do_handshake: -1
2016/10/11 12:20:39 [debug] 44231#0: *46332 SSL_get_error: 2
2016/10/11 12:20:58 [debug] 44231#0: *46332 post event 0000000001449120
2016/10/11 12:20:58 [debug] 44231#0: *46332 delete posted event 0000000001449120
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL handshake handler: 0
2016/10/11 12:20:58 [debug] 44231#0: *46332 verify:1, error:0, depth:1, subject¡
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL_do_handshake: -1
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL_get_error: 2
2016/10/11 12:20:58 [debug] 44231#0: *46332 post event 0000000001449120
2016/10/11 12:20:58 [debug] 44231#0: *46332 delete posted event 0000000001449120
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL handshake handler: 0
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL_do_handshake: -1
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL_get_error: 2
2016/10/11 12:20:58 [debug] 44231#0: *46332 post event 0000000001449120
2016/10/11 12:20:58 [debug] 44231#0: *46332 delete posted event 0000000001449120
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL handshake handler: 0
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL_do_handshake: 1
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL: TLSv1.2, cipher:
2016/10/11 12:20:58 [debug] 44231#0: *46332 reusable connection: 1
2016/10/11 12:20:58 [debug] 44231#0: *46332 http wait request handler
2016/10/11 12:20:58 [debug] 44231#0: *46332 malloc: 00000000014456D0:1024
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL_read: -1
2016/10/11 12:20:58 [debug] 44231#0: *46332 SSL_get_error: 2
2016/10/11 12:20:58 [debug] 44231#0: *46332 free: 00000000014456D0
2016/10/11 12:20:59 [debug] 44231#0: *46332 post event 0000000001449120
2016/10/11 12:20:59 [debug] 44231#0: *46332 delete posted event 0000000001449120
2016/10/11 12:20:59 [debug] 44231#0: *46332 http wait request handler
2016/10/11 12:20:59 [debug] 44231#0: *46332 malloc: 00000000014456D0:1024
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL_read: 144
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL_read: -1
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL_get_error: 2
2016/10/11 12:20:59 [debug] 44231#0: *46332 reusable connection: 0
2016/10/11 12:20:59 [debug] 44231#0: *46332 posix_memalign: 00000000016F1CC0:4096 @16
2016/10/11 12:20:59 [debug] 44231#0: *46332 http process request line
2016/10/11 12:20:59 [debug] 44231#0: *46332 http request line: "POST / HTTP/1.1"
2016/10/11 12:20:59 [debug] 44231#0: *46332 http uri: "/"
2016/10/11 12:20:59 [debug] 44231#0: *46332 http args: ""
2016/10/11 12:20:59 [debug] 44231#0: *46332 http exten: ""
2016/10/11 12:20:59 [debug] 44231#0: *46332 http process request header line
2016/10/11 12:20:59 [debug] 44231#0: *46332 http header: "Host:"
2016/10/11 12:20:59 [debug] 44231#0: *46332 http header: "Transfer-Encoding: chunked"
2016/10/11 12:20:59 [debug] 44231#0: *46332 http header: "Accept: */*"
2016/10/11 12:20:59 [debug] 44231#0: *46332 http header: "content-type: application/json"
2016/10/11 12:20:59 [debug] 44231#0: *46332 posix_memalign: 00000000014974A0:4096 @16
2016/10/11 12:20:59 [debug] 44231#0: *46332 http header: "Content-Length: 149"
2016/10/11 12:20:59 [debug] 44231#0: *46332 post event 0000000001449120
2016/10/11 12:20:59 [debug] 44231#0: *46332 delete posted event 0000000001449120
2016/10/11 12:20:59 [debug] 44231#0: *46332 http process request header line
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL_read: 6
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL_read: 149
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL_read: 7
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL_read: -1
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL_get_error: 2
2016/10/11 12:20:59 [debug] 44231#0: *46332 http header done
2016/10/11 12:20:59 [debug] 44231#0: *46332 event timer del: 4: 1476181298580
2016/10/11 12:20:59 [debug] 44231#0: *46332 generic phase: 0
2016/10/11 12:20:59 [debug] 44231#0: *46332 rewrite phase: 1
2016/10/11 12:20:59 [debug] 44231#0: *46332 test location: "/"
2016/10/11 12:20:59 [debug] 44231#0: *46332 using configuration "/"
2016/10/11 12:20:59 [debug] 44231#0: *46332 http cl:-1 max:1048576
2016/10/11 12:20:59 [debug] 44231#0: *46332 rewrite phase: 3
2016/10/11 12:20:59 [debug] 44231#0: *46332 http set discard body
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 39 s:0
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 35 s:1
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 0D s:1
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 0A s:3
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 7B s:4
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 0D s:5
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 0A s:6
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 30 s:0
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 0D s:1
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 0A s:8
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 0D s:9
2016/10/11 12:20:59 [debug] 44231#0: *46332 http chunked byte: 0A s:10
2016/10/11 12:20:59 [debug] 44231#0: *46332 xslt filter header
2016/10/11 12:20:59 [debug] 44231#0: *46332 HTTP/1.1 200 OK
2016/10/11 12:20:59 [debug] 44231#0: *46332 write new buf t:1 f:0 00000000014976C0, pos 00000000014976C0, size: 160 file: 0, size: 0
2016/10/11 12:20:59 [debug] 44231#0: *46332 http write filter: l:0 f:0 s:160
2016/10/11 12:20:59 [debug] 44231#0: *46332 http output filter "/?"
2016/10/11 12:20:59 [debug] 44231#0: *46332 http copy filter: "/?"
2016/10/11 12:20:59 [debug] 44231#0: *46332 image filter
2016/10/11 12:20:59 [debug] 44231#0: *46332 xslt filter body
2016/10/11 12:20:59 [debug] 44231#0: *46332 http postpone filter "/?" 00007FFFADE3C4A0
2016/10/11 12:20:59 [debug] 44231#0: *46332 write old buf t:1 f:0 00000000014976C0, pos 00000000014976C0, size: 160 file: 0, size: 0
2016/10/11 12:20:59 [debug] 44231#0: *46332 write new buf t:0 f:0 0000000000000000, pos 0000000000000000, size: 0 file: 0, size: 0
2016/10/11 12:20:59 [debug] 44231#0: *46332 http write filter: l:1 f:0 s:160
2016/10/11 12:20:59 [debug] 44231#0: *46332 http write filter limit 0
2016/10/11 12:20:59 [debug] 44231#0: *46332 posix_memalign: 00000000014E78E0:256 @16
2016/10/11 12:20:59 [debug] 44231#0: *46332 malloc: 000000000147DF50:16384
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL buf copy: 160
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL to write: 160
2016/10/11 12:20:59 [debug] 44231#0: *46332 SSL_write: 160
2016/10/11 12:20:59 [debug] 44231#0: *46332 http write filter 0000000000000000
2016/10/11 12:20:59 [debug] 44231#0: *46332 http copy filter: 0 "/?"
2016/10/11 12:20:59 [debug] 44231#0: *46332 http finalize request: 0, "/?" a:1, c:1
2016/10/11 12:20:59 [debug] 44231#0: *46332 set http keepalive handler
2016/10/11 12:20:59 [debug] 44231#0: *46332 http close request
2016/10/11 12:20:59 [debug] 44231#0: *46332 http log handler
2016/10/11 12:20:59 [debug] 44231#0: *46332 free: 00000000016F1CC0, unused: 1
2016/10/11 12:20:59 [debug] 44231#0: *46332 free: 00000000014974A0, unused: 3108
2016/10/11 12:20:59 [debug] 44231#0: *46332 free: 00000000014456D0
2016/10/11 12:20:59 [debug] 44231#0: *46332 hc free: 0000000000000000 0
2016/10/11 12:20:59 [debug] 44231#0: *46332 hc busy: 0000000000000000 0
2016/10/11 12:20:59 [debug] 44231#0: *46332 free: 000000000147DF50
2016/10/11 12:20:59 [debug] 44231#0: *46332 tcp_nodelay
2016/10/11 12:20:59 [debug] 44231#0: *46332 reusable connection: 1
2016/10/11 12:20:59 [debug] 44231#0: *46332 event timer add: 4: 65000:1476181324667
2016/10/11 12:22:04 [debug] 44231#0: *46332 event timer del: 4: 1476181324667
2016/10/11 12:22:04 [debug] 44231#0: *46332 http keepalive handler
2016/10/11 12:22:04 [debug] 44231#0: *46332 close http connection: 4
2016/10/11 12:22:04 [debug] 44231#0: *46332 SSL_shutdown: 1
2016/10/11 12:22:04 [debug] 44231#0: *46332 reusable connection: 0
2016/10/11 12:22:04 [debug] 44231#0: *46332 free: 0000000000000000
2016/10/11 12:22:04 [debug] 44231#0: *46332 free: 0000000000000000
2016/10/11 12:22:04 [debug] 44231#0: *46332 free: 00000000015D79A0, unused: 8
2016/10/11 12:22:04 [debug] 44231#0: *46332 free: 000000000156C5F0, unused: 8
2016/10/11 12:22:04 [debug] 44231#0: *46332 free: 00000000014E78E0, unused: 144
</code></pre>
<p>I want to parse a several key sentences and depends if they are on the line or not, I only want to catch the <code>date</code>, <code>hour</code> and <code>identifier</code> from the first case <code>http check ssl handshake</code> and then take only the hours of the other key sentences, like <code>SSL: TSLv1.2, chiper:</code>, <code>http process request line</code> or <code>http close request</code>.
The expected result would be something like:</p>
<pre><code>39957, 2016/10/11, 10:49:59, 10:50:11, 10:50:12, 10:50:12, 0
</code></pre>
<p>or</p>
<pre><code>39957, 2016/10/11, 10:49:59, 10:50:11, 10:50:12, 10:50:12, 1
</code></pre>
<p>(The final <code>1</code> or <code>0</code> is for the sentence "<code>SSL reused session</code>" exists)</p>
<p>I'm trying with this piece of ode in <code>Python</code>, but I can't get my desired results:</p>
<pre><code>#!/usr/bin/env python
import re
file = open('log_to_parse.txt', 'r')
openFile = file.readlines()
file.close()
resultsFile = open('resultsFile.txt', 'a')
printList = []
identifierNew ="45"
identifierOld = "467"
#reuseSession = []
sentencesToFind = ["http check ssl handshake","SSL: TLSv1.2, cipher:","http process request line","http close request","SSL reused session"]
for line in openFile:
lineSplitted = line.split(' ')
identifierOld = lineSplitted[3]
for phrase in sentencesToFind:
if phrase in line:
if identifierNew != identifierOld:
print >> resultsFile, "\n"
printList = []
else:
if sentencesToFind.index(phrase) == 0:
printList.append(lineSplitted[3]) #+ " " + lineSplitted[0] + " " + lineSplitted[1] + " ")
printList.append(lineSplitted[0])
printList.append(lineSplitted[1])
elif sentencesToFind.index(phrase) == 4:
printList.append("0")
else:
printList.append(lineSplitted[1])
identifierNew = identifierOld
if printList:
print >>resultsFile, printList
printList = []
resultsFile.close()
</code></pre>
<p>I don't know what is going wrong, but I'm not an expert in Python... </p>
<p>EDIT: I get this </p>
<pre><code>['11:15:57', '11:15:57', '11:15:58', '44231#0:', '2016/10/11', '11:19:23', '11:19:23', '0', '11:19:24', '11:19:24', '44231#0:', '2016/10/11', '12:20:39', '12:20:58', '12:20:59', '12:20:59']
</code></pre>
<p>Thank you!</p>
| 0 | 2016-10-13T06:58:40Z | 40,051,743 | <p>If you just want a comma delimited string to be printed out, you can change the line</p>
<pre><code>print >>resultsFile, printList
</code></pre>
<p>to:</p>
<pre><code>print >>resultsFile, ",".join(printList)
</code></pre>
| 1 | 2016-10-14T20:46:54Z | [
"python",
"regex",
"parsing",
"nginx"
] |
Initialize variable depending on another variables type | 40,014,390 | <p>In Python 2.7 I want to intialize a variables type depending on another variable.</p>
<p>For example I want to do something like:</p>
<pre><code>var_1 = type(var_2)
</code></pre>
<p>Is there a simple/fast way to do that?</p>
| 3 | 2016-10-13T07:04:48Z | 40,014,466 | <p>Just create another instance</p>
<pre><code>var_1 = type(var_2)()
</code></pre>
<p>Note that if you're not sure whether the object has a non-default constructor, you cannot rely on the above, but you can use <code>copy</code> or <code>deepcopy</code> (you get a "non-empty" object.</p>
<pre><code>import copy
var_1 = copy.copy(var_2) # or copy.deepcopy
</code></pre>
<p>You could use both combined with the latter as a fallback mechanism</p>
<p>Note: <code>deepcopy</code> will ensure that your second object is completely independent from the first (If there are lists of lists, for instance)</p>
| 2 | 2016-10-13T07:09:07Z | [
"python",
"python-2.7"
] |
Initialize variable depending on another variables type | 40,014,390 | <p>In Python 2.7 I want to intialize a variables type depending on another variable.</p>
<p>For example I want to do something like:</p>
<pre><code>var_1 = type(var_2)
</code></pre>
<p>Is there a simple/fast way to do that?</p>
| 3 | 2016-10-13T07:04:48Z | 40,014,469 | <pre><code>a = 1 # a is an int
a_type = type(a) # a_type now contains the int-type
b = '1' # '1' is a string
c = a_type(b) # c is now an int with the value 1
</code></pre>
<p>So you can get the type of a variable using <code>type()</code>. You can then store this type in a variable and you can then use that variable just like you would use <code>int(b)</code>, <code>str(b)</code>, <code>float(b)</code> etc. </p>
| 2 | 2016-10-13T07:09:24Z | [
"python",
"python-2.7"
] |
How to wait for the site to return the data using Beautifulsoup4 | 40,014,395 | <p>I wrote a script using beautifulsoup4 , the script basically brings the list of ciphers from the table present on a web page. The problem is my python script doesn't wait for the returned content of the web page and either breaks or says 'list index out of range'. The code is as follows: </p>
<pre><code>ssl_lab_url = 'https://www.ssllabs.com/ssltest/analyze.html?d='+site
req = requests.get(ssl_lab_url)
data = req.text
soup = BeautifulSoup(data)
print CYELLOW+"Now Bringing in the LIST of cipher gathered from SSL LABS for "+str(ssl_lab_url)+CEND
for i in tqdm(range(10000)):
sleep(0.01)
table = soup.find_all('table',class_='reportTable', limit=5)[-1]
data = [ str(td.text.split()[0]) for td in table.select("td.tableLeft")]
print CGREEN+str(data)+CEND
time.sleep(1)
</code></pre>
<p>It sometimes return NOTHING in <code>data</code> or says :</p>
<pre><code>Traceback (most recent call last):
File "multiple_scan_es.py", line 79, in <module>
scan_cipher_ssl(list_url )
File "multiple_scan_es.py", line 62, in scan_cipher_ssl
table = soup.find_all('table',class_='reportTable', limit=5)[-1]
IndexError: list index out of range
</code></pre>
<p>I need to wait here , how to do so ?</p>
| 0 | 2016-10-13T07:05:00Z | 40,014,536 | <p>If the data isn't present in the original HTML page but is returned from JS code in the background, consider using a headless browser, such as PhantomJS, with Selenium. <a href="https://realpython.com/blog/python/headless-selenium-testing-with-python-and-phantomjs/" rel="nofollow">Here's an example</a>.</p>
| 1 | 2016-10-13T07:13:14Z | [
"python",
"beautifulsoup"
] |
How to wait for the site to return the data using Beautifulsoup4 | 40,014,395 | <p>I wrote a script using beautifulsoup4 , the script basically brings the list of ciphers from the table present on a web page. The problem is my python script doesn't wait for the returned content of the web page and either breaks or says 'list index out of range'. The code is as follows: </p>
<pre><code>ssl_lab_url = 'https://www.ssllabs.com/ssltest/analyze.html?d='+site
req = requests.get(ssl_lab_url)
data = req.text
soup = BeautifulSoup(data)
print CYELLOW+"Now Bringing in the LIST of cipher gathered from SSL LABS for "+str(ssl_lab_url)+CEND
for i in tqdm(range(10000)):
sleep(0.01)
table = soup.find_all('table',class_='reportTable', limit=5)[-1]
data = [ str(td.text.split()[0]) for td in table.select("td.tableLeft")]
print CGREEN+str(data)+CEND
time.sleep(1)
</code></pre>
<p>It sometimes return NOTHING in <code>data</code> or says :</p>
<pre><code>Traceback (most recent call last):
File "multiple_scan_es.py", line 79, in <module>
scan_cipher_ssl(list_url )
File "multiple_scan_es.py", line 62, in scan_cipher_ssl
table = soup.find_all('table',class_='reportTable', limit=5)[-1]
IndexError: list index out of range
</code></pre>
<p>I need to wait here , how to do so ?</p>
| 0 | 2016-10-13T07:05:00Z | 40,015,599 | <p>I was thinking that this page use JavaScript to get data but it use old HTML method to refresh page. </p>
<p>It adds HTML tag <code><meta http-equiv="refresh" content='**time**; url></code> and browser will reload page after <strong>time</strong> seconds.</p>
<p>You have to check this tag - if you find it then you can wait and you have to load page again. Mostly you can reload page without waiting and you get data or you find this tag again.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import time
site = 'some_site_name.com'
url = 'https://www.ssllabs.com/ssltest/analyze.html?d='+site
# ---
while True:
r = requests.get(url)
soup = BeautifulSoup(r.text)
refresh = soup.find_all('meta', attrs={'http-equiv': 'refresh'})
#print 'refresh:', refresh
if not refresh:
break
#wait = int(refresh[0].get('content','0').split(';')[0])
#print 'wait:', wait
#time.sleep(wait)
# ---
table = soup.find_all('table', class_='reportTable', limit=5)
if table:
table = table[-1]
data = [str(td.text.split()[0]) for td in table.select("td.tableLeft")]
print str(data)
else:
print "[!] no data"
</code></pre>
| 1 | 2016-10-13T08:10:45Z | [
"python",
"beautifulsoup"
] |
Updating other players screen Django | 40,014,528 | <p>I am developing a small game with four members for a board. When a player moves something, that move has to updated in remaining players screen(their webpage). I ended up tornado, but I can't find any examples for my case. </p>
<p>I need to display the move to all players when a move was saved in DB. Polling DB continuously after x seconds may miss some moves. How can I achieve this. </p>
| 0 | 2016-10-13T07:12:45Z | 40,017,978 | <p>Use websockets instead. Here's the <a href="http://www.tornadoweb.org/en/stable/websocket.html" rel="nofollow">documentation</a> with a simple example.</p>
| 0 | 2016-10-13T10:03:01Z | [
"python",
"django",
"tornado"
] |
Matplotlib interpolating / plotting unstructured data | 40,014,554 | <p>usually, Im working with image data which is in arrays the shape of m x n. Displaying is easy, right?</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
#sample data
m,n = 10,20
sample = np.random.random((m,n))
plt.imshow(sample)
</code></pre>
<p>from a different algorith, Im now getting data which has x,y,data from a different shape as m,n but in the same range. Let me generate some sample to better explain.</p>
<pre><code>k = 300
x = np.random.random((k,)) * m
y = np.random.random((k,)) * n
data = np.random.random((k,))
</code></pre>
<p>I want to do two things im not getting my head around. </p>
<p>1) Plotting the data in an imshow style</p>
<p>2) For better comparability, interpolate the data on a rectangular m,n grid, that is genrating an array of shape m,n with values from data (like "nearest"). </p>
<p>Im actuallte using scipy.ndimage.map_coordinates to do the thing the way around but cant get it working inversed...</p>
<p>Cheers</p>
| 0 | 2016-10-13T07:13:52Z | 40,017,056 | <p>Below is slightly changed example of <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.html#scipy.interpolate.griddata" rel="nofollow">scipy.interpolate.griddata</a> usage:</p>
<pre><code>import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
k = 300
m, n = 10, 20
x = np.random.random((k,)) * m
y = np.random.random((k,)) * n
data = np.random.random((k,))
grid_x, grid_y = np.mgrid[0:m+1, 0:n+1]
grid_z0 = griddata((x, y), data, (grid_x, grid_y), method='nearest')
grid_z1 = griddata((x, y), data, (grid_x, grid_y), method='linear')
grid_z2 = griddata((x, y), data, (grid_x, grid_y), method='cubic')
plt.subplot(131)
plt.imshow(grid_z0.T)
plt.title('Nearest')
plt.subplot(132)
plt.imshow(grid_z1.T)
plt.title('Linear')
plt.subplot(133)
plt.imshow(grid_z2.T)
plt.title('Cubic')
plt.gcf().set_size_inches(6, 6)
plt.show()
</code></pre>
| 0 | 2016-10-13T09:22:51Z | [
"python",
"matplotlib"
] |
Compile python virtual environment | 40,014,823 | <p>I created a Python script for a Freelance job and I can't find how to compile/build/package it for easy sharing. The person for which I created it is not a technical one, so I can't explain him how to activate a virtualenv, install requirements and so on.</p>
<p>What is the easiest way for him to run the project right after downloading it?</p>
<p>Can the whole virtualenv be compiled into an <code>.exe</code>? If yes, can this be done inside a macOS system?</p>
| 0 | 2016-10-13T07:28:45Z | 40,014,914 | <p>Yes you can package your python programs and it's dependencies with</p>
<p><a href="https://cx-freeze.readthedocs.io/en/latest/" rel="nofollow">Cx_Freeze</a></p>
<p>There are other python modules that do the same, personally i prefer <code>cx_Freeze</code> because it's cross platform and was the only one that worked out of the box for me.</p>
<p>By default <code>cx_Freeze</code> automatically discovers modules and adds them to the exe to be generated. but sometimes this doesn't work and you might have to add them by yourself</p>
<p>To create a simple executable from a file. you can just use the bundled <code>cxfreeze</code> script</p>
<pre><code>cxfreeze hello.py --target-dir dist
</code></pre>
<p>but more for more complex applications that have different files you'll have to create a distutils setup script.</p>
<p>Note that <code>cx_freeze</code> doesn't compile your code like a traditional compiler. it simply zips your python files and all it's dependencies ( as byte code) together, and includes the python interpreter to make your program run. So your code can be disassembled. (if anyone wants to) and you'll also notice that the size of your program would be larger than it was initially (Because of the extra files included)</p>
| 0 | 2016-10-13T07:34:01Z | [
"python",
"virtualenv"
] |
How to redirect Python print commands to putty SSH console? | 40,014,826 | <p>after many unsuccessful researches I've decided to ask my question here so maybe someone will provide me an answer or a lead for a problem I got.</p>
<p>I have a Python script that runs as a background process on an embedded device (the OS is a Linux distro). This script do important measurements and because of that, it can not be terminated or restarted.</p>
<p>I was wondering if it was possible to implement a chunk of code that will redirect the print() outputs to a Putty SSH console when we send it a command via a messaging protocol (MQTT).</p>
<p>So the situation will be like this:</p>
<ul>
<li>Device receive a command, set a variable to 1</li>
<li>Print() outputs will now be visible on the current root session opened by Putty SSH client.</li>
</ul>
<p>I don't know if it is possible but I'm opened to suggestions.</p>
<p>Thank you in advance for your answers, and sorry for my bad english.</p>
| 0 | 2016-10-13T07:28:58Z | 40,018,845 | <p>As suggested by GhostCat, I've decided to go for a logging solution so anyone who can connect to the device by SSH can just "tail -F" the log file and see the debug messages.</p>
<p>I've removed all the print() statements in the code and replaced them by logging calls (which is, indeed, a more professional approach)</p>
<p>If someone had the same question as I, you can read this : <a href="http://www.blog.pythonlibrary.org/2014/02/11/python-how-to-create-rotating-logs/" rel="nofollow">http://www.blog.pythonlibrary.org/2014/02/11/python-how-to-create-rotating-logs/</a></p>
<p>or this : <a href="https://docs.python.org/2/howto/logging.html#logging-basic-tutorial" rel="nofollow">https://docs.python.org/2/howto/logging.html#logging-basic-tutorial</a></p>
<p>to help you solve your issue.</p>
<p>Thanks again to GhostCat and Tripleee for their help.</p>
| 0 | 2016-10-13T10:46:27Z | [
"python",
"linux",
"ssh",
"putty"
] |
python-accessing the next object in database while in for loop | 40,014,953 | <p>This is my view code. I iterate over all the entries in DB and when rollno matches, I want to store the student name for previous,current and next student in one go. Is there any way to implement it?</p>
<pre><code>if request.method == 'POST':
rollno = request.POST.get('roll',None)
studentlist = Students.objects.all()
for st in studentlist:
if st.roll_no == rollno:
three_students=[*prev_student,current_student,next_student*]
</code></pre>
| 0 | 2016-10-13T07:35:26Z | 40,015,051 | <p>Assuming <code>roll_no</code> is incremental then you can just use <code>__in</code></p>
<pre><code>Student.objects.filter(roll_no__in=[roll_no - 1, roll_no, roll_no + 1])
</code></pre>
<p>If you can't guarrantee they're always incremental then you may need a separate query first to get the roll_no's you're trying to find first.</p>
<p>For example (without error/out of bounds handling),</p>
<pre><code>rolls = Student.objects.order_by('roll_no').values_list('roll_no', flat=True)
idx = rolls.index(rollno)
rolls_to_filter_on = rolls[idx-1:3]
</code></pre>
| 0 | 2016-10-13T07:41:02Z | [
"python",
"django"
] |
python-accessing the next object in database while in for loop | 40,014,953 | <p>This is my view code. I iterate over all the entries in DB and when rollno matches, I want to store the student name for previous,current and next student in one go. Is there any way to implement it?</p>
<pre><code>if request.method == 'POST':
rollno = request.POST.get('roll',None)
studentlist = Students.objects.all()
for st in studentlist:
if st.roll_no == rollno:
three_students=[*prev_student,current_student,next_student*]
</code></pre>
| 0 | 2016-10-13T07:35:26Z | 40,015,676 | <p>If I understood you correctly this is what you want</p>
<pre><code># create generator that will provide you with 3 neighobring students at the same time
def student_gen():
triple = []
for s in Students.objects.all():
if len(triple) == 3:
triple.pop(0)
triple.append(s)
yield triple
else:
triple.append(s)
# and inside your view
...
if request.method == 'POST':
rollno = request.POST.get('roll',None)
for three_students in student_gen():
if three_students[1].roll_no == rollno:
break
print(three_students)
</code></pre>
| 0 | 2016-10-13T08:15:31Z | [
"python",
"django"
] |
Converting daily data to weekly means and medians | 40,014,986 | <p>I have a list of dicts like this:</p>
<pre><code>[
{'2016-06-11': 10,
'2016-06-09': 10,
'ID': 1,
'2016-06-04': 10,
'2016-06-07': 10,
'2016-06-06': 10,
'2016-06-01': 10,
'2016-06-03': 10,
'type': 'primary',
'2016-06-05': 10,
'2016-06-10': 10,
'2016-06-02': 10,
'2016-06-08': 10},
{'2016-06-11': 2,
'2016-06-09': 1,
'ID': 2,
'type': 'secondary',
'2016-06-04': 1,
'2016-06-07': 1,
'2016-06-06': 1,
'2016-06-01': 1,
'2016-06-03': 1,
'2016-06-05': 1,
'2016-06-10': 2,
'2016-06-02': 1,
'2016-06-08': 1}
]
</code></pre>
<p>I need to convert this to a similar list of dicts, where the keys would be weeks (starting on Mondays, so eg <code>2016-06-03 - 2016-06-09</code>) or months (so eg <code>2016-06</code>), and the values would be either the mean or median of that week/month's values. What would be the simplest way to do this?</p>
| 2 | 2016-10-13T07:37:10Z | 40,015,340 | <p>I think you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a> by <code>months</code>, aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.resample.Resampler.mean.html" rel="nofollow"><code>mean</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.resample.Resampler.median.html" rel="nofollow"><code>median</code></a> and last create <code>list</code> of <code>dict</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html" rel="nofollow"><code>DataFrame.to_dict</code></a>:</p>
<pre><code>df = pd.DataFrame(d)
print (df)
2016-06-01 2016-06-02 2016-06-03 2016-06-04 2016-06-05 2016-06-06 \
0 10 10 10 10 10 10
1 1 1 1 1 1 1
2016-06-07 2016-06-08 2016-06-09 2016-06-10 2016-06-11 ID type
0 10 10 10 10 10 1 primary
1 1 1 1 2 2 2 secondary
df.set_index(['type', 'ID'], inplace=True)
df.columns = pd.to_datetime(df.columns)
df = df.T.resample('M').mean()
df.index = df.index.strftime('%Y-%m')
print (df)
type primary secondary
ID 1 2
2016-06 10.0 1.181818
print (df.T.reset_index().to_dict(orient='records'))
[{'type': 'primary', '2016-06': 10.0, 'ID': 1},
{'type': 'secondary', '2016-06': 1.1818181818181819, 'ID': 2}]
</code></pre>
<hr>
<pre><code>df.set_index(['type', 'ID'], inplace=True)
df.columns = pd.to_datetime(df.columns)
df = df.T.resample('M').median()
df.index = df.index.strftime('%Y-%m')
print (df)
type primary secondary
ID 1 2
2016-06 10 1
print (df.T.reset_index().to_dict(orient='records'))
[{'type': 'primary', '2016-06': 10, 'ID': 1},
{'type': 'secondary', '2016-06': 1, 'ID': 2}]
</code></pre>
<p>Another solution instead <code>reample</code> is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by month period created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.to_period.html" rel="nofollow"><code>DatetimeIndex.to_period</code></a>:</p>
<pre><code>df = df.groupby([df.index.to_period('m')]).mean()
df = df.groupby([df.index.to_period('m')]).median()
</code></pre>
| 1 | 2016-10-13T07:57:20Z | [
"python",
"date",
"pandas",
"mean",
"median"
] |
Python Xlrd and Xlwt | 40,014,989 | <p>I have the following content in an old Excel sheet:</p>
<p><a href="https://i.stack.imgur.com/64eFb.png" rel="nofollow"><img src="https://i.stack.imgur.com/64eFb.png" alt="excel sheet screenshot"></a></p>
<p>I need to generate a new Excel sheet with the following values:</p>
<p><a href="https://i.stack.imgur.com/17UIw.png" rel="nofollow"><img src="https://i.stack.imgur.com/17UIw.png" alt="excel sheet updated"></a></p>
<p>In the input Excel file's 3rd column I have a range <code>10010-10040</code> and an increment value of <code>10</code>. This needs to be expanded in my new Excel file.</p>
<p>If I give a comma (,) in between values, it should be treated as separate values and expanded. (Like in row2, column 3)</p>
<p>I have no idea how to do this and I am new to Python.</p>
| 0 | 2016-10-13T07:37:20Z | 40,022,335 | <p>Try the following. This uses the <code>xlrd</code> and <code>xlwt</code> libraries to read and write <code>xls</code> spreadsheets:</p>
<pre><code>import xlrd
import xlwt
wb_in = xlrd.open_workbook(r'input.xls')
sheet_name = wb_in.sheet_names()[0]
ws_in = wb_in.sheet_by_name(sheet_name)
wb_out = xlwt.Workbook()
ws_out = wb_out.add_sheet(sheet_name) # Use the same sheet name
row_out = 0
for row_in in range(ws_in.nrows):
row = ws_in.row_values(row_in)
if isinstance(row[2], float):
req_spec = str(int(row[2]))
else:
req_spec = row[2]
req_range = req_spec.split('-')
req_enum = req_spec.split(',')
if len(req_range) > 1: # e.g. 10010-10040-10
for value in range(int(str(req_range[0])), int(str(req_range[1])) + 1, int(str(req_range[2]))):
ws_out.write(row_out, 0, row[0])
ws_out.write(row_out, 1, row[1])
ws_out.write(row_out, 2, str(value))
row_out += 1
elif len(req_enum) > 1: # e.g. 1010,1020
for value in req_enum:
ws_out.write(row_out, 0, row[0])
ws_out.write(row_out, 1, row[1])
ws_out.write(row_out, 2, value)
row_out += 1
else: # e.g. 10100
ws_out.write(row_out, 0, row[0])
ws_out.write(row_out, 1, row[1])
ws_out.write(row_out, 2, req_spec)
row_out += 1
wb_out.save('output.xls')
</code></pre>
<p>Unfortunately, if you not familiar with Python there is quite a lot to take in. </p>
<p>The script works by creating an input workbook and an output workbook. For each row in the input, it assumes you will always have 3 columns and that the third one contains one of your three types of specifies. It decides which is in use based on whether or not there is a <code>-</code> or a <code>,</code> present. It then writes out rows to the output based on this range.</p>
<p>Note, when reading the file in, <code>xlrd</code> attempts to guess the format of the cell. For most of your entries, it guesses a string format, but sometimes it wrongly guesses a floating point number. The script tests for this and converts it to a string for consistency. Also <code>xlrd</code> uses unicode <code>u"xxx"</code> format to store the strings. These need to be converted to numbers to be able to calculate the required ranges.</p>
| 0 | 2016-10-13T13:26:25Z | [
"python",
"xlrd",
"xlwt"
] |
Selenium not working with python 2.7 | 40,015,019 | <p>I am trying to run a basic selenium code with python 2.7. I got the below exception. I have installed the latest selenium. </p>
<p>What should I do to fix it?</p>
<pre><code>C:\Python27\python.exe D:/Python/Selenium/seleniumTest.py
Traceback (most recent call last):
File "D:/Python/Selenium/seleniumTest.py",
line 4, in <module> driver = webdriver.Firefox()
File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\webdriver.py",
line 80, in __init__ self.binary, timeout)
File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\extension_connection.py",
line 52, in __init__ self.binary.launch_browser(self.profile, timeout=timeout)
File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py",
line 68, in launch_browser self._wait_until_connectable(timeout=timeout)
File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py",
line 108, in _wait_until_connectable % (self.profile.path))
selenium.common.exceptions.WebDriverException: Message:
Can't load the profile. Profile Dir: c:\users\venkat~1.ps\appdata\local\temp\tmpiht1hq
If you specified a log_file in the FirefoxBinary constructor, check it for details.
</code></pre>
| 0 | 2016-10-13T07:39:15Z | 40,015,712 | <p>If by latest version you mean the 2.53 you get with <code>pip install selenium</code>, it's a known problem (<a href="https://github.com/SeleniumHQ/selenium/issues/2739" rel="nofollow">https://github.com/SeleniumHQ/selenium/issues/2739</a>), this version does not support the last versions of firefox, and it won't be fixed because the dev team focus on the version 3.0 (which works fine).</p>
<p>So you can either :</p>
<ul>
<li>use another browser</li>
<li>use an old version of firefox (<=46)</li>
<li>use the new version of selenium with <code>pip install selenium==3.0.0b3</code>. It should become the default version soon.</li>
</ul>
| 1 | 2016-10-13T08:16:56Z | [
"python",
"python-2.7",
"selenium",
"firefox"
] |
How to print predefined sequence in python | 40,015,183 | <p>I am trying to print predefined sequence from pdb input file in python but I am not getting expected result. I am new in python, and I have also import directory but its not working. not showing anything (unable to find error). Its just running without any output. </p>
<pre><code>import os
os.chdir('C:\Users\Vishnu\Desktop\Test_folder\Input')
for path, dirs, pdbfile in os.walk('/C:\Users\Vishnu\Desktop\Test_folder\Input'):
for line in pdbfile:
if line[:6] != "HETATM":
continue
chainID = line[21:22]
atomID = line[13:16].strip()
if chainID not in ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'):
continue
if atomID not in ('C4B', 'O4B', 'C1B', 'C2B', 'C3B'):
continue
with open('C:\Users\Vishnu\Desktop\Test_folder\Input', 'r') as fh:
new = [line.rstrip() for line in fh]
with open('C:\Users\Vishnu\Desktop\Test_folder\Output', 'w') as fh:
[fh.write('%s\n' % line) for line in new]
fh.write((line.rstrip()))
</code></pre>
<p>Expected output:</p>
<pre><code>HETATM 3788 C4B NAI A 302 52.695 15.486 8.535 1.00 57.28 C
HETATM 3789 O4B NAI A 302 52.258 14.631 7.456 1.00 56.26 O
HETATM 3794 C1B NAI A 302 53.348 13.816 7.022 1.00 53.44 C
HETATM 3792 C2B NAI A 302 54.537 14.748 7.190 1.00 50.93 C
HETATM 3789 O4B NAI A 302 52.258 14.631 7.456 1.00 56.26 O
HETATM 3794 C1B NAI A 302 53.348 13.816 7.022 1.00 53.44 C
HETATM 3792 C2B NAI A 302 54.537 14.748 7.190 1.00 50.93 C
HETATM 3790 C3B NAI A 302 54.225 15.525 8.465 1.00 52.99 C
HETATM 3794 C1B NAI A 302 53.348 13.816 7.022 1.00 53.44 C
HETATM 3792 C2B NAI A 302 54.537 14.748 7.190 1.00 50.93 C
HETATM 3790 C3B NAI A 302 54.225 15.525 8.465 1.00 52.99 C
HETATM 3788 C4B NAI A 302 52.695 15.486 8.535 1.00 57.28 C
HETATM 3792 C2B NAI A 302 54.537 14.748 7.190 1.00 50.93 C
HETATM 3790 C3B NAI A 302 54.225 15.525 8.465 1.00 52.99 C
HETATM 3788 C4B NAI A 302 52.695 15.486 8.535 1.00 57.28 C
HETATM 3789 O4B NAI A 302 52.258 14.631 7.456 1.00 56.26 O
HETATM 3790 C3B NAI A 302 54.225 15.525 8.465 1.00 52.99 C
HETATM 3788 C4B NAI A 302 52.695 15.486 8.535 1.00 57.28 C
HETATM 3789 O4B NAI A 302 52.258 14.631 7.456 1.00 56.26 O
HETATM 3794 C1B NAI A 302 53.348 13.816 7.022 1.00 53.44 C
</code></pre>
<p>same format for B chain also.</p>
<p>How to print predefined sequence? line [21:22] is there chain ID, chain ID may be A to H. How to define A to H chain ID? </p>
<p>I am unable to print in sequence, can any one let me know how to print predefined sequence in python?</p>
<p><strong>After Answer:</strong></p>
<p>I have updated above code with below code: </p>
<pre><code>n = 4
for chain, atoms in d.items():
for atom, line in atoms.items():
for i in range(len(atom)-n+1):
for j in range(n):
print d[chain][atomIDs[i+j]]
print
</code></pre>
<p>I want to extend two more paragraph but not getting expected output</p>
| 0 | 2016-10-13T07:48:12Z | 40,015,411 | <p>Here are my comments all combined into an answer:</p>
<pre><code>with open('1AHI.pdb') as pdbfile:
for line in pdbfile:
if line[:6] != "HETATM":
continue
chainID = line[21:22]
atomID = line[13:16].strip()
if chainID not in ('A', 'B'):
continue
if atomID not in ('C4B', 'O4B', 'C1B', 'C2B', 'C3B'):
continue
## Either:
print(line, end='')
## Or:
print(line.rstrip(), end='\n')
## Or if Python2.x:
print line.rstrip()
</code></pre>
<p>My first lines of code was written more than 10 years ago parsing PDB files. Don't despair. You have a long and beautiful journey ahead of you.</p>
<p>P.S. I think mmCIF is to prefer over PDB these days... Make sure you read the specifications for both file formats.</p>
<hr>
<p>I have updated the answer, but please be aware this site is for solving specific problems and not for other people to do the work for you. It is generally looked down on.</p>
<pre><code>d = {}
chainIDs = ('A', 'B',)
atomIDs = ('C4B', 'O4B', 'C1B', 'C2B', 'C3B', 'C4B')
with open('1AHI.pdb') as pdbfile:
for line in map(str.rstrip, pdbfile):
if line[:6] != "HETATM":
continue
chainID = line[21:22]
atomID = line[13:16].strip()
if chainID not in chainIDs:
continue
if atomID not in atomIDs:
continue
try:
d[chainID][atomID] = line
except KeyError:
d[chainID] = {atomID: line}
n = 4
for chainID in chainIDs:
for i in range(len(atomIDs)-n+1):
for j in range(n):
print d[chainID][atomIDs[i+j]]
print
</code></pre>
| 1 | 2016-10-13T08:00:45Z | [
"python",
"python-2.7",
"python-3.x",
"bioinformatics",
"biopython"
] |
load .mat file from python | 40,015,212 | <p>I am trying to run from Python a script in Matlab that run a Simulink mode, save a variable as Power.mat and read this variable in Python. I am using Python 2.7 on Windows.</p>
<p>I've tried to use the library hdf5storage to read the file:</p>
<pre><code>import hdf5storage
x=hdf5storage.loadmat('Power.mat','r')
</code></pre>
<p>but I get the error attached.
<img src="https://i.stack.imgur.com/hHI33.png" alt="error"></p>
<p>Which could be the problem?
I have also tried with the library h5py but I get the same error.
The file .mat seems not to be corrupted since I open it without any problem in Matlab.</p>
<p>Thanks!</p>
| 0 | 2016-10-13T07:49:46Z | 40,015,513 | <p>You can use scipy.io to exchange data between Python and Matlab. There are functions named savemat and loadmat for this purpose. </p>
<p>Something like this should work:</p>
<pre><code>import scipy.io
mat = scipy.io.loadmat('Power.mat')
</code></pre>
<p>For reference, <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html</a></p>
| 1 | 2016-10-13T08:06:16Z | [
"python",
"matlab",
"h5py",
"hdf5storage"
] |
load .mat file from python | 40,015,212 | <p>I am trying to run from Python a script in Matlab that run a Simulink mode, save a variable as Power.mat and read this variable in Python. I am using Python 2.7 on Windows.</p>
<p>I've tried to use the library hdf5storage to read the file:</p>
<pre><code>import hdf5storage
x=hdf5storage.loadmat('Power.mat','r')
</code></pre>
<p>but I get the error attached.
<img src="https://i.stack.imgur.com/hHI33.png" alt="error"></p>
<p>Which could be the problem?
I have also tried with the library h5py but I get the same error.
The file .mat seems not to be corrupted since I open it without any problem in Matlab.</p>
<p>Thanks!</p>
| 0 | 2016-10-13T07:49:46Z | 40,015,516 | <p>Try this code :</p>
<pre><code>import h5py
Data = h5py.File('File.mat')
</code></pre>
| 0 | 2016-10-13T08:06:25Z | [
"python",
"matlab",
"h5py",
"hdf5storage"
] |
Whey is_leap_year returning None instead of True | 40,015,236 | <p>Why does this code print None instead of True. It seems that once it checks if it divisible by 4 it does not go on to check the other requirements. From my current understanding, for each successive if statement it should keep going down and checking the next if until one of them is false. At which point it should go the the else statement and return False. But, obviously I'm doing something wrong. Thank you.</p>
<pre><code>def is_leap_year(year):
# step 1 check if dvisible by 4
if year % 4 == 0:
print "year is divisble by 4"
# step 2 check if divisible by 100
if year % 100 == 0:
print "year is divisible by 100"
# step 3 check if divisble by 400
if year % 400 == 0:
print "year is divisible by 400"
return True
else:
return False
print is_leap_year(1996)
</code></pre>
| -1 | 2016-10-13T07:51:18Z | 40,015,272 | <blockquote>
<p>From my current understanding, for each successive if statement it
should keep going down and checking the next if until one of them is
false. At which point it should go the the else statement and return
False</p>
</blockquote>
<p>No that isn't completely true. That <code>else</code> block is only executed when the first <code>if</code> block is not i.e when the year is not divisible by 4. When the other <code>if</code> blocks are not (e.g for a year divisible by 4 and not by 100), the function will rightly <em>return</em> <code>None</code>.</p>
<p>Instead, you can <code>return False</code> in the case everything other <code>if</code> fails:</p>
<pre><code>def is_leap_year(year):
# step 1 check if dvisible by 4
if year % 4 == 0:
print "year is divisble by 4"
# step 2 check if divisible by 100
if year % 100 == 0:
print "year is divisible by 100"
# step 3 check if divisble by 400
if year % 400 == 0:
print "year is divisible by 400"
return True
return False
</code></pre>
<p>That said, I'm not sure about the correctness of your approach. Here is an SO post that can help you improve your code:</p>
<p><a href="http://stackoverflow.com/questions/11621740/how-to-determine-whether-a-year-is-a-leap-year-in-python">How to determine whether a year is a leap year in Python?</a></p>
<hr>
<p>Otherwise, you may find out if a year is leap using <a href="https://docs.python.org/2/library/calendar.html#calendar.isleap" rel="nofollow"><code>calendar.isleap</code></a>:</p>
<pre><code>import calendar
print(calendar.isleap(2000))
</code></pre>
| 1 | 2016-10-13T07:53:41Z | [
"python"
] |
Whey is_leap_year returning None instead of True | 40,015,236 | <p>Why does this code print None instead of True. It seems that once it checks if it divisible by 4 it does not go on to check the other requirements. From my current understanding, for each successive if statement it should keep going down and checking the next if until one of them is false. At which point it should go the the else statement and return False. But, obviously I'm doing something wrong. Thank you.</p>
<pre><code>def is_leap_year(year):
# step 1 check if dvisible by 4
if year % 4 == 0:
print "year is divisble by 4"
# step 2 check if divisible by 100
if year % 100 == 0:
print "year is divisible by 100"
# step 3 check if divisble by 400
if year % 400 == 0:
print "year is divisible by 400"
return True
else:
return False
print is_leap_year(1996)
</code></pre>
| -1 | 2016-10-13T07:51:18Z | 40,015,279 | <p>Your function will only return <code>True</code> if the year is divisible by <code>4</code>, <code>100</code> <em>and</em> <code>400</code> and it will return <code>False</code> if the year is not divisible by <code>4</code>.</p>
<p>There are a number of cases where you haven't specified the return value (e.g. divisible by <code>4</code> but <em>not</em> divisible by <code>100</code>). In those cases, your function will return <code>None</code>. <code>1996</code> falls into those cases.</p>
| 1 | 2016-10-13T07:53:58Z | [
"python"
] |
Whey is_leap_year returning None instead of True | 40,015,236 | <p>Why does this code print None instead of True. It seems that once it checks if it divisible by 4 it does not go on to check the other requirements. From my current understanding, for each successive if statement it should keep going down and checking the next if until one of them is false. At which point it should go the the else statement and return False. But, obviously I'm doing something wrong. Thank you.</p>
<pre><code>def is_leap_year(year):
# step 1 check if dvisible by 4
if year % 4 == 0:
print "year is divisble by 4"
# step 2 check if divisible by 100
if year % 100 == 0:
print "year is divisible by 100"
# step 3 check if divisble by 400
if year % 400 == 0:
print "year is divisible by 400"
return True
else:
return False
print is_leap_year(1996)
</code></pre>
| -1 | 2016-10-13T07:51:18Z | 40,015,296 | <p>The <code>else</code> refers only to the first <code>if</code> - i.e. for years not divisible by four. Therefore for a year divisible by four, but not by 100 you do not fall into the <code>else</code>. Python functions return <code>None</code> if no return value is specified.</p>
<p>In general <code>else</code> refers to the last <code>if</code> with the same indentation.</p>
<p>You can fix it by doing:</p>
<pre><code>def is_leap_year(year):
# step 1 check if dvisible by 4
if year % 4 == 0:
print "year is divisble by 4"
# step 2 check if divisible by 100
if year % 100 == 0:
print "year is divisible by 100"
# step 3 check if divisble by 400
if year % 400 == 0:
print "year is divisible by 400"
return True
else:
return True
return False
</code></pre>
| 2 | 2016-10-13T07:54:55Z | [
"python"
] |
Whey is_leap_year returning None instead of True | 40,015,236 | <p>Why does this code print None instead of True. It seems that once it checks if it divisible by 4 it does not go on to check the other requirements. From my current understanding, for each successive if statement it should keep going down and checking the next if until one of them is false. At which point it should go the the else statement and return False. But, obviously I'm doing something wrong. Thank you.</p>
<pre><code>def is_leap_year(year):
# step 1 check if dvisible by 4
if year % 4 == 0:
print "year is divisble by 4"
# step 2 check if divisible by 100
if year % 100 == 0:
print "year is divisible by 100"
# step 3 check if divisble by 400
if year % 400 == 0:
print "year is divisible by 400"
return True
else:
return False
print is_leap_year(1996)
</code></pre>
| -1 | 2016-10-13T07:51:18Z | 40,015,822 | <p>You can use this approach:</p>
<pre><code>def is_leap_year(year):
leap = False
# step 1 check if dvisible by 4
if year % 4 == 0:
print "year is divisble by 4"
leap = True
# step 2 check if divisible by 100
if year % 100 == 0:
print "year is divisible by 100"
leap = False
# step 3 check if divisble by 400
if year % 400 == 0:
print "year is divisible by 400"
leap = True
return leap
print is_leap_year(1996)
</code></pre>
<p>Explanation: year is leap if it is dividable by 4, and not leap if is dividable by 100 (unless it is also dividable by 400).</p>
| 0 | 2016-10-13T08:22:58Z | [
"python"
] |
Apache - Prefork and Worker | 40,015,289 | <p>I am trying to build a Python Web Application using Django. On it's official "<a href="https://docs.djangoproject.com/en/1.10/topics/install/" rel="nofollow">how-to-install</a>" page, it says Apache and mod_wsgi must be installed. </p>
<p>I have manually installed, in my Ubuntu machine, Apache 2.2.31 HTTP Server at the location </p>
<blockquote>
<p><code>/usr/local/apache</code></p>
</blockquote>
<p>I am looking up for the instructions for installing mod_wsgi from <a href="https://pypi.python.org/pypi/mod_wsgi" rel="nofollow">https://pypi.python.org/pypi/mod_wsgi</a></p>
<p>On this site, it says for "system requirement" that the apache prefork or worker mpm along with its respective developer variant needs to be installed. </p>
<p>After executing the following command, </p>
<blockquote>
<p><code>/usr/local/apache/bin/apachectl -V</code></p>
</blockquote>
<p>I am getting many outputs, one of which says that the MPM Server is "Prefork".</p>
<p>So, my conclusion is that MPM Servers are prepackaged with Apache. </p>
<p>Now, my questions are</p>
<p>1) How to change the MPM Server from "Prefork" to "Worker"?</p>
<p>2) Since I have manually installed Apache, how to install the developer variant of the MPM Server? If it is already installed, how to verify it? </p>
| 0 | 2016-10-13T07:54:32Z | 40,015,453 | <p>You are worrying about two things that you absolutely do not need to worry about.</p>
<p>Firstly, on that Django page, it explicitly states that to begin development you do not need to install any server. It suggests that you will need mod_wsgi when you come to deploy to your production server, although goes on to state that other deployment options are available such as uwsgi (personally I prefer gunicorn, but never mind). To be honest that page could do with a bit of rewording to make this clearer, though.</p>
<p>Secondly, that mod_wsgi page talks about compiling it from scratch. Even when you do come to deploy, there is almost never any need to do that. Since you are using Ubuntu, you can install it with aptitude:</p>
<pre><code>sudo apt-get install libapache2-mod-wsgi
</code></pre>
| 0 | 2016-10-13T08:02:42Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
Why does map return a map object instead of a list in Python 3? | 40,015,439 | <p>I am interested in understanding the <a href="http://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x">new language design of Python 3.x</a>.</p>
<p>I do enjoy, in Python 2.7, the function <code>map</code>:</p>
<pre><code>Python 2.7.12
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: [2, 3, 4]
</code></pre>
<p>However, in Python 3.x things have changed:</p>
<pre><code>Python 3.5.1
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: <map at 0x4218390>
</code></pre>
<p>I understand the how, but I could not find a reference to the why. Why did the language designers make this choice, which, in my opinion, introduces a great deal of pain. Was this to arm-wrestle developers in sticking to list comprehensions?</p>
<p>IMO, list can be naturally thought as <a href="http://learnyouahaskell.com/functors-applicative-functors-and-monoids" rel="nofollow">Functors</a>; and I have been somehow been thought to think in this way:</p>
<pre><code>fmap :: (a -> b) -> f a -> f b
</code></pre>
| 20 | 2016-10-13T08:01:41Z | 40,015,480 | <p>Because it returns an iterator, it omit storing the full list in the memory. So that you can easily iterate over it in the future not making pain to memory. Possibly you even don't need a full list, but the part of it, until your condition is matched.</p>
<p>You can find this <a href="https://docs.python.org/3/glossary.html#term-iterator">docs</a> useful, because iterators are awesome.</p>
<blockquote>
<p>An object representing a stream of data. Repeated calls to the iteratorâs <code>__next__()</code> method (or passing it to the built-in function <code>next()</code>) return successive items in the stream. When no more data are available a <code>StopIteration</code> exception is raised instead. At this point, the iterator object is exhausted and any further calls to its <code>__next__()</code> method just raise <code>StopIteration</code> again. Iterators are required to have an <code>__iter__()</code> method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a <code>list</code>) produces a fresh new iterator each time you pass it to the <code>iter()</code> function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container. </p>
</blockquote>
| 7 | 2016-10-13T08:04:08Z | [
"python",
"python-3.x"
] |
Why does map return a map object instead of a list in Python 3? | 40,015,439 | <p>I am interested in understanding the <a href="http://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x">new language design of Python 3.x</a>.</p>
<p>I do enjoy, in Python 2.7, the function <code>map</code>:</p>
<pre><code>Python 2.7.12
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: [2, 3, 4]
</code></pre>
<p>However, in Python 3.x things have changed:</p>
<pre><code>Python 3.5.1
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: <map at 0x4218390>
</code></pre>
<p>I understand the how, but I could not find a reference to the why. Why did the language designers make this choice, which, in my opinion, introduces a great deal of pain. Was this to arm-wrestle developers in sticking to list comprehensions?</p>
<p>IMO, list can be naturally thought as <a href="http://learnyouahaskell.com/functors-applicative-functors-and-monoids" rel="nofollow">Functors</a>; and I have been somehow been thought to think in this way:</p>
<pre><code>fmap :: (a -> b) -> f a -> f b
</code></pre>
| 20 | 2016-10-13T08:01:41Z | 40,015,658 | <p>In Python 3, many functions (not just <code>map</code> but <code>zip</code>, <code>range</code> and others) return an iterator rather than the full list. This puts an emphasis on a <em>lazy</em> approach, where each item is generated sequentially on the fly until the iterator is exhausted, so that an entire list does not need to be held in memory unnecessarily. Iterators are not always suitable, for example if you need to access the entire list at once or particular list indexes.</p>
<p>In your example, if you had a much more intensive calculation like <code>map(lambda x: x+1, range(large_number))</code> (the equivalent would be <code>xrange</code> in Python 2) then it would make little sense to generate a list immediately rather than process each item of the iterator one by one. However, in this case, and many others, a generator expression would suffice and be arguable more readable, like <code>(x+1 for x in range(large_number))</code>.</p>
<p>Note that for <code>map()</code>/<code>list(map)</code> in Python 3 is not quite equivalent to <code>iter(map())</code>/<code>map()</code> in Python 2 as explained in answers to this <a href="http://stackoverflow.com/questions/12015521/python-3-vs-python-2-map-behavior">question</a>.</p>
| 4 | 2016-10-13T08:14:25Z | [
"python",
"python-3.x"
] |
Why does map return a map object instead of a list in Python 3? | 40,015,439 | <p>I am interested in understanding the <a href="http://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x">new language design of Python 3.x</a>.</p>
<p>I do enjoy, in Python 2.7, the function <code>map</code>:</p>
<pre><code>Python 2.7.12
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: [2, 3, 4]
</code></pre>
<p>However, in Python 3.x things have changed:</p>
<pre><code>Python 3.5.1
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: <map at 0x4218390>
</code></pre>
<p>I understand the how, but I could not find a reference to the why. Why did the language designers make this choice, which, in my opinion, introduces a great deal of pain. Was this to arm-wrestle developers in sticking to list comprehensions?</p>
<p>IMO, list can be naturally thought as <a href="http://learnyouahaskell.com/functors-applicative-functors-and-monoids" rel="nofollow">Functors</a>; and I have been somehow been thought to think in this way:</p>
<pre><code>fmap :: (a -> b) -> f a -> f b
</code></pre>
| 20 | 2016-10-13T08:01:41Z | 40,015,733 | <p>I think the reason why map still exists <em>at all</em> when generator expressions also exist, is that it can take multiple iterator arguments that are all looped over and passed into the function:</p>
<pre><code>>>> list(map(min, [1,2,3,4], [0,10,0,10]))
[0,2,0,4]
</code></pre>
<p>That's slightly easier than using zip:</p>
<pre><code>>>> list(min(x, y) for x, y in zip([1,2,3,4], [0,10,0,10]))
</code></pre>
<p>Otherwise, it simply doesn't add anything over generator expressions.</p>
| 5 | 2016-10-13T08:17:55Z | [
"python",
"python-3.x"
] |
Subsets and Splits