Real time process list - time

I'm trying to make a real time process list at python. I want that every 5 seconds the list i made will be updated. Moreover I want to get cpu time usage for each process but the output is 0 for some reason....
This is a part from the code:
def start(self):
while True:
#-----------------------------------------------------------------------------
processes = []
for process in self.wmi_object.Win32_Process ():
size = int(process.WorkingSetSize) / 1024
try:
p = psutil.Process(process.ProcessId)
cpu_percent = 0# p.cpu_percent(interval=1)
processes.append( process.Name + " " + str(process.ProcessId) + " " + str(size) + "kb" + " " + str(cpu_percent) )
except : pass
self.clientNetwork.send ( pickle.dumps(processes) )
time.sleep(5)
I don't know how to make this a right. Every 5 second the processes just added to the list the previous stay instead of being deleted.
Appriciate help :)

Related

How to Enable Scroll Bar of QBasic Output Window?

I'm trying to display a statement 1000 times in QBASIC (using for statement). I think the program works properly, but I cannot see the 1000 statements because I cannot scroll up and down in the output window of QBASIC. I can see only the last part of the 1000 statements.
FOR x = 1 TO 1000
PRINT "maydie";
PRINT
NEXT x
That will be very hard. For QBasic you have to know how PRINT works. Than with look you could write an TSR program that does what you want in some other language. Alternative is store everything in array and create you own display routine with scrolling. But with 1000 lines will run into memory restrictions
In short, unless you're using a modern take on QBasic, you can't.
What you can do is print the output to a text file:
OPEN "C:\somefile.txt" FOR OUTPUT AS #1
FOR x = 1 TO 1000
PRINT #1, "maydie":
PRINT
NEXT x
This will write "maydie" to C:\somefile.txt 1000 times. Then use some text editor to view the output. You could even use a program to count the lines of text, something like OPEN "C:|somefile.txt" FOR INPUT AS #1: WHILE NOT EOF(1): INPUT #1, junk$: i = i + 1: WEND: PRINT "There were " + STR$(i) + " lines."
Though the other answerers are correct in saying that it is not inbuilt and hence not possible, I agree that this is very desirable! Consequently, I have time and time again devised scripts based on the following:
DIM text(1 to 1000) AS STRING
'Define text below: Here I've just defined it as every line being
'"maydie" with the value of the line number, but it could be whatever.
FOR i = 1 TO 1000
text(i) = STR$(i) + "maydie"
NEXT i
CLS
position% = 0
FOR i = 1 to 25
LOCATE i, 1: PRINT text(i); SPACE$(80 - LEN(text(i)));
NEXT i
DO
x$=INKEY$
IF x$ <> "" THEN
SELECT CASE x$
CASE CHR$(0) + CHR$(72) 'Up arrow
position% = position% - 1
IF position% < 0 THEN position% = 0
CASE CHR$(0) + CHR$(80) 'Down arrow
position% = position% + 1
IF position% > 975 THEN position% = 975
CASE CHR$(0) + "I" 'Page Up
position% = position% - 24
IF position% < 0 THEN position% = 0
CASE CHR$(0) + "Q" 'Page Down
position% = position% + 24
IF position% > 975 THEN position% = 975
CASE CHR$(27) 'ENDS the Program on ESC key.
END
END SELECT
FOR i = 1 to 25
LOCATE i, 1: PRINT text(i + position%); SPACE$(80 - LEN(text(i + position%)));
NEXT i
END IF
LOOP
Tested and works! If you want to use it multiple times in your program for multiple different text blocks, you can just turn it into a function and pass it the variables you want.

why doesn't this ruby code work

here's a practice question - Write a method that will take in a number of minutes, and returns a string that formats the number into hours:minutes.
def time_conversion(minutes)
hours = minutes / 60
mins = minutes % 60
time = hours + ":" + mins
return time
end
the following are tests to see if this works. if they return true then it means my code works correctly.
puts('time_conversion(15) == "0:15": ' + (time_conversion(15) == '0:15').to_s)
puts('time_conversion(150) == "2:30": ' + (time_conversion(150) == '2:30').to_s)
puts('time_conversion(360) == "6:00": ' + (time_conversion(360) == '6:00').to_s)
sometimes i get true for the first two tests but the third test line shows false even though the code will print out exactly the required.
other times I get the following error:
String can't be coerced into Fixnum (repl):4:in +' (repl):4:intime_conversion' (repl):1:in `initialize'
please assist.
The error mainly refers to this line
time = hours + ":" + mins
hours & mins are Fixnum, whereas ":" is String
As the error message indicates, "String can't be coerced into Fixnum".
You could either do time = hours.to_s + ":" + minutes.to_s or time = "#{hours}:#{minutes}".
Because Fixnum#+ takes a Numeral argument, not a String.

Multiprocessing and shared multiprocessing manager lists for parsing large file

