def main(self): c = Create(15) c.setDistribution('exp') c.setName('creator') p0 = Doctor(0, 0, 2) p0.setName('doctors') p0.setDistribution('exp') p1 = Process(3, 8, 3) p1.setName('chambers') p1.setDistribution('unif') #p1.setDistribution('exp') p2 = Process(3, 4.5, 1) p2.setName('registration') #p2.set_distribution('erlang') p2.setDistribution('exp') #p2.maxQueue = 2 p3 = Labs(2, 4, 2) p3.setName('lab') p3.setDistribution('exp') #p3.set_distribution('erlang') #p0.chambers = p1 #p0.registration = p2 c.nextElement = p0 p0.setNextElements([p1, p2]) p2.setNextElements([p3]) p3.setNextElements([p0]) elementsList = [c, p0, p1, p2, p3] model = Model(elementsList) model.simulate(10000.0)
def get_files(): """Return a list of python files that differs from the remote.""" # Figure out the remote name. branch_name, _, _ = Process().run("git rev-parse --abbrev-ref HEAD") remote = "origin/" + branch_name # Get all the files that differ from 'remote'. stdout, _, _ = Process().run("git diff %s --name-only" % remote, verify=True) if not stdout: return [] # Check which files are python files. python_files = [] for file in (line for line in stdout.split("\n") if line): if file.endswith(".py"): python_files.append(file) else: try: with open(file) as edited_file: # Check the shebang from the first line. if "python" in edited_file.readline(): python_files.append(file) except FileNotFoundError: print("'%s' cannot be opened." % file, file=sys.stderr) return python_files
def main(self): c = Create(.5) p1 = Process(1.0, 2) p21 = Process(4.0, 1) p22 = Process(3.0, 2) p3 = Process(1.2, 1) print('id0 = {} id1= {} '.format(c.getId(), p1.getId())) c.setNextElement(p1) p1.setMaxqueue(5) p21.setMaxqueue(3) p22.setMaxqueue(2) p3.setMaxqueue(2) c.setName('CREATOR') p1.setName('PROCESSOR1') p21.setName('PROCESSOR21') p22.setName('PROCESSOR22') p3.setName('PROCESSOR3') c.setDistribution('exp') p1.setDistribution('exp') p21.setDistribution('exp') p22.setDistribution('exp') p3.setDistribution('exp') p1.setNextElements([p21, p22]) p21.setNextElements([p3]) p22.setNextElements([p3]) elementsList = [c, p1, p21, p22, p3] model = Model(elementsList) model.simulate(1000.0)
def __init__(self, program1, program2): self.memory = Memory(4096) self.memory.load(program1, 0) self.memory.load(program2, 2048) if len(program1) * 32 > 2048 or len(program2) * 32 > 2048: raise ValueError self.process_queue = [[Process()], [Process()]] self.player1 = self.process_queue[0] # process queue of program1 self.player2 = self.process_queue[1] # process queue of program2 self.state = None
def _launch_process(self): self.process = [] for i in range(0, self.config["numprocs"]): if self.config["numprocs"] <= 1: self.process.append( Process(self.name_prog, self.config, self.logger)) else: self.process.append( Process("{}:{}".format(self.name_prog, i), self.config, self.logger)) if self.config["autostart"] == True: self.process[i].start()
def creat_ring_topo(node_count: int) -> list: lst_id = [x for x in range(node_count)] random.shuffle(lst_id) print(lst_id) ring_topo = [] for index, proc_id in enumerate(lst_id[:node_count - 1]): tmp_proc = Process(proc_id, node_count - 1) tmp_proc.prev_nb = lst_id[index - 1] tmp_proc.next_nb = lst_id[index + 1] ring_topo.append(tmp_proc) tmp_proc = Process(lst_id[node_count - 1], node_count - 1) tmp_proc.prev_nb = lst_id[node_count - 2] tmp_proc.next_nb = lst_id[0] ring_topo.append(tmp_proc) return ring_topo
def prepare(txt, amount=100): # create random processes processes = [] for i in range(amount): processes.append(Process(i, randint(2, 20))) # write them to file # here is something i dont really understand why i did # var txt can hold the exact name as seen in line below -------------------------\ # BUT if it doesnt then it is treated differently and instead | # the processes are written to two files at the same time, | # which is a weird behaviour that i believe was done for compatibility | # with running two algorithms at the same time | # but i should REALLY change this | if txt in ["fcfs_input.csv", "sjf_input.csv"]: # <-------------------------------/ with open(txt, "w") as f: for i in processes: f.write("{0}\t{1}\n".format(i.arrivalTime, i.executeTime)) else: with open("fcfs_input.csv", "w") as f: for i in processes: f.write("{0}\t{1}\n".format(i.arrivalTime, i.executeTime)) with open("sjf_input.csv", "w") as f: for i in processes: f.write("{0}\t{1}\n".format(i.arrivalTime, i.executeTime)) # return a chain of processes return processes
def mount(parent, device): mountpoint, options = query_mount(parent, device) if not mountpoint: return None command = ('mount', '-t', 'ocfs2', device, mountpoint) if options: command = list(command) command[1:1] = ('-o', options) p = Process(command, 'Mount', 'Mounting...', parent, spin_now=True) success, output, killed = p.reap() if not success: if killed: error_box( parent, 'mount died unexpectedly! Your system is ' 'probably in an inconsistent state. You ' 'should reboot at the earliest opportunity') else: error_box(parent, '%s: Could not mount %s' % (output, device)) return None else: return mountpoint
def run(bot, update, args): if str(update.message.chat_id) in dict_settings['allowed_ids']: try: user_list = users(update.message.chat_id) usernames = [a['username'].lower() for a in user_list] if not args[1].lower() in usernames: update.message.reply_text( "Sorry, username <b>{}</b> is not saved.".format(args[1]), parse_mode='HTML') return action = args[0] if not action in scripts: update.message.reply_text( "Sorry, action <b>{}</b> is not in your scripts file.". format(action), parse_mode='HTML') return for user in user_list: if user['username'].lower() == args[1].lower(): break process_array[action] = Process(dict_settings['instapy_folder'], action, update.message.chat_id, bot, user['username'], user['password'], scripts) process_array[action].start() except (IndexError, ValueError): update.message.reply_text('Usage: /run <action> <username>') else: message = 'You have not the permission to use this bot.' update.message.reply_text(message)
def main(): if (sys.argv[-1] == '--collect'): url_pois = 'https://pt.foursquare.com/explore?mode=url&ne=-29.358988%2C-50.837817&q=Sele%C3%A7%C3%B5es%20principais&sw=-29.41889%2C-50.887942' url_city = 'http://www.dataviva.info/pt/location/5rs020102' e = Extraction(url_pois, url_city) e.poi_data_extraction() e.city_data_extraction() # Gera relatório do dataset file = 'foursquare_data.csv' df = pd.read_csv(file, parse_dates=True, encoding='UTF-8') profile = pandas_profiling.ProfileReport(df) profile.to_file(outputfile='dataset_report.html') P = Process(file) df = P.method() df_report = pd.read_csv('preprocessed.csv', parse_dates=True, encoding='UTF-8') profile = pandas_profiling.ProfileReport(df_report) profile.to_file(outputfile='preprocessed_dataset_report.html') R = Recommendation(df) R.pattern_recommendation() R.new_recommendation() R.compare() # R.test_rec() ont = Ontology() ont.write_owl()
def run(self, _trace=None, **kwargs): """ Run process :param kwargs: :return: Process instance """ # Find start node start_node = self.get_start_node() if not start_node: raise InvalidStartNode(self.start_node) # trace = self.trace if _trace is None else _trace # Prepare context ctx = {} for v in Variable.objects.filter(workflow=self.id): if v.name in kwargs: ctx[v.name] = v.clean(kwargs[v.name]) elif v.default: ctx[v.name] = v.clean(v.default) else: ctx[v.name] = None p = Process(workflow=self, context=ctx, start_time=datetime.datetime.now(), node=start_node, trace=trace) p.save() # Schedule job p.schedule() return p
def main(): ps = ProcessTable() for i in range(5): ps.append(Process(None, i)) print(f' Исходное состояние \n{ps.__str__()}') model = RR(1).main(ps) print(f' Исходное состояние \n{ps.__str__()}')
def launch_master_thread(n, ids, root, conn_matrix): global id_process, id_label, _terminate print(f'In master thread. Launching {n} threads..') # establish communication channels q = Queue() # master comm channel qhead = None # create threads for p_id, conn in zip(ids, conn_matrix): neighbor_ids = [] for i in range(len(conn)): if conn[i] == 1 and id_label[i] != int(p_id): neighbor_ids.append(id_label[i]) process = Process(int(p_id), root, neighbor_ids, q, qhead) id_process[p_id] = process # start all processes for v in id_process.values(): v.start() # for each round # for k in range(3): # print(f'***** Round {i} ********') # broadcast(q, _terminate) for v in id_process.values(): v.join() print('exiting master thread. bye!')
def __init__(self, filename, maxtime): """ Builds an instance of "Simulation", including its events engine, the underlying network, the weights of the links & the table of processes. """ emptyline = re.compile('\n') self.__numnodes = 0 # <-- Contador self.__engine = Simulator(maxtime) f = open(filename) lines = f.readlines() f.close() self.__graph = [] self.__weights = [] for line in lines: fields = line.split() neighbors = [] nweight = [] if not emptyline.match(line): # <-- Revisa self.__numnodes += 1 # <-- Aumenta contador for f in fields: subf = f.split(",") if len(subf) == 1: neighbors.append(int(f)) nweight.append(1) elif len(subf) == 2: neighbors.append(int(subf[0])) nweight.append(int(subf[1])) self.__graph.append(neighbors) self.__weights.append(nweight) self.__table = [[]] # la entrada 0 se deja vacia for i, row in enumerate(self.__graph): newprocess = Process(row, self.__weights[i], self.__engine, i + 1) self.__table.append(newprocess)
def initUI(self): layout = [[sg.Text('Improvise. Adapt. Overcome.', size=(30, 1), font=("Helvetica", 25))], [sg.Image(filename='', key='frame'), sg.Image(filename='', key='dst_img')], [sg.Text('Choose A Folder', size=(35, 1))], [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'), sg.InputText('Default Folder', key='path'), sg.FileBrowse()], [sg.Button('Load'), sg.Button('Start'), sg.Button('Save'), sg.Button('About'), sg.Button('Quit')]] window = sg.Window('My Basketball Coach', default_element_size=(80, 1)).Layout(layout) window.Move(0, 0) process = None about_window_active = False while True: event, values = window.ReadNonBlocking() if event == 'Load': play_border = sg.PopupGetText('Please type the number of play that will be processed.', 'Number of Plays') process = Process(values['path'], play_border) elif event == 'Start': sg.Popup( 'Please select with the order below:\nTop Left, Bottom Left, Bottom Right and Top Right.\nHit "e" for selection, "r" for select again.') process.getInitFourPoints() sg.Popup('Please select the backboard.\nHit "Enter" for selection, "c" for select again.') process.getInitROI() process.start() elif event == 'Quit': break elif event == 'Save': save_path = sg.PopupGetFile('Choose', save_as=True) cv2.imwrite(save_path + ".png", process.dst_image_clone) elif event == 'About' and not about_window_active: about_window_active = True window.Hide() layout_about = [[sg.Text('My Basketball Coach', size=(30, 1), font=("Helvetica", 25))], [sg.Text('To use the application, please choose a video from file browser.', size=(60, 1), font=("Helvetica", 15))], [sg.Text('Then, click "Load" button to create a new session.', size=(60, 1), font=("Helvetica", 15))], [sg.Text('Click "Start" to run the application.', size=(60, 1), font=("Helvetica", 15))], [sg.Text('Given number of plays will be processed after start.', size=(60, 1), font=("Helvetica", 15))], [sg.Text('After the heat map is created, click "Save" to save heat map as PNG.', size=(60, 1), font=("Helvetica", 15))], [sg.Text('Restart process to create another heat map or click "Quit" to exit the application.', size=(60, 1), font=("Helvetica", 15))], [sg.Text('Never say never because limits, like fears, are often just an illusion. -Michael Jordan', text_color="red" ,size=(80, 1), font=("Helvetica", 15))], [sg.Button('Exit')]] about_window = sg.Window('About', default_element_size=(120, 1)).Layout(layout_about) while True: event2, values2 = about_window.Read() if event2 == 'Exit': about_window.Close() about_window_active = False window.UnHide() break if process is not None: dst_image = cv2.cvtColor(process.dst_image_clone, cv2.COLOR_BGR2RGB) # dst_image = imutils.resize(dst_image, width=400) img = Image.fromarray(dst_image) # create PIL image from frame bio = io.BytesIO() # a binary memory resident stream img.save(bio, format='PNG') # save image as png to it imgbytes = bio.getvalue() # this can be used by OpenCV hopefully window.FindElement('dst_img').Update(data=imgbytes)
def prepare_process(self, process_name: str) -> Process: process = Process(process_name) process.name_pad = self.name_pad if len(self.prepared_processes) < 1000: process.activate(self.generate_pid(), self.quantum_rat) self.prepared_processes.append(process) return process
def validate(model_filename): word_model = CustomEmbedding() valid_set, indexes = word_model.valid_set, word_model.indexes w2idx, la2idx = indexes['w2idx'], indexes['la2idx'] idx2w, idx2la = indexes['idx2w'], indexes['idx2la'] n_classes = len(idx2la) n_vocab = len(idx2w) valid_x, valid_label = valid_set log("Processing word indexes... ") words_val = [list(map(lambda x: idx2w[x], w)) for w in valid_x] groundtruth_val = [list(map(lambda x: idx2la[x], y)) for y in valid_label] log("Done processing word indexes!") process = Process() process.load(model_filename) predword_val = process.validate(valid_set) metrics = conlleval(predword_val, groundtruth_val, words_val, 'diff.txt') log('Precision = {}, Recall = {}, F1 = {}'.format(metrics['precision'], metrics['recall'], metrics['f1']))
def update(self): print("\n---------------") print("Starting Update.\n") self.stop() Process().update_all() print("\nUpdate finished") print("---------------\n")
def parse_jobs(jobs): returned_jobs = list() for job in jobs: burst, arrival = job.split(":") returned_jobs.append(Process(int(burst), int(arrival))) return returned_jobs
def count_word(self): """ Count stop words and output statistics. """ word_list = [] result = ETL().extract_word() count, total = 0, len(result) for row in result: count += 1 test_id = row[0] print(f"{test_id}, {count}/{total}") try: dump = ETL().extract_cdb(test_id) processed = Process(dump).internal_process() except (IndexError, UnicodeDecodeError): continue if "\n\n" in dump: exceptions = dump[dump.index("\n\n") + len("\n\n"):] try: header = "exception throw location:\n" stack = exceptions[exceptions.index(header) + len(header):] except ValueError: continue # extract root cause from exceptions if dump.count(header) > 1: stack = stack[:stack.index("\n\n")] roots = re.findall(r"^\d+:[ ](.+)[ ]at[ ].+", stack, re.M) words = self.obtain_word(roots, processed) word_list += words Log().chart_print(Counter(word_list).most_common(10))
def home(): dropdown_list = [] try: countryField = pd.read_csv( "AVOXI Coding Challenge - Automation - ITFS Packages.csv") process = Process(countryField) dropdown_list = set(i for i in countryField.Country) except Exception as e: return render_template('home.html', dropdown_list=sorted(dropdown_list), data=e, valType="") #Handle the posting of the data if request.method == 'POST': country = str(request.form['country']) data = process.processData(country) if isinstance(data, list): valType = "list" else: valType = "" return render_template('home.html', dropdown_list=sorted(dropdown_list), data=data, valType=valType) return render_template('home.html', dropdown_list=sorted(dropdown_list), data=[])
def now(bot, update, args): if str(update.message.chat_id) in dict_settings['allowed_id']: try: usernames = [ a['username'].lower() for a in users ] if not args[1].lower() in usernames: update.message.reply_text("Sorry, username <b>{}</b> is not saved.".format(args[1]), parse_mode='HTML') return if not args[0] in scripts: update.message.reply_text("Sorry, script named <b>{}</b> is not in your scripts file.".format(args[0]), parse_mode='HTML') return job_name = "{}_temp_{}".format(args[0], int( time.time() )) for user in users: if user['username'].lower() == args[1].lower(): break process_array[job_name] = Process( dict_settings['instapy_folder'], job_name, args[0], update.message.chat_id, bot, user['username'], user['password'], scripts, proxy=user['proxy'] ) process_array[job_name].start() except (IndexError, ValueError): update.message.reply_text('Usage: /now <script_name> <username>') else: message = 'You have not the permission to use this bot.\nFor more details visit [Telegram-InstaPy-Scheduling](https://github.com/Tkd-Alex/Telegram-InstaPy-Scheduling)' update.message.reply_text(message, parse_mode='Markdown')
def __init__(self, compare_func=strictly_compare, name: str = '', max_time: list = [], max_memery: list = [], inputfiles: list = [], score: int = 100, sub_score: list = [], anses: list = [], input_cc_code: str = '', tmp_cc_path: str = 'main.cpp', tmp_output_dir: str = './', output_cc_file='./main', additional_args: list = [], compare_in_memory: bool = True, load_ans: bool = False,exit_if_error:bool=True, use_cc_file=False, enable_o2: bool = True,clean:bool=False): super().__init__() self.process = Process() self.compare_func = compare_func self.name = name self.max_time = max_time self.max_memory = max_memery self.inputfiles = inputfiles self.anses = anses self.input_cc_code = input_cc_code self.output_cc_file = output_cc_file self.additional_args = additional_args self.compare_in_memory = compare_in_memory self.use_cc_file = use_cc_file self.enable_o2 = enable_o2 self.tmp_cc_path = tmp_cc_path self.tmp_output_dir = tmp_output_dir self.load_ans = load_ans self.tmp_output_files = [] self.report = {'compile': {}, 'details': []} self.score = score self.sub_score = sub_score self._clean=clean self.exit_if_error=exit_if_error
def test_process_run_two_segments(): mem = PhysicalMemory(1) pm = PageManager(mem) proc = Process(pm, '../programs/two_fifties.process', 1) proc.run(100) assert proc.state == ProcessState.EXIT assert proc.program_counter == 2
def initialize(self): ''' Restore system to its initial state and create Process 0 Returns process 0 ''' self.PCB = [None] * 16 self.RCB = [None] * 4 #self.ready_list = deque() self.ready_list = { 2: deque(), 1: deque(), 0: deque() } #### WHERE YOU LAST LEFT OFF 10.28.19 5:20 AM ## Creating Process 0 and placing it into Ready List self.PCB[0] = Process(0, 0, 1, 0) ## Process(id/index, state, parent) self.active_processes += 1 self.ready_list[0].append(self.PCB[0].id) self.run_proc = self.PCB[self.ready_list[0][0]] #print(self.run_proc.id) ## Set up all Resources self.RCB[0] = Resource(0, 1) self.RCB[1] = Resource(1, 1) self.RCB[2] = Resource(2, 2) self.RCB[3] = Resource(3, 3) return 0
def create_processes(self): """Create x processes with random size.""" for _ in range(PROCESS_COUNT): proc_size = random.randint(MIN_PAGE_COUNT, MAX_PAGE_COUNT) self.processes.append( Process(self.create_requests(proc_size), proc_size, THRASHING_MIN_LENGTH, THRASHING_FACTOR))
def create_process(self, process, size, time): p = Process(process, size) # creates a new process object pages = self.ram.allocate_page( time, process, size) # tries to allocate memory for the new process if pages is None: # if there was no space in memory print('No size to create new process with size {}'.format(size)) if self.disc.is_full() and ( self.ram.is_full() or size > self.ram.size - self.ram.mem_allocated): # if there are no space at all print('Out of Memory') # it can't create the process return False else: print('###Page fault###') # if there are space, dumps memory print('###Before###') self.print_memories() # memory status before page fault page, pageid = self.ram.get_page_by_method( self.switch_method) # get page from memory self.disc.on_new_page( (time, page, pageid)) # store page in disc print('###After###') self.print_memories() # memory status after page fault return self.create_process( process, size, time) # tries to create proccess again else: # if allocated successfully p.pagetable = pages # pagetable of process is created (received from allocation method) self.process_list[process] = p # puts new process in dictionary print('-Process {} created. Size: {}.'.format( process, size)) # reports success and returns return True
def __init__(self, width, height, title): #init application window super().__init__(width, height, title) # init process object self.process = Process() # set application window background color arcade.set_background_color(arcade.color.BOTTLE_GREEN) # Store gamepad list self.gamepads = arcade.get_joysticks() # check every connected gamepad if self.gamepads: for g in self.gamepads: #link all gamepad callbacks to the current class methods g.open() g.on_joybutton_press = self.__onButtonPressed g.on_joybutton_release = self.__onButtonReleased g.on_joyhat_motion = self.__onCrossMove g.on_joyaxis_motion = self.__onAxisMove # transform list into a dictionary to get its index faster self.gamepads = { self.gamepads[idx]: idx for idx in range(len(self.gamepads)) } else: print("There are no Gamepad connected !") self.gamepads = None
def file_open(self, auto=False): if not auto: fname = QFileDialog.getOpenFileName(self, 'Abrir', '/home') else: fname = "('" + self.path[:-12] + 'autosave' + "', " + "'Todos os arquivos (*)')" self.listProcess = [] if fname[0]: f = open(fname[0], 'r') with f: data = f.read().split('\n') index = 0 for a in data: if a == '': break i = a.split(' ') processo = Process(int(i[0]), int(i[1]), int(i[2]), int(i[3]), int(i[4])) if i[6] == "True": processo.need_io = True else: processo.need_io = False processo.priority = int(i[7]) self.listProcess.append(processo) self.printProcesses()
def launch_threads(ids, conn_matrix, root, config): for p_id, conn in zip(ids, conn_matrix): process = Process(int(p_id), root, conn, config) id_process[p_id] = process for v in id_process.values(): v.start() return id_process