Python - Skipping websocket callback "queue" - python-3.x

I have the following:
def process(msg):
print(msg)
for i in range(10): # This is in place of the
print(i, end=' ') # actual task, which takes
time.sleep(1) # around 10 seconds to run
ws = websocket()
ws.start_socket_abc(callback=process)
The websocket pushes info every second and makes a call to process each time.
Say the websocket is returning "one" for this second, "two" for the next second, "three" for the second after, and so on. Running the above code, the ouput would be:
one
0 1 2 3 4 5 6 7 8 9 <- this line takes 10 seconds to finish
two
0 1 2 3 4 5 6 7 8 9 <- this line takes 10 seconds to finish
...
It's clear that process("two") gets queued somewhere and is waited to be called after process("one") finishes. By the time the program prints out two, the real-time message should be twelve.
What I'm trying to achieve is to completely skip the "queue". I want it to take the message, do the task, skip all the calls in between (this is important, I actually need to skip them), take the next real-time message and do the task. In short, I want it to print out whatever real-time message is at the moment process("one") finishes. i.e.
one
0 1 2 3 4 5 6 7 8 9 <- this line takes 10 seconds to finish
twelve
...
This is what I have in mind.
message = ''
def process(msg):
message = msg
ws = websocket()
ws.start_socket_abc(callback=process)
def task(msg=message):
print(msg)
for i in range(10): # This is in place of the
print(i, end=' ') # actual task, which takes
time.sleep(1) # around 10 seconds to run
start_thread(target=task)
This performs the task with the message variable, which changes in real-time with the messages received from the websocket so after task("one") finishes, message is at "twelve" and task("twelve") will be called, skipping all the messages in between.
I strongly doubt that this is the proper way of doing it. Someone please enlighten me, thanks in advance!

Related

Do you know how to convert from bases in python?

How do you convert base 12 to base 10 in Python 3 and the other way around too? (from 10 to 12)
I wrote this code to make a list of numbers in base 4, but the code never executes and eventually has a timeout error. Any ideas on how to fix it? It also identifies the mode and counts the frequency of the mode. The program should start at 1 and print the next 21 numbers in base 4 and then do the mode stuff.
while num > 0:
if start in yes:
list4.append(start)
start += 1
num -= 1
if start not in yes:
num += 1
new_4 = ''.join([str(n) for n in list4])
print(statistics.mode(new_4))
count_m = new_4.count(statistics.mode(new_4))
print(count_m)
Comment any other questions you may have!

My python virus generation code has an issue

I am trying to write a code that will count how many viruses there are after some time. Specifically, the original virus will begin to multiply after 120 sec, then every 60 sec, and it's 'offspring' follow the same pattern. With this, I am trying to find how many viruses there are after 879 seconds. The code below should execute every one second, and count how many times it executes until it reaches 879 seconds, but I keep getting an error. Can anyone help? Thanks
import time
maxtime = 10
Arr = []
def virus():
virus_count = 0
count_time = 0
time.sleep(1)
while True:
virus_count += 1
count_time +=1
if count_time > maxtime:
Arr.append(count)
print('There are', Arr, 'viruses')
while True:
virus()
virus()
You don't have to actually "wait" to simulate this (though I guess you could if you wanted to.
I'm going to keep track of the "age" of each virus in terms of generations. I'll reframe the task as to split viruses only if they are older than 1 generation.
generation_time = 60
max_ticks = 879
geration_count = max_ticks // generation_time
# start with a single baby virus
virus_ages = [0]
for _ in range(geration_count):
## Age each virus by a generation
virus_ages = [v+1 for v in virus_ages]
## viruses older than one spawn a new virus
virus_ages.extend([0 for v in virus_ages if v != 1])
print(len(virus_ages))
This gives me 610 which I hope if the answer you are looking for.

Game of life is running slow