I am trying to parse a huge file (approx 23 MB) using the code below, wherein I populate a multiprocessing.manager.list with all the lines read from the file . In the target routine (parse_line) for each process, I pop a line and parse it to create a defaultdict object with certain parsed attributes and finally push each of these objects into another multiprocessing.manager.list.
class parser(object):
def __init__(self):
self.manager = mp.Manager()
self.in_list = self.manager.list()
self.out_list = self.manager.list()
self.dict_list,self.lines, self.pcap_text = [],[],[]
self.last_timestamp = [[(999999,0)]*32]*2
self.num = Word(nums)
self.word = Word(alphas)
self.open_brace = Suppress(Literal("["))
self.close_brace = Suppress(Literal("]"))
self.colon = Literal(":")
self.stime = Combine(OneOrMore(self.num + self.colon) + self.num + Literal(".") + self.num)
self.date = OneOrMore(self.word) + self.num + self.stime
self.is_cavium = self.open_brace + (Suppress(self.word)) + self.close_brace
self.oct_id = self.open_brace + Suppress(self.word) + Suppress(Literal("=")) \
+ self.num + self.close_brace
self.core_id = self.open_brace + Suppress(self.word) + Suppress(Literal("#")) \
+ self.num + self.close_brace
self.ppm_id = self.open_brace + self.num + self.close_brace
self.oct_ts = self.open_brace + self.num + self.close_brace
self.dump = Suppress(Word(hexnums) + Literal(":")) + OneOrMore(Word(hexnums))
self.opening = Suppress(self.date) + Optional(self.is_cavium.setResultsName("cavium")) \
+ self.oct_id.setResultsName("octeon").setParseAction(lambda toks:int(toks[0])) \
+ self.core_id.setResultsName("core").setParseAction(lambda toks:int(toks[0])) \
+ Optional(self.ppm_id.setResultsName("ppm").setParseAction(lambda toks:int(toks[0])) \
+ self.oct_ts.setResultsName("timestamp").setParseAction(lambda toks:int(toks[0]))) \
+ Optional(self.dump.setResultsName("pcap"))
def parse_file(self, filepath):
self.filepath = filepath
with open(self.filepath,'r') as f:
self.lines = f.readlines()
for lineno,line in enumerate(self.lines):
self.in_list.append((lineno,line))
processes = [mp.Process(target=self.parse_line) for i in range(mp.cpu_count())]
[process.start() for process in processes]
[process.join() for process in processes]
while self.in_list:
(lineno, len) = self.in_list.pop()
print mp.current_process().name, "start"
dic = defaultdict(int)
result = self.opening.parseString(line)
self.pcap_text.append("".join(result.pcap))
if result.timestamp or result.ppm:
dic['oct'], dic['core'], dic['ppm'], dic['timestamp'] = result[0:4]
self.last_timestamp[result.octeon][result.core] = (result.ppm,result.timestamp)
else:
dic['oct'], dic['core'] = result[0:2]
dic['ppm'] = (self.last_timestamp[result.octeon][result.core])[0]
dic['ts'] = (self.last_timestamp[result.octeon][result.core])[1]
dic['line'] = lineno
self.out_list.append(dic)
However this entire process takes approximately 3 minutes to complete.
My question is, if there is a better way to make this faster ?
I am using pyparsing module to parse each line, if it makes any difference.
PS: Made changes in the routine Paul McGuire's advice
Not a big performance issue, but learn to iterate over files directly, instead of using readlines(). In place of this code:
self.lines = f.readlines()
for lineno,line in enumerate(self.lines):
self.in_list.append((lineno,line))
You can write:
self.in_list = list(enumerate(f))
A hidden performance killer is using while self.in_list: (lineno,line) = list.pop(). Each call to pop removes the 0'th element from the list. Unfortunately, Python's lists are implemented as arrays. To remove the 0'th element, the 1..n-1'th elements have to be moved up one slot in the array. You don't really have to destroy self.in_list as you go, just iterate over it:
for lineno, line in self.in_list:
<Do something with line and line no. Parse each line and push into out_list>
If you are thinking that consuming self.in_list as you go is a memory-saving measure, then you can avoid the array-shifting inefficiency of Python lists by using a deque instead (from Python's provided collections module). deque's are implemented internally as linked lists, so that pushing or popping to and from either end is very fast, but indexed access is slow. To use a deque, replace the line:
self.in_list = list(enumerate(f))
with:
self.in_list = deque(enumerate(f))
Then replace the call in your code self.in_list.pop() with self.in_list.popleft().
But MUCH more likely to be the performance issue is the pyparsing code you are using to process each line. But since you didn't post the parser code, there is not much help we can provide there.
To get an idea about where the time is going, try leaving all your code, and then comment out the <Do something with line and line no. Parse each line and push into out_list> code (you may have to add a pass statement for the for loop), and then run against your 23MB file. This will give you a rough idea about how much of your 3 minutes is being spent in reading and iterating over the file, and how much is being spent doing the actual parsing. Then post back in another question when you find where the real performance issues lie.

It's Making A Continuous Loop!!! What Is Wrong?

Ok, so I have been given the task to create a script that can increase or decrease the volume. My problem is when I run it, and type in "Decrease" then type in "29" it goes down to 0 then starts to loop. Can you please tell me where the loop is and how to fix it?
set Keys = CreateObject("WScript.Shell") 'So The Script Can Simulate Key Presses
set oShell = CreateObject("WScript.Shell") 'So The Script Can Control The Master Volume
'Asks The User If They Wish To Increase Or Decrease The Volume
Answer = InputBox("Increase Or Decrease Volume?", "Increase/Decrease Volume:")
If Answer = "Increase" Then 'If The User Types In Increase The Following Happens
'Runs The Master Volume App.
oShell.run"%SystemRoot%\System32\SndVol.exe"
'Stops The Program For # Milliseconds
WScript.Sleep 1500
'Asks How Much To Increase The Volume By
Amount = InputBox("How Much Do You Want To Turn The Volume Up?", "Increment:")
'Pushes the Up Arrow Key The Amount Of Which The User Entered
For X = 0 To Amount Step 1
'Simulates The Pushing Of The Up Arrow
Keys.SendKeys("{Up}")
X =+ 1 'Counter Increment
Next
ElseIf Answer = "Decrease" Then 'If The User Types In Decrease The Following Happens
'Runs The Master Volume App.
oShell.run"%SystemRoot%\System32\SndVol.exe"
'Stops The Program For # Milliseconds
WScript.Sleep 1500
'Asks How Much To Decrease The Volume By
Amount = InputBox("How Much Do You Want To Turn The Volume Down?", "Decrement:")
'Pushes the Down Arrow Key The Amount Of Which The User Entered
For X = 0 To Amount Step 1
'Simulates The Pushing Of The Down Arrow
Keys.SendKeys("{Down}")
X =+ 1 'Counter Increment
Next
ElseIf Answer = "" Then 'If The User Pushes Cancel The Following Happens
Question = MsgBox("Do You Wish To Quit?",vbYesNo,"Quit:")
'If The User Pushes Yes Then The Script Will End
If Question = vbYes Then
WScript.Quit 0 'Stops The Script
End if
Else
MsgBox("The Values Allowed Are:" & vbNewLine & "Increase" & vbNewLine & "Decrease")
End If
Does VBScript have Increment Operators
X = X + 1 is the proper way of achieving what you're trying to do with X =+ 1 (which may just be setting X to 1 over and over again). In your usage however, you can take those lines out completely since the For X = 0 To Amount Step 1 should already be handling the increment for you.
There is no =+ (add and assign) operator in VBScript. Your
X =+ 1 'Counter Increment
is seen as
X = +1 ' assign +1 to X
Evidence:
>> X = 10
>> X =+ 1
>> WScript.Echo X
>>
1
You should delete those lines as the loop variable in a For To statement updates automagically.

web app is sharing the same memory storage [duplicate]

This question already has answers here:
Computing Result on server side but session data not isolated per user
(3 answers)
Closed 8 years ago.
I working in a app that i use to compute user details. But somehow, the values of a user alter that of another user.
Below is a fragment of the code
def Compute_UserScore(self, details, ques_no):
try:
if(HomePage.answer_.strip() == ""):
self.response.write("""<script type = "text/javascript">
alert("Dear User, You can not answer same answer twice.. Take test Again !");
</script>""")
self.redirect('/otherPages/subjectSelect.html')
else:
count = 0
HomePage.ans_no = 0
HomePage.unans_no = 0
HomePage.correct_no = 0
HomePage.wrong_no = 0
HomePage.failed_ques = list()
HomePage.answer_ = HomePage.answer_.strip()
question_1 = HomePage.question_.split(" gcdc_split_format ")
while (count != (ques_no)):
user_answer = str(details[count]).strip().capitalize()
real_answer = str(HomePage.answer_[count]).strip().capitalize()
if (len(str(user_answer).strip()) == 1):
HomePage.ans_no = HomePage.ans_no + 1
if(user_answer.strip() == real_answer.strip()):
HomePage.correct_no = HomePage.correct_no + 1
else:
HomePage.wrong_no = HomePage.wrong_no + 1
HomePage.failed_ques.append(str("No. " + str(int((count + 1))) + " " + str(question_1[count])))
else:
HomePage.unans_no = HomePage.unans_no + 1
count = count + 1
HomePage.answer_ = ""
except:
self.redirect('/')
return " "
and this is how my homepage looks like
class HomePage(webapp2.RequestHandler):
percentage = None
subject_answered = None
username_ = None
email_ = None
super_date = None
answer_ = " "
question_ = " "
failed_ques = list()
wrong_no = 0
correct_no = 0
ans_no = 0
unans_no = 0
The problem is, when a user A, take a test, He sees the result of another user B.
Read about Using instance variable, but still have not figure ouut how to make it work
Solution is simple: Stop setting class variables in web development! :)
Web requests are stateless, it's mean you never know what's happen between requests - between setting class variable and redirect.
Use database to store temporary data with user login/name (or use hashing/random for security) or send values by parameters (hidden or after '?') to other html page.
Using database is better, if you don't want this then send values (hidden in html) over http. Here is one version of solution (without database):
1.Use normal html form and write handler for this form - question page.
2.In handler write get method like this:
def post(self, some_parameters):
...
self.render('homepage.html', {'ans_no': ans_no,\
'uans_no': uans_no ...})
3.homepage.html have to be template for showing results

Resources