I need a loop to restart because I'm limited as to how many elements I can process before google blocks me using googletrans module.
I've worked out that I can get about fifty elements using a random time delay until Google blocks me but I need it to loop through about 850.
As far as I know there is no way to restart a loop so I tried a while loop but it doesn't seen to update the loop and finishes after the first block has been processed.
I am also randomly setting a second interval between between translations to keep the loop working. it goes from 0 to 50 and then stops the loops
my code
from googletrans import Translator
from random import randint
import datetime
should_restart = True
spanish_subs = get_subs(page)# list of over 850 sentances to be translated
counter_num = 1
translator = Translator()
start_block = 0
end_block = 50
while should_restart:
print('start_block ' + str(start_block))# see where the loop is in the process
print('end_block ' + str(end_block))
if end_block < len(get_subs(page)):
translations = translator.translate(spanish_subs[start_block:end_block], src='es')
for translation in translations:
english_subs.append(translation.text)
print('Loop ' + str(counter_num + 1 ))
time.sleep(random())# pauses between 1 and 10 seconds
if end_block >= len(get_subs(page)):
should_restart = False
with open('englist_translation.txt', 'w') as f:
for item in english_subs:
f.write("%s\n" % item)
print('Finished')
start_block = end_block + 50
end_block = end_block + 50 # date the end block
print(english_subs)# print to console to see what was translated
return english_subs
def random():
random_number = randint(0, 10)
return random_number
This setup will help you get past Googles limits, it is a slow process but it works on a list of 50,000 characters.
from random import randint
import time
from googletrans import Translator
def get_script_eng():
should_restart = True
spanish_subs = get_subs(page)
counter_num = 1
translator = Translator()
start_block = 0
end_block = 50
while end_block < len(get_subs(page)):
print('start_block ' + str(start_block))
print('end_block ' + str(end_block))
if should_restart == True:
translations = translator.translate(spanish_subs[start_block:end_block], src='es')
for translation in translations:
english_subs.append(translation.text)
time.sleep(random())
print('translation ' + str(counter_num + 1 ))
else:
should_restart = False
with open('spanish.txt', 'w') as f:
for item in english_subs:
f.write("%s\n" % item)
print('Finished')
start_block = start_block + 50
end_block = end_block + 50
print(english_subs)
return english_subs
And then to generate the random time delay
def random():
random_number = randint(0, 10)
return random_number
Related
This is a script that is a simple proof of work and it's in md5 algo. Is there any way I can use it to transfer it to sha256?
# proof-of-work.py
import md5
string = "1"
complete = False
n = 0
while complete == False:
curr_string = string + str(n)
curr_hash = md5.new(curr_string).hexdigest()
n = n + 1
# slows performance drastically
## print curr_hash
if curr_hash.startswith('000000'):
print curr_hash
print curr_string
complete = True
from hashlib import sha256
string = "1"
complete = False
n = 0
while complete == False:
curr_string = string + str(n)
curr_hash = sha256(curr_string.encode()).hexdigest()
n = n + 1
print(curr_hash + ' ' + curr_hash[:4])
This outputs hashes and first 4 bytes like this:
c19df416e581278d028f20527b96c018f313e983f0a9bda4914679bb482d14f6 c19d
b5662892a57d57b6d904fa6243fae838c28aaebc190fc885ee2e20de6fbcaddb b566
a9c0a662c81abe40bca7d250e93965285e0aea74f2f3edde704015c11e98cdeb a9c0
635f19669b8b48cd78f05bfe52ccf4bfbdb55e544486d71404f5fa786d93e5be 635f
and never ends. Add your logic to exit the loop.
I'm trying to code a small pomodoro-timer, it uses a while loop with an if-elif-else statement to check which timer to start.
As expected it starts with the first if-block and then modifies the variable, I would expect it to go the elif-block after that, however it seems to be stuck in the if-block. And doesn't reiterate the entire while loop code.
How to overcome this?
import os
import time
pomodoro = ['Pomodoro', 1500]
short_break = ['Short Break', 300]
long_break = ['Long Break', 1800]
pomodori_count = 0
def countdown(time_frame):
duration = time_frame[1]
while duration:
os.system('clear')
mins, secs = divmod(duration, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(f"{time_frame[0]} | {timer}")
time.sleep(1)
duration -= 1
while True:
last = ""
if last != "Pomodoro":
countdown(pomodoro)
last = "Pomodoro"
pomodori_count += 1
elif pomodori_count % 4 != 0:
countdown(short_break)
last = "Short Break"
else:
countdown(long_break)
last = "Long Break"
So what is wrong with this code is that you reset the last value in each repeat of the while loop, so it never persists its state for the next cycle.
You should declare the variable before the while loop to fix this issue
last = ""
while True:
if last != "Pomodoro":
countdown(pomodoro)
last = "Pomodoro"
pomodori_count += 1
elif pomodori_count % 4 != 0:
countdown(short_break)
last = "Short Break"
else:
countdown(long_break)
last = "Long Break"
I'm trying to do the polish notation challenge on kattis.com. Thing is, I feel I have done everything they asked for and I've tried fixing everything I could think of. I even looked up some other's solutions and while theirs are more clean I want to continue on mine as I am learning.
Why is it that for example this person's code works but not mine?
Here is my current code:
import sys
case = 1
valid_ints = set([str(i) for i in range(-10,11)])
def simplify(index, myLine, processed):
while index+1 > 0:
if (myLine[index] == "+" or myLine[index] == "-" or myLine[index] == "*") and index < len(myLine)-2:
if myLine[index+1] in valid_ints and myLine[index+2] in valid_ints:
try:
processed = myLine[index+3:] + processed
a = str(myLine[index+1] + myLine[index] + myLine[index+2])
processed.insert(0, str(eval(a)))
del myLine[index:]
except:
processed = [myLine[index], myLine[index+1], myLine[index+2]] + processed
del myLine[index:]
elif len(myLine) < 3:
processed = myLine + processed
del myLine[index]
index -= 1
processed = myLine + processed
return processed
for line in sys.stdin:
myLine = line.split()
processed = []
index = len(myLine)-1
savedprocessed = []
processed = simplify(index, myLine, processed)
while True:
if savedprocessed == processed:
break
else:
savedprocessed = []
savedprocessed += processed
processed = simplify(len(processed)-1, processed, [])
result = " ".join(savedprocessed)
print("Case " + str(case) + ": " + result)
case += 1
if case > 5:
break
You're bringing some other language style to Python, that's unnecessary because Python is more flexible.
I've simplified as much as I can here.
Split the input string on white spaces and iterate over the tokens.
For every operator in the expression, push a list onto the stack and append the operator and its operands to the list.
Now pop each list off the stack and process the list
def simplify(exp):
stack1 = []
ops = set('+*-')
for token in exp.split():
if token in ops:
stack1.append([])
stack1[-1].append(token)
stack2 = []
while stack1:
top = stack1.pop()
while len(top) < 3 and stack2:
top.append(stack2.pop())
if any(x.isalpha() for x in top):
simplified = ' '.join(top)
else:
top[0], top[1] = top[1], top[0]
simplified = str(eval(''.join(top)))
stack2.append(simplified)
return simplified
exp = '* - 6 + x -6 - - 9 6 * 0 c'
print(exp)
simplify(exp)
Output;
* - 6 + x -6 - - 9 6 * 0 c
* - 6 + x -6 - - 3 * 0 c
I have the following code which turns an outlet on/off every 3 seconds.
start_time = time.time()
counter = 0
agent = snmpy4.Agent("192.168.9.50")
while True:
if (counter % 2 == 0):
agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1",1)
else:
agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1", 0)
time.sleep(3- ((time.time()-start_time) % 3))
counter = counter + 1
Is there a way I can have the loop terminate at any given point if something is entered, (space) for example... while letting the code above run in the mean time
You can put the loop in a thread and use the main thread to wait on the keyboard. If its okay for "something to be entered" can be a line with line feed (e.g., type a command and enter), then this will do
import time
import threading
import sys
def agent_setter(event):
start_time = time.time()
counter = 0
#agent = snmpy4.Agent("192.168.9.50")
while True:
if (counter % 2 == 0):
print('agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1",1)')
else:
print('agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1", 0)')
if event.wait(3- ((time.time()-start_time) % 3)):
print('got keyboard')
event.clear()
counter = counter + 1
agent_event = threading.Event()
agent_thread = threading.Thread(target=agent_setter, args=(agent_event,))
agent_thread.start()
for line in sys.stdin:
agent_event.set()
I'm writing a photobooth program in Python on my Raspberry Pi 2 and it worked if I just want to take one picture or use auto focus once. I'm trying to write a function "scheduler" that waits 4 seconds then runs auto-focus, then waits 4 seconds to take picture 1, waits another 4 seconds for picture 2 and waits 4 seconds for picture 3 while updating a status bar in PyGTK. But when the "scheduler" function is called it goes through and starts all the while loops at the same time.
I tried putting the while loops in separate functions and running them as threads and using threadx.start(), threadx.join() commands under each thread call. I suspect the way gobject.timeout_add() function is preventing blocking, which I need to keep the GUI updated and the live preview running, but I also can't figure out how to get blocking when I need it. I also started scheduler as a thread and used time.sleep(1) in each of the while loops and it acts behaves how I want it to except the GUI disappears after the first image gets processed and I can't find any error message to explain it.
I've been working on this for weeks and would happily pay someone to help me get this finished via email. I live in a rural area and have had a very hard time finding someone locally to help. I can paypal... please contact me at derosia at the popular google email service. If you have a camera supported by gphoto2 and a usb tether that would be a bonus.
class Photobooth(gtk.Window):
def set_statusBar(self, status):
self.statusBar.label.set_text(str(status))
def focus_counter2(self, counter):
if counter > 3:
self.set_statusBar("Get into position!")
elif counter > 0:
self.set_statusBar("Focusing: " + str(counter-1))
else:
self.set_statusBar("Focusing: " + str(counter-1))
self.focus_function() #runs the function for auto focus
def countdown_function(self, counter, image_name):
if counter > 1:
self.set_statusBar(str(counter-1))
elif counter > 0:
self.set_statusBar("Keep Smiling!")
else:
self.photo_cb(image_name) #runs the function to take an image
def scheduler(self, widget, data = None):
global ftp_path
global image_names
global countdown_timer
image_names = []
counter = countdown_timer
while counter > 0:
gobject.timeout_add(counter * 1000, self.focus_counter2, countdown_timer-counter)
counter -= 1
counter = countdown_timer
while counter >= 0:
image_name = datetime.datetime.now().strftime("%Y_%m-%d_%H-%M-%S")
gobject.timeout_add(counter * 1000, self.countdown_function, countdown_timer-counter, image_name)
counter -= 1
image_names.append(image_name + ".jpg")
counter = countdown_timer
while counter >= 0:
image_name = datetime.datetime.now().strftime("%Y_%m-%d_%H-%M-%S")
gobject.timeout_add(counter * 1000, self.countdown_function, countdown_timer-counter, image_name)
counter -= 1
image_names.append(image_name + ".jpg")
counter = countdown_timer
while counter >= 0:
image_name = datetime.datetime.now().strftime("%Y_%m-%d_%H-%M-%S")
gobject.timeout_add(counter * 1000, self.countdown_function, countdown_timer-counter, image_name)
counter -= 1
image_names.append(image_name + ".jpg")
def __init__(self):
super(PictureBox, self).__init__()
startB_image = gtk.image_new_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_SMALL_TOOLBAR)
startB = gtk.Button()
startB.set_image(startB_image)
startB.set_tooltip_text("Start countdown")
startB.connect('clicked', self.scheduler, None)
Thanks to andlabs I solved this the way he suggested:
Call a function and have each function call the next one when they finished what they were doing. Then to make sure it looped through the proper number of times I just passed along a counter to each function that got iterated at the end of each loop, image_number. It seems to work.
class Photobooth(gtk.Window):
def set_statusBar(self, status):
self.statusBar.label.set_text(str(status))
def focus_counter1(self, widget, data=None):
global countdown_timer
counter = countdown_timer
while counter > 0:
gobject.timeout_add(counter * 1000, self.focus_counter2,
countdown_timer-counter)
counter -= 1
def focus_counter2(self, counter):
if counter > 3:
self.set_statusBar("Get into position!")
elif counter > 0:
self.set_statusBar("Focusing: " + str(counter))
else:
self.set_statusBar("Focusing: " + str(counter))
self.focus_function()
gobject.timeout_add(1000, self.countdown_clicked, 1)
def countdown_clicked(self, image_number):
global countdown_timer
counter = countdown_timer
while counter >= 0:
gobject.timeout_add(counter * 1000, self.countdown_function,
countdown_timer-counter, image_number)
counter -= 1
def countdown_function(self, counter, image_number):
global images_per_sequence
if counter > 1:
self.set_statusBar(str(counter-1))
elif counter > 0:
self.set_statusBar("Keep Smiling!")
else:
image_name = datetime.datetime.now()
self.photo_cb(image_name.strftime("%Y_%m-%d_%H-%M-%S"))
if image_number < images_per_sequence:
gobject.timeout_add(1000, self.countdown_clicked,
image_number + 1)
def __init__(self):
super(PictureBox, self).__init__()
startB_image = gtk.image_new_from_stock(gtk.STOCK_YES,
gtk.ICON_SIZE_SMALL_TOOLBAR)
startB = gtk.Button()
startB.set_image(startB_image)
startB.set_tooltip_text("Start countdown")
startB.connect('clicked', self.focus_counter1, None)