I am trying to simulate n-dimensional game of life for first t=6 time steps. My Nim code is a straightforward port from Python and it works correctly but instead of the expected speedup, for n=4, t=6 it takes 2 seconds to run, which is order of magnitude slower than my CPython version. Why is my code so slow? What can I do to speed it up? I am compiling with -d:release and --opt:speed
I represent each point in space with a single 64bit integer.
That is, I map (x_0, x_1, ..., x_{n-1}) to sum x_i * 32^i. I can do that since I know that after 6 time steps each coordinate -15<=x_i<=15 so I have no overflow.
The rules are:
alive - has 2 or 3 alive neigbours: stays alive
- different number of them: becomes alive
dead - has 3 alive neighbours: becomes alive
- else: stays dead
Below is my code. The critical part is the proc nxt which gets set of active cells and outputs set of active cells next time step. This proc is called 6 times. The only thing I'm interested in is the number of alive cells.
I run the code on the following input:
.##...#.
.#.###..
..##.#.#
##...#.#
#..#...#
#..###..
.##.####
..#####.
Code:
import sets, tables, intsets, times, os, math
const DIM = 4
const ROUNDS = 6
const REG_SIZE = 5
const MAX_VAL = 2^(REG_SIZE-1)
var grid = initIntSet()
# Inits neighbours
var neigbours: seq[int]
proc initNeigbours(base,depth: int) =
if depth == 0:
if base != 0:
neigbours.add(base)
else:
initNeigbours(base*2*MAX_VAL-1, depth-1)
initNeigbours(base*2*MAX_VAL+0, depth-1)
initNeigbours(base*2*MAX_VAL+1, depth-1)
initNeigbours(0,DIM)
echo neigbours
# Calculates next iteration:
proc nxt(grid: IntSet): IntSet =
var counting: CountTable[int]
for x in grid:
for dx in neigbours:
counting.inc(x+dx)
for x, count in counting.pairs:
if count == 3 or (count == 2 and x in grid):
result.incl(x)
# Loads input
var row = 0
while true:
var line = stdin.readLine
if line == "":
break
for col in 0..<line.len:
if line[col] == '#':
grid.incl((row-MAX_VAL)*2*MAX_VAL + col-MAX_VAL)
inc row
# Run computation
let time = cpuTime()
for i in 1..ROUNDS:
grid = nxt(grid)
echo "Time taken: ", cpuTime() - time
echo "Result: ", grid.len
discard stdin.readLine
Your code runs in my computer in about 0.02:
Time taken: 0.020875947
Result: 2276
Time taken: 0.01853268
Result: 2276
Time taken: 0.021355269
Result: 2276
I changed the part where the input is read to this:
# Loads input
var row = 0
let input = open("input.txt")
for line in input.lines:
for i, col in line:
if col == '#':
grid.incl((row-MAX_VAL)*2*MAX_VAL + i-MAX_VAL)
inc row
input.close()
But it shouldn't impact the performance, it just looks better to my eyes. I compiled with:
nim c -d:danger script.nim
Using Nim 1.4.2. -d:danger is the flag for maximum speed before entering deeper waters.
But even compiling in debug mode:
$ nim c -r script.nim
Time taken: 0.07699487199999999
Result: 2276
Way faster than 2 seconds. There has to be other problem in your end. Sorry for the non-answer.

how to run timer function multiple times in parallel in matlab

This is a matlab code that uses guide to run a timer. The timer function counts 10 numbers starting from the number provided in the text field. I would like to know how to enter two numbers successively and make matlab counts 10 numbers for both values in parallel.
let's say I entered 0 then I pressed the start button, then I immediately entered 10 and pressed the start button again. what happens now is that it counts only from 0 to 10. I would appreciate if you can share a way to make my code count from 0 to 10 and from 10 to 20 simultaneously in parallel.
guide code :
function startbutton_Callback(hObject, eventdata, handles)
t=timer;
t.TimerFcn = #counter;
t.Period = 15;
t.ExecutionMode = 'fixedRate';
t.TasksToExecute = 1;
start(t);
stop (t);
delete (t);
timer callback function:
function counter(~,~)
handles = guidata(counterFig);
num = str2double(get(handles.edit1,'String'));
for i = 0:10
disp (num);
num = num+1;
pause (1);
end
you can use parrallel toolbox for real parallel computation.
but if you dont have that , you can create another timer object that count from 10 to 20
and run it

How to run a while loop in the background of my program?

So I'm making a Quiz for a school project and I want to start a timer at the start of the Quiz which will be stopped at the end and printed the time took for the player to complete the Quiz, I put the Timer that I created at the start but my program gets stuck at the 'While loop' and doesn't continue with the program.
Heres the beginning of my code:
import time
score = 0
lives = 3
o = 1
timer = 0
while o == 1:
time.sleep(1)
timer += 1
I add 1 to 'o' just before the Quiz ends so I can print out the time taken but I can get past the start
Your While loop isnt comparing the value of 'o'. Use == not = and check.

Resources