def sms(request): render = {} gate = Gate(request.user.school.gate_url, request.user.school.gate_id, request.user.school.gate_password) render['text'] = gate.getPaymentInfo()['text'] t = gate.getBalance(request.user.gate_id) render['sms'] = t['sms'] render['account'] = t['account'] return render_to_response('sms.html', render, context_instance=RequestContext(request))
def save(self, *args, **kwargs): if not self.pk: if self.pupil.gate_id: from gate import Gate gate = Gate(self.pupil.school.gate_url, self.pupil.school.gate_id, self.pupil.school.gate_password) message = u'%s. %s. ' % (self.lesson.date.strftime('%d.%m.%Y'), self.lesson.subject.name) if self.absent: message = message + u'Отсутствовал' else: message = message + u'Получил %s' % int(self.mark) gate.sendMessage(self.pupil.gate_id, message) super(Mark, self).save(*args, **kwargs)
def __init__(self, conf_str, team1_conf, team2_conf): self._score = [0, 0] self._is_paused = False self._exceptional_type_problem_happened = [False, False] self._croot = ET.fromstring(conf_str) self._t1_croot = ET.fromstring(team1_conf) self._t2_croot = ET.fromstring(team2_conf) self._board = Board.fromNode(self._croot.find('board')) self._gate = Gate.fromNode(self._croot.find('gate')) self._max_score = [int(self._croot.find('max_score').get('left')), int(self._croot.find('max_score').get('right'))] self._balls_init = [] self._team_players1 = [] self._team_players2 = [] for ball in self._croot.findall('./balls/ball'): bi = "self._balls_init.append(game_objects.Ball([" + \ ball.get('x') + "," + \ ball.get('y') + "]," + \ ball.get('r') + " , game_objects.ball_skin))" exec (bi) self._player_deviation = int(self._croot.find('player_deviation').text) t1_filename = self._t1_croot.find('file_name').text exec ("import " + t1_filename) for pl in self._t1_croot.findall('./players/player'): comm = "self._team_players1.append(game_objects.Player([" + \ pl.get('x') + "," + \ pl.get('y') + "]," + \ pl.get('r') + " , game_objects.first_team_skin, " + \ t1_filename + "." + pl.get('logic') + "() , '" + \ pl.get('name') + \ "'))" exec (comm) t2_filename = self._t2_croot.find('file_name').text exec ("import " + t2_filename) for pl in self._t2_croot.findall('./players/player'): comm = "self._team_players2.append(game_objects.Player([" + \ pl.get('x') + "," + \ pl.get('y') + "]," + \ pl.get('r') + " , game_objects.second_team_skin, " + \ t2_filename + "." + pl.get('logic') + "() , '" + \ pl.get('name') + \ "'))" exec (comm) self.refresh()
def generate_iscas_faults(file, num_mutated_gates): net = Net(*SimpleParser(open(file)).parse()) net.generate_random_inputs() net.calculate_outputs() original_outputs = dict(net.outputs) tries = 0 while tries < 100: gates = random.sample(net.gates.values(), num_mutated_gates) mutated_gates = [] tries += 1 for g in gates: m = Gate(*g) m.type = GATE_MUTATION[m.type] mutated_gates.append(m) original_gates = net.mutate_net(mutated_gates) net.reset_outputs() net.calculate_outputs() net.mutate_net(original_gates) if net.outputs != original_outputs: return [file, net.input_values_compact(), mutated_gates] print "Failed to generate fault for " + file + " within 100 tries." net.finished()
async def run(self): """ Setting up Gate, routes and main socket """ app = web.Application() app["api_gate"] = Gate() app.add_routes([ web.get('/api/v1/{entity}', entry_points.api), ]) runner = web.AppRunner(app) await runner.setup() sock = self.__make_socket() srv = web.SockSite(runner, sock) await srv.start() return srv, app, runner
def __get_gates_from_file(self, file): """Get all the gates from the circuit file and store it in the circuit. Keyword arguments: file -- Circuit file to read """ # Initialize a private list to hold logic gates. self.__gates = [] # Read the .in file and get each line. file_content = read_file(file) file_content_lines = file_content.splitlines() # Parse each line for gate information. for i in range(len(file_content_lines)): # Get the gate information separated by whitespaces. data = file_content_lines[i].split() data_fields = [] gate_inputs = [] # Temporarily store each data field. for j in range(len(data)): # If j is 0, then store an int for the gate ID. if j == 0: data_fields.append(int(data[j])) # Else if j is greater than 2, then store the gate inputs. elif j > 2: gate_inputs.append(data[j].upper()) # Otherwise, simply store either the name or type. else: data_fields.append(data[j].upper()) # Merge the gate inputs into the data fields list. data_fields.append(gate_inputs) # Create a new Gate object and store it. self.__gates.append( Gate(data_fields[0], data_fields[1], data_fields[2], data_fields[3]))
def save(self, force_insert = False, force_update = False, init = False, safe = False): if hasattr(self, 'account'): self.account = str(self.account) if self.pk: if self.prefix == 'p': old = Pupil.objects.get(id = self.id) if self.prefix == 't': old = Teacher.objects.get(id = self.id) if self.prefix == 's': old = Staff.objects.get(id = self.id) if self.school.gate_use: from gate import Gate gate = Gate(self.school.gate_url, self.school.gate_id, self.school.gate_password) if self.prefix == 'p': if not self.gate_id: if len(self.phone_mother) > 5: self.gate_id = gate.addUser(self.phone_mother) if len(self.phone_father) > 5: self.gate_id = gate.addUser(self.phone_father) else: if old.phone_mother != self.phone_mother: gate.changePhone(self.gate_id, self.phone_mother) if old.phone_father != self.phone_father: gate.changePhone(self.gate_id, self.phone_father) if not self.pk or init: if self.school.gapps_use: import gdata.apps.service self.username = self.gen_username() service = gdata.apps.service.AppsService(email = self.school.gapps_login, domain = self.school.gapps_domain, password = self.school.gapps_password) service.ProgrammaticLogin() try: service.CreateUser(self.username, self.last_name, self.first_name, '123456789', quota_limit=1000) except gdata.apps.service.AppsForYourDomainException, (error, ): self.set_password('123456789') super(Clerk, self).save(force_insert, force_update) raise gdata.apps.service.AppsForYourDomainException(error) else: from random import randint username = self.school.prefix + str(randint(10**6, 9999999)) while User.objects.filter(username = username).count()!=0: username = '******' + str(randint(10**6, 9999999)) self.username = username self.set_password("123456789") super(Clerk, self).save(force_insert, force_update)
class Track(): def __init__(self): self.sensors = Sensors() self.displays = Displays() self.gate = Gate() def startRace(self): self.displays.clear() self.gate.release() self.sensors.start() def stopRace(self): # No need to keep sensing when no race is happening self.sensors.stop() # Make sure we can reset the gate self.gate.reset() self.displays.displayTimes(self.sensors.getTimes()) return self.sensors.getTimes() def getTimes(self): return self.sensors.getTimes() def test(self): self.gate.release() time.sleep(2) self.gate.reset() self.displays.displayHex([0xba5e, 0xba11, 0x0]) time.sleep(2) self.displays.displayHex([0x0, 0xcafe, 0xbabe]) time.sleep(2) self.displays.displayHex([0xdead, 0x0, 0xbeef]) time.sleep(2) self.displays.clear() time.sleep(1) currentTime = time.time() while (currentTime + 10.0) > time.time(): self.displays.displayTimes(self.sensors.getState()) self.displays.clear()
def load_objects(self): for x, y in place_objects(CHECK): self.game_objects["check"].append( Checkpoint(x * 8, y * 8, self.plr)) for x, y in place_objects(SWITCH): self.game_objects["switch"].append(Switch(x * 8, y * 8)) for x, y in place_objects(BAD_ROBOT): self.game_objects["robot"].append(BadRobot(x * 8, y * 8, self.cam)) for x, y in place_objects(BADDER_ROBOT): self.game_objects["robot"].append( BadRobot(x * 8, y * 8, self.cam, True)) for x, y in place_objects(MOVING_PLATFORM): self.game_objects["platform"].append(MobilePlatform(x * 8, y * 8)) for x, y in place_objects(MOVING_PLATFORM_OPPOSITE): self.game_objects["platform"].append( MobilePlatform(x * 8, y * 8, True)) for x, y in place_objects(LASER): self.game_objects["laser"].append( Laser(x * 8, y * 8, self, self.cam, 3)) for x, y in place_objects(FAST_LASER): self.game_objects["laser"].append( Laser(x * 8, y * 8, self, self.cam, 2)) for x, y in place_objects(VERY_FAST_LASER): self.game_objects["laser"].append( Laser(x * 8, y * 8, self, self.cam, 1)) for id in range(1, GATE_IDS + 1): for x, y in place_objects(GATE_START_ADDRESS + id): self.game_objects["gate"].append(Gate(x * 8, y * 8, id))
class Map(object): """description of class""" def in_map(self, x, y, screen_width, screen_height): if x < 0 or y < 0 or x > screen_width - 1 or y > screen_height - 1: return False return True def __init__(self, width, height): self.player = Player(0, 0) self.box = Box(1, 1) self.gate = Gate(2, 2) self.width = width self.height = height #def print_map(boxes, p, gates, walls, screen_width, screen_height): def print_map(self): for y in range(self.height): for x in range(self.width): if (self.player.check_match(x, y)): print("P", end=" ") elif self.box.check_match(x, y): print("B", end=" ") elif self.gate.check_match(x, y): print("G", end=" ") else: print("-", end=" ") print() def move_player(self, dx, dy): self.player.nextx = self.player.x + dx self.player.nexty = self.player.y + dy self.box.nextx = self.box.x + dx self.box.nexty = self.box.y + dy if (self.in_map(self.player.nextx, self.player.nexty, self.width, self.height)): if self.box.check_match( self.player.nextx, self.player.nexty) and self.in_map( self.box.nextx, self.box.nexty, self.width, self.height): self.box.x = self.box.nextx self.box.y = self.box.nexty self.player.x = self.player.nextx self.player.y = self.player.nexty elif self.box.check_match(self.player.nextx, self.player.nexty): print("NO") else: self.player.x = self.player.nextx self.player.y = self.player.nexty else: print("NO") def player_input(self, direction): dx = 0 dy = 0 if direction == "w": dy = -1 elif direction == "s": dy = 1 elif direction == "a": dx = -1 elif direction == "d": dx = 1 self.move_player(dx, dy) def win(self, bx, by, gx, gy): if (bx == gx) and (by == gy): return True return False def loop(self): while True: self.print_map() direction = input("Your move (W,S,A,D): ") self.player_input(direction) if (self.win(self.box.x, self.box.y, self.gate.x, self.gate.y)): print("YOU WIN") break
class ThreadedClient: gate = None scales = None dispensingControl = None dispensingRule = None tickCounter = 0 """ Launch the main part of the GUI and the worker thread. periodicCall and endApplication could reside in the GUI part, but putting them here means that you have all the thread controls in a single place. """ def __init__(self, master): """ Start the GUI and the asynchronous threads. We are in the main (original) thread of the application, which will later be used by the GUI. We spawn a new thread for the worker. """ self.master = master self.running = 1 self.dispensing_state = 0 # Create the queue self.queue = queue.Queue() # Set up the GUI part self.gui = GuiPart(master, self.queue, self.onEndApplication, self.onGUIEvent) self.gate = Gate(self.processOpeningChange) self.gate.start() self.gate.execute(["Z"]) self.scales = Scales() self.scales.subscribe("WeightChanged", self) self.scales.start() self.scales.execute("T") self.scales.execute("Z") self.dispensingControl = DispensingControl(self.scales, self.gate) self.dispensingControl.subscribe("FlowChanged", self) self.loadDispensingRule() # Start the periodic call in the GUI to check if the queue contains # anything self.periodicCall() def processOpeningChange(self, sender, openingData): self.gui.update(["OpeningPercentage", openingData[0]]) self.gui.update(["OpeningSteps", openingData[1]]) def onWeightChanged(self, weightAndState): weight = weightAndState[0] stable = weightAndState[1] self.gui.update(["ActualWeight", weight]) if self.dispensing_state == 1: opening = self.dispensingRule.getOpeningForWeight(weight) if opening < 0: self.btn_stopdispensing_click() else: self.gate.execute(["P", opening]) def onFlowChanged(self, flow): self.gui.update(["ActualFlow", flow]) def periodicCall(self): """ Check every 100 ms if there is something new in the queue. """ self.gui.processIncoming() if not self.running: # This is the brutal stop of the system. You may want to do # some cleanup before actually shutting it down. import sys sys.exit(1) self.master.after(100, self.periodicCall) def onEndApplication(self): self.gate.execute(["C"]) self.gate.execute("X") self.scales.execute("X") print("before join") self.gate.join() self.scales.join() print("ready") self.running = 0 def onGUIEvent(self, event): if isinstance(event.widget, Button): btn_text = event.widget.cget("text") if btn_text == "Down": self.btn_down_click() elif btn_text == "Up": self.btn_up_click() elif btn_text == "TickDn": self.btn_tickdown_click() elif btn_text == "TickUp": self.btn_tickup_click() elif btn_text == "Zero": self.btn_zero_click() elif btn_text == "Open": self.btn_open_click() elif btn_text == "Close": self.btn_close_click() elif btn_text == "StartDispensing": self.btn_startdispensing_click() elif btn_text == "StopDispensing": self.btn_stopdispensing_click() elif btn_text == "LoadDispRule": self.btn_loaddispensingrule_click() else: print("widgetType = ", typeof(event.widget), ", x= ", event.x, ", y = ", event.y, ", num = ", event.num) def btn_down_click(self): self.gate.execute(["S", 10]) def btn_up_click(self): self.gate.execute(["S", -10]) def btn_tickdown_click(self): self.gate.execute(["S", 1]) def btn_tickup_click(self): self.gate.execute(["S", -1]) def btn_zero_click(self): self.gate.execute(["Z"]) def btn_open_click(self): self.gate.execute(["O"]) def btn_close_click(self): self.gate.execute(["C"]) def btn_startdispensing_click(self): self.dispensing_state = 1 self.scales.execute(["T"]) self.gate.execute(["O"]) self.gui.update(["DispensingState", self.dispensing_state]) # self.periodicWeight() def btn_stopdispensing_click(self): self.dispensing_state = 0 self.gate.execute(["C"]) self.gui.update(["DispensingState", self.dispensing_state]) def btn_loaddispensingrule_click(self): self.loadDispensingRule() def loadDispensingRule(self): if self.dispensingRule is None: self.dispensingRule = DispensingRule() self.dispensingRule.load() self.gui.update(["DispensingRule", self.dispensingRule.asString()])
def assemble_gate(circuit, output_wire, a, gate_type, b): part_a = assemble_input(circuit, a) part_b = assemble_input(circuit, b) gate = Gate(gate_type, part_a, part_b, output_wire) output_wire.set_input(gate)
from gate import Gate sender = Gate(api_login = '******', api_password = '******'); phonesArray = ['79991234567', '79991234576'] # getting account credits print(sender.credits()) #getting sender names and removing from response some shit senders = str(sender.senders()).replace("b'", "").split("\\n") #send sms for phone in phonesArray: print(sender.send(phone = phone, text ='some text here', sender=senders[0])) #you may get status by request id in such way #print(sender.status(12345))
def __init__(self, width, height): self.player = Player(0, 0) self.box = Box(3, 1) self.gate = Gate(2, 3) self.width = width self.height = height
def catchen_open(): gate = Gate() gate.open() return redirect(url_for('index'))
def prefix_gate(gate): output = prefix(gate.output) inputs = [] for input in gate.inputs: inputs.append(prefix(input)) return Gate(output, gate.type, inputs)
def generate_independent_faults(file, num_gates_to_mutate, exclude_gates=[]): net = Net(*SimpleParser(open(file)).parse()) if len(net.outputs) < num_gates_to_mutate: net.finished() raise Exception( "Cannot create %d independent mutations for net with %d outputs" % (num_gates_to_mutate, len(net.outputs))) try_num = 1 log.info("Trying to generate %d independent fault(s) for %s" % (num_gates_to_mutate, file)) while try_num < 2 * (2**len( net.inputs )): # try about two times the number of possible input combinations try_num += 1 net.generate_random_inputs() log.debug("=== Trying input %s" % net.inputs) net.reset_outputs() # unconstrain all outputs at the beginning net.calculate_outputs() previous_outputs = dict(net.outputs) log.debug("Original Outputs: %s" % previous_outputs) net.reset_outputs() gates_to_try = filter(lambda g: g.output not in exclude_gates, net.gates.values()) mutated_gates = [] immutable_outputs = set() while len(mutated_gates) < num_gates_to_mutate: while gates_to_try: log.debug("Previous output: %s" % previous_outputs) random.shuffle(gates_to_try) gate = gates_to_try.pop() mutated_gate = Gate(*gate) mutated_gate.type = GATE_MUTATION[mutated_gate.type] log.debug("Mutating %s to %s" % (gate, mutated_gate)) net.mutate_net([mutated_gate]) if not net.calculate_outputs(): log.debug("Unsatisfiable, undoing mutation.") net.mutate_net([gate]) # restore original gate break new_outputs = dict(net.outputs) log.debug("New output: %s" % new_outputs) changed_outputs = set([ g for g in new_outputs if new_outputs[g] != previous_outputs[g] ]) if changed_outputs: log.debug("found mutation") immutable_outputs |= changed_outputs log.debug("Immutable outputs: %s" % immutable_outputs) mutated_gates.append(mutated_gate) previous_outputs = new_outputs for o in net.outputs: # unconstrain all outputs that didn't change if o not in immutable_outputs: net.outputs[o] = None break else: log.debug("undoing mutation, trying next") net.mutate_net([gate]) for o in net.outputs: # unconstrain all outputs that didn't change (in the last step) if o not in immutable_outputs: net.outputs[o] = None # end while gates_to_try if not gates_to_try and len(mutated_gates) < num_gates_to_mutate: log.debug("no more gates to try :(") break # end while len(mutated_gates) < num_gates_to_mutate: if not len(mutated_gates) < num_gates_to_mutate: break net.finished() # end while try_num < 2*(2**len(net.inputs)): if len(mutated_gates) < num_gates_to_mutate: return None return [file, net.input_values_compact(), mutated_gates]
def __init__(self, args): Gate.__init__(self, args)
def __init__(self, width, height): self.player = Player(2, 2) self.box = Box(3, 3) self.gate = Gate(4, 4) self.width = width self.height = height
class Map: def __init__(self, width, height): self.player = Player(2, 2) self.box = Box(3, 3) self.gate = Gate(4, 4) self.width = width self.height = height def print(self): for y in range(self.height): for x in range(self.width): if self.player.match(x, y): print(self.player.text, end="") elif self.box.match(x, y): print(self.box.text, end="") elif self.gate.match(x, y): print(self.gate.text, end="") else: print("- ", end="") print() def move_player(self, dx, dy): self.player.move(dx, dy) def move_box(self, dx, dy): self.box.move(dx, dy) def in_map(self, x, y): if x < 0 or y < 0 or x > self.width - 1 or y > self.height - 1: return True return False def process_input(self, move): direction = move.upper() dx, dy = 0, 0 if direction == "W": dx, dy = 0, -1 elif direction == "S": dx, dy = 0, 1 elif direction == "A": dx, dy = -1, 0 elif direction == "D": dx, dy = 1, 0 next_px, next_py = self.player.calc_next(dx, dy) if self.in_map(next_px, next_py): print("Another direction please! ") else: next_bx, next_by = self.box.x + dx, self.box.y + dy if next_px == self.box.x and next_py == self.box.y: if self.in_map(next_bx, next_by): print("Your box is facing wall, another direction please!") else: self.player.move(dx, dy) self.box.move(dx, dy) else: self.player.move(dx, dy) def loop(self): while True: self.print() move = input("Your move (A,S,D,W): ") self.process_input(move) if self.box.x == self.gate.x and self.box.y == self.gate.y: print("You win the game, congrats!") self.print() break
def __init__(self): print '<===INIT GATE _PATH===>' self.aicontrol = AIControl() self.gate = Gate() self.path = Path()
def catchen_proceed(): gate = Gate() gate.proceed(2) return redirect(url_for('index'))
def __init__(self, width, height): self.width = width self.height = height self.player = Player(0, 0) self.box = Box(4, 4) self.gate = Gate(0, 5)
def catchen_close(): gate = Gate() gate.close() return redirect(url_for('index'))
def run(name='test.avi'): '''Main function ''' gate_obj = Gate(name) gate_obj.read()
def read(path): print('Reading tasks: ' + path[0]) print('Station locations reference: ' + path[1]) print('Station booth id to rtif id reference: ' + path[2]) print('Checker list: ' + path[3]) print('Special sample: ' + path[4]) sheet = pd.read_excel(path[0]) station_loc = pd.read_csv(path[1]) station_ls = pd.read_excel(path[2]) checker_schedule = pd.read_excel(path[3]) special = pd.read_excel(path[4]) rows = len(sheet) special_rows = len(special) checker_rows = len( checker_schedule ) #checkers available for subway; will need to modify to select specific checkers wkd_graph = Graph(constants.DAY[0], constants.GRAPH_TYPE[1]) sat_graph = Graph(constants.DAY[1], constants.GRAPH_TYPE[1]) sun_graph = Graph(constants.DAY[2], constants.GRAPH_TYPE[1]) # map from rtif id to locations location_book = {} # map from booth id to rtif id station_id_book = {} # build a map for stations and locations for i in range(len(station_loc)): station_id = str(station_loc.loc[i, 'GTFS Stop ID']) latitude = station_loc.loc[i, 'GTFS Latitude'] longitude = station_loc.loc[i, 'GTFS Longitude'] location_book[station_id] = [latitude, longitude] # build a map for station loc and station_rtif_id for i in range(len(station_ls)): station_loc_id = str(station_ls.loc[i, 'loc']) station_id = str(station_ls.loc[i, 'station_rtif_id']) station_id = station_id.split(',')[0] if not station_id_book.get(station_loc_id): station_id_book[station_loc_id] = station_id # build a 3*24 map where each entry represents the number of checkers # available at that time availability_book = {} for i in range(3): availability_book[i] = {} for j in range(24): availability_book[i][j] = 0 for i in range(19, 31): # values 19,31 correspond to range of checkers assigned to subway shift_end_time = int(int(checker_schedule.values[i, 3]) / 100 - 1) shift_start_time = int(int(checker_schedule.values[i, 2]) / 100 + 1) days_off = checker_schedule.values[i, 5] if days_off == 'FRI - SAT': for j in range(shift_start_time, shift_end_time): availability_book[2][j] = availability_book[2][j] + 1 elif days_off == 'SAT - SUN': for j in range(shift_start_time, shift_end_time): availability_book[0][j] = availability_book[0][j] + 1 elif days_off == 'SUN - MON': for j in range(shift_start_time, shift_end_time): availability_book[1][j] = availability_book[1][j] + 1 else: print('Unrecognized days off: ' + days_off) wkd_graph.availability_book = availability_book sat_graph.availability_book = availability_book sun_graph.availability_book = availability_book for i in tqdm(range(rows)): sample_id = sheet.loc[i, 'sample_id'] booth_id = sheet.values[i, 1] day = sheet.values[i, 2] # begin_time has 24-hour format in form x00 where it actually means x:00 # mod 24 because there are some 2400 to 2500 tasks begin_time = int(int(sheet.values[i, 3]) / 100 - 1) boro = sheet.values[i, 6] routes_str = str(sheet.values[i, 7]) name = str(sheet.values[i, 8]) routes = routes_str.split(',') comments = sheet.values[i, 10] # calculate availability priority if day == constants.DAY[0]: i = 0 elif day == constants.DAY[1]: i = 1 elif day == constants.DAY[2]: i = 2 available_checkers = availability_book[i][begin_time] if available_checkers == 0: availability_priority = 1 else: availability_priority = 1 / available_checkers if availability_priority == 1: availability_priority += 1 #test buffer value # get location of a station station_id = station_id_book.get(str(booth_id)) if not station_id: loc = [0, 0] print('RTIF ID for ' + name + ' not found.') loc = location_book.get(station_id) if not loc: loc = [0, 0] print('Location for ' + name + ' not found.') task = Gate(name=name, boro=boro, loc=loc, routes=routes, sample_id=sample_id, booth_id=booth_id, begin_time=begin_time, day=day, comments=comments, availability_priority_holder=availability_priority) # adding vertex to graph if task.day == constants.DAY[0]: wkd_graph.add_vertex(task) elif task.day == constants.DAY[1]: sat_graph.add_vertex(task) elif task.day == constants.DAY[2]: sun_graph.add_vertex(task) # normalize distance priority wkd_graph.normalize_distance_priority() sat_graph.normalize_distance_priority() sun_graph.normalize_distance_priority() wkd_graph.normalize_availability_priority() sat_graph.normalize_availability_priority() sun_graph.normalize_availability_priority() #print and see the graphs # wkd_graph.print() # sat_graph.print() # sun_graph.print() #wkd_graph.vertices[0][0].print() #wkd_graph.vertices[2][5].print() #read special sample for i in range(special_rows): sample_id = special.loc[i, 'sample_id'] booth_id = special.values[i, 1] day = special.values[i, 3] time_period = special.values[i, 9] boro = special.values[i, 5] routes_str = str(special.values[i, 6]) name = str(special.values[i, 4]) routes = routes_str.split(',') comments = special.values[i, 8] # get location of a station station_id = station_id_book.get(str(booth_id)) if not station_id: loc = [] print('RTIF ID for ' + name + ' not found.') loc = location_book.get(station_id) if not loc: loc = [40.775594, -73.97641] print('Location for ' + name + ' not found.') special_task = Gate(name=name, boro=boro, loc=loc, routes=routes, sample_id=sample_id, booth_id=booth_id, day=day, comments=comments, task_type=constants.TASK_TYPE[2]) if day == constants.DAY[0]: if time_period == 'AM': wkd_graph.am_special_tasks.append(special_task) elif time_period == 'PM': wkd_graph.pm_special_tasks.append(special_task) elif day == constants.DAY[1]: if time_period == 'AM': sat_graph.am_special_tasks.append(special_task) elif time_period == 'PM': sat_graph.pm_special_tasks.append(special_task) elif day == constants.DAY[2]: if time_period == 'AM': sun_graph.am_special_tasks.append(special_task) elif time_period == 'PM': sun_graph.pm_special_tasks.append(special_task) with open('wkd_save.pkl', 'wb') as wkd, open('sat_save.pkl', 'wb') as sat, open('sun_save.pkl', 'wb') as sun: pickle.dump(wkd_graph, wkd) pickle.dump(sat_graph, sat) pickle.dump(sun_graph, sun) return wkd_graph, sat_graph, sun_graph
def generate_independent_faults(file, num_gates_to_mutate, exclude_gates=[]): net = Net(*SimpleParser(open(file)).parse()) if len(net.outputs) < num_gates_to_mutate: net.finished() raise Exception("Cannot create %d independent mutations for net with %d outputs" % (num_gates_to_mutate, len(net.outputs))) try_num = 1 log.info("Trying to generate %d independent fault(s) for %s" % (num_gates_to_mutate, file)) while try_num < 2*(2**len(net.inputs)): # try about two times the number of possible input combinations try_num += 1 net.generate_random_inputs() log.debug("=== Trying input %s" % net.inputs) net.reset_outputs() # unconstrain all outputs at the beginning net.calculate_outputs() previous_outputs = dict(net.outputs) log.debug("Original Outputs: %s" % previous_outputs) net.reset_outputs() gates_to_try = filter(lambda g: g.output not in exclude_gates, net.gates.values()) mutated_gates = [] immutable_outputs = set() while len(mutated_gates) < num_gates_to_mutate: while gates_to_try: log.debug("Previous output: %s" % previous_outputs) random.shuffle(gates_to_try) gate = gates_to_try.pop() mutated_gate = Gate(*gate) mutated_gate.type = GATE_MUTATION[mutated_gate.type] log.debug("Mutating %s to %s" % (gate, mutated_gate)) net.mutate_net([mutated_gate]) if not net.calculate_outputs(): log.debug("Unsatisfiable, undoing mutation.") net.mutate_net([gate]) # restore original gate break new_outputs = dict(net.outputs) log.debug("New output: %s" % new_outputs) changed_outputs = set([g for g in new_outputs if new_outputs[g] != previous_outputs[g]]) if changed_outputs: log.debug("found mutation") immutable_outputs |= changed_outputs log.debug("Immutable outputs: %s" % immutable_outputs) mutated_gates.append(mutated_gate) previous_outputs = new_outputs for o in net.outputs: # unconstrain all outputs that didn't change if o not in immutable_outputs: net.outputs[o] = None break else: log.debug("undoing mutation, trying next") net.mutate_net([gate]) for o in net.outputs: # unconstrain all outputs that didn't change (in the last step) if o not in immutable_outputs: net.outputs[o] = None # end while gates_to_try if not gates_to_try and len(mutated_gates) < num_gates_to_mutate: log.debug("no more gates to try :(") break # end while len(mutated_gates) < num_gates_to_mutate: if not len(mutated_gates) < num_gates_to_mutate: break net.finished() # end while try_num < 2*(2**len(net.inputs)): if len(mutated_gates) < num_gates_to_mutate: return None return [file, net.input_values_compact(), mutated_gates]
def _fill_use_flags(self): def pre_evaluate_to_set(use_flags): # .. -foo .. foo .. --> foo # .. foo .. -foo .. --> -foo d = {} for i in [e.lstrip('+') for e in use_flags]: if i.startswith('-'): enabled = False flag = i.lstrip('-') else: enabled = True flag = i d[flag] = enabled return set((enabled and flag or '-' + flag) for flag, enabled in d.items()) def get_use_flags(section): res = pre_evaluate_to_set(portage.settings.configdict[section].get( "USE", "").split()) use_expand = portage.settings.configdict[section].get( "USE_EXPAND", "").split() for expand_var in use_expand: expand_var_values = portage.settings.configdict[section].get( expand_var, "").split() prefix = expand_var.lower() res = res.union( set('%s_%s' % (prefix, e) for e in expand_var_values)) return res publish_global_use_flags = Gate().grants('gentoo', 'global_use_flags') publish_system_profile = Gate().grants('gentoo', 'system_profile') self._use_flags = {} for key in ('defaults', 'conf', 'env'): self._use_flags[key] = {} self._use_flags['defaults']['publish'] = \ publish_global_use_flags and publish_system_profile self._use_flags['conf']['publish'] = publish_global_use_flags self._use_flags['env']['publish'] = \ self._use_flags['defaults']['publish'] and \ self._use_flags['conf']['publish'] _all_use_flags = {} for key in ('defaults', 'conf', 'env'): if self._use_flags[key]['publish']: _all_use_flags[key] = get_use_flags(key) else: _all_use_flags[key] = [] # Filter our private use flags self._non_private_space = self._registered_global_use_flags().union( self._registered_local_use_flags()).union( self._expanded_use_flags()).union(self._auto_use_flags()) def is_non_private(x): positive = x.lstrip('-') return positive in self._non_private_space for key in ('defaults', 'conf', 'env'): self._use_flags[key]['flags'] = \ set(e for e in _all_use_flags[key] if is_non_private(e)) self._use_flags[key]['count_non_private'] = \ len(self._use_flags[key]['flags']) self._use_flags[key]['count_private'] = len(_all_use_flags[key]) - \ self._use_flags[key]['count_non_private']
from gate import Gate import sys args = sys.argv port = None if len(args) == 3: try: port = int(args[1]) except: print('invalid port number') sys.exit(0) relay = Gate(port) command = args[2] if command.lower() == 'open': relay.open() elif command.lower() == 'close': relay.close() elif command.lower() == 'state': relay.print_state() else: print('invalid command; [open, close, state]') sys.exit(0) else: print( 'Please provide proper arguments; e.g. python main.py <port> <command>' )
def __init__(self): self.sensors = Sensors() self.displays = Displays() self.gate = Gate()
from armer import Armer from jerk import AccelGraph class SubController(object): def __init__(self, run_config): self.mover = Mover(run_config) self.armer = Armer(run_config) if __name__ == "__main__": rospy.init_node('tartan_19_controller', anonymous=True) run_config = ConfigMap['Sub'] sub_controller = SubController(run_config) gate = Gate(sub_controller, run_config) print("Arming") sub_controller.armer.arm() print("Gate") gate.execute() sub_controller.armer.disarm() rospy.spin() if __name__ == '__main__': main(sys.argv)
count += 1 else: reset += 1 if count >= 10: reset = 0 count = 0 elif reset >= 10: os.system('rosnode kill /main_ai') if __name__ == '__main__': rospy.init_node('main_ai') rospy.Subsciber('/planner_switch', Bool, getSwitchState, queue_size=1) gate = Gate() path1 = Path() shoot_craps = ShootCraps() path2 = Path() slots = Slots() roulette = Roulette() cash_in = CashIn() gate.run() path1.run() if path1.failed: auv.turnAbs(cons.SC_DEGREES) shoot_craps.run()
def __init__(self, weight, height): self.weight = weight self.height = height self.player = Player(1, 1) self.box = Box(2, 2) self.gate = Gate(3, 3)
def main(): parser = argparse.ArgumentParser() parser.add_argument("--point-permute", help="enable the point-and-permute optimization", action='store_true') parser.add_argument("--free-xor", help="enable the free-XOR optimization", action='store_true') parser.add_argument("--grr3", help="enable the GRR3 optimization", action='store_true') args = parser.parse_args() if args.grr3 and not args.point_permute: print("The GRR3 optimization requires the point-and-permute optimization to be enabled") exit(0) if args.free_xor: config.USE_FREE_XOR = True print("Optimization enabled: free-XOR") if args.point_permute: config.USE_POINT_PERMUTE = True print("Optimization enabled: point-and-permute") if args.grr3: config.USE_GRR3 = True print("Optimization enabled: GRR3") alice = Alice() bob = Bob() # In this implementation we store wires as strings, whose values are those supplied by the user. # These strings uniquely identify the corresponding wire. Not to be confused with labels, for which there are # two for every unique wire! print( "Welcome! Please define your circuit by entering a sequence of logic gate specifications of the form \"z = x " "OP y\", where:") print(" - x and y are identifiers that uniquely specify the gate's two input wires, ") print(" - z is an identifier that uniquely specifies the gate's output wire") print(" - OP is the gate operation, which is one of \"and\", \"or\", \"xor\"") print( "Please enter one logic gate per line. When you are finished defining gates and are ready to proceed, " "please enter a blank line.") wires = dict() out_wires = [] in_wires = [] while True: gate_info = input() if not gate_info: break gate_info = gate_info.split() gate = Gate() if gate_info[3] == "and": gate.op = 'AND' elif gate_info[3] == "or": gate.op = 'OR' elif gate_info[3] == "xor": gate.op = 'XOR' else: raise ValueError("Operation must be one of \"and\", \"or\", \"xor\"") gate.in1 = gate_info[2] gate.in2 = gate_info[4] gate.out = gate_info[0] gates[gate.out] = gate wires[gate.in1] = "" wires[gate.in2] = "" wires[gate.out] = "" in_wires.append(gate.in1) in_wires.append(gate.in2) out_wires.append(gate.out) wires[gate_info[0]] = "" wires[gate_info[2]] = "" wires[gate_info[4]] = "" input_wires = [] output_wires = [] for w in wires: # select the wires that are ONLY input and ONLY output if w in in_wires and w not in out_wires: input_wires.append(w) if w in out_wires and w not in in_wires: output_wires.append(w) print("Detected the following INPUT wires: " + str(input_wires)) print("Detected the following OUTPUT wires: " + str(output_wires)) alice_wires = [] alice_wire_values = [] bob_wires = [] bob_wire_values = [] print("Among the input wires " + str( input_wires) + ", which are supplied by Alice, the garbler? Please enter the wire identifiers seperated by commas.") alice_wires = input().split(",") if len(alice_wires) > 0: # Alice has at least one input print( "What are Alice's boolean input values? Please enter a sequence of 0s and 1s corresponding to her input wires, separated by commas.") alice_wire_values = list(map(int, input().split(","))) # ...therefore, the remaining inputs must be owned by Bob for w in input_wires: if w not in alice_wires: bob_wires.append(w) if len(bob_wires) > 0: print("The remaining input wires, " + str(bob_wires), " must be supplied by Bob. Please enter a sequence of 0s and 1s corresponding to his input wires, separated by commas.") bob_wire_values = list(map(int, input().split(","))) else: print("Assuming all inputs are supplied by Alice, and Bob only evaluates.") else: # Alice has no inputs; all inputs must be owned by Bob print( "Assuming all inputs are supplied by Bob, the evaluator. What are Bob's boolean input values? Please enter a sequence of 0s and 1s corresponding to his input wires, separated by commas.") bob_input_values = input().split(",") # TODO Instead of exiting, handle bad user input gracefully. assert (len(alice_wires) == len(alice_wire_values)) assert (len(bob_wire_values) == len(bob_wire_values)) alice.input_wires = dict(zip(alice_wires, alice_wire_values)) bob.input_wires = dict(zip(bob_wires, bob_wire_values)) print() print("Successfully generated the following circuit: ") circuit = Circuit() # at the moment, we only support one output wire; hence output_wires[0] # but the infrastructure is in place to change this, if we so desire # to do this, we would likely have to represent the circuit as a digraph instead of a tree # and reimplement our construction and evaluation algorithms accordingly circuit.build(output_wires[0], gates) circuit.tree.show() # Give the circuit to Alice to garble alice.circuit = circuit # Instruct Alice to generate labels and garble garble gates using the generated labels print() print("Alice generates labels for the circuit, and garbles gates accordingly:") alice.garble_gates() # Instruct Alice to permute the garbled tables print() print("Alice permutes the entries in each garbled gate's garbled truth table:") alice.permute_entries() # Transfer the circuit to Bob print() print("Alice transfers the circuit to Bob.") bob.circuit = alice.circuit for wire in alice.input_wires: # Transfer the labels corresponding to Alice's input to Bob bob.known_labels[wire] = alice.wire_labels[wire][alice.input_wires[wire]] # Simulate OT between Alice and Bob so that Bob can acquire labels corresponding to his input print() print("Bob uses OT to request from Alice labels corresponding to his input bits:") bob.request_labels(alice) # Instruct Bob to evaluate the circuit print() print("Bob proceeds to evaluate the circuit:") result = bob.evaluate() print() print("Alice reveals the value of the label that Bob computed as the circuit's output:") # Instruct Alice to reveal the result of Bob's computation alice.reveal_result(result)
class Map: def __init__(self, width, height): self.player = Player(3, 2) self.box = Box(2, 4) self.gate = Gate(1, 3) self.width = width self.height = height def print(self): for y in range(self.height): for x in range(self.width): if self.player.match(x, y): print(self.player.text, end=" ") elif self.box.match(x, y): print(self.box.text, end=" ") elif self.gate.match(x, y): print(self.gate.text, end=" ") else: print("-", end=" ") print() def in_map(self, x, y): if x < 0 or y < 0 or x > self.width - 1 or y > self.height - 1: return True return False def move_box(self, dx, dy): self.box.move(dx, dy) def move_player(self, dx, dy): self.player.move(dx, dy) def process_input(self, move): # W S D A dx = 0 dy = 0 direction = move.upper() if direction == "W": dx, dy = 0, -1 elif direction == "S": dx, dy = 0, 1 elif direction == "A": dx, dy = -1, 0 elif direction == "D": dx, dy = 1, 0 [next_px, next_py] = self.player.calc_next(dx, dy) if self.in_map(next_px, next_py): print(" Please, Come back") else: next_bx = self.box.x + dx next_by = self.box.y + dy if next_px == self.box.x and next_py == self.box.y: if self.in_map(next_bx, next_by): print("NOT GO") else: self.move_player(dx, dy) self.move_box(dx, dy) else: self.move_player(dx, dy) def loop(self): while True: self.print() move = input("You move: W S A D") self.process_input(move) if self.box.x == self.gate.x and self.box.y == self.gate.y: self.print() print(" YOU WIN !!") break elif self.box.x == 0 and self.box.y == 0: print("YOU LOSE") break elif self.box.x == 0 and self.box.y == self.height - 1: print("YOU LOSE") break elif self.box.x == self.width - 1 and self.box.y == 0: print("YOU LOSE") break elif self.box.x == self.width - 1 and self.box.y == self.height - 1: print("YOU LOSE") break
class StrategyStraight: def __init__(self): self.control = CommandInterfaces("strategy") self.control.publish_data("Waiting service name /vision/gate") rospy.wait_for_service('/vision/gate') self.rate = rospy.Rate(10) # Step setup mission gate # try: # gate_srv = rospy.ServiceProxy('/vision/gate', VisionGate) # except rospy.ServiceException, e: # print("Service call failed: %s" % e) # self.mission_gate = Gate(gate_srv) self.mission_gate = Gate() # Step setup mission Path self.mission_path = Path(_CONSTANT_PATH_1_MOVEMENT_X_, _CONSTANT_PATH_1_MOVEMENT_Y_) self.vision_path = AnalysisPath() # Step setup mission buoy self.mission_buoy = Buoy() self.vision_buoy = AnalysisBuoy() self.current_play = False # Step setup service of strategy_mission self.service_service = rospy.Service('/mission/strategy', SendBool(), self.callback_service) self.control.publish_data("Waiting command to run mission") while (not rospy.is_shutdown()): if (self.current_play): self.main() self.current_play = False break self.rate.sleep() # Start part of all mission def main(self): self.control.reset_state() self.control.publish_data("Now I will run code doing mission gate") # self.mission_gate.step00_checkDeep() # if( not rospy.is_shutdown() ): # self.mission_gate.step01_rotateAndFindGate() # if( not rospy.is_shutdown() ): # self.mission_gate.step01_5_lockYawToGate() # if( not rospy.is_shutdown() ): # self.mission_gate.step02_forwardWithMoveLeftRight() self.mission_gate.start_mission() self.control.publish_data( "Finish to search gate I will move forward with serach path") self.control.publish_data( "I will move forward by parameter of gate with find path") self.control.relative_xy(7, 0) count = 0 # This step will use to movement with rotation yaw self.control.update_target() collect_yaw = self.control.target_pose[5] self.control.publish_data("SPIN PASS GATE") while (not self.control.check_xy(0.1, 0.1)): self.rate.sleep() self.vision_path.call_data() self.vision_path.echo_data() if (self.vision_path.num_point != 0): self.control.get_state() count += 1 else: count = 0 if (count == 2): self.control.publish_data( "I found path 2 round at here reset now") self.control.reset_state() self.control.publish_data("Sleep 2 second wait to reset state") rospy.sleep(2) self.control.publish_data("Wakeup I will waiting yaw") while (not self.control.check_yaw(0.15)): self.rate.sleep() relative_x = self.vision_path.y_point[0] * 0.8 / 100 relative_y = self.vision_path.x_point[0] * -1.2 / 100 self.control.publish_data("Move go to path ( x , y ) : " + repr((relative_x, relative_y))) self.control.relative_xy(relative_x, relative_y) while (not self.control.check_xy(0.15, 0.15)): self.rate.sleep() break if (self.control.check_yaw(0.6)): self.control.publish_data("Adding spin yaw") self.control.relative_yaw(math.pi / 1.5) # End part of movement with rotation yaw self.control.publish_data("Return absolute yaw " + str(collect_yaw)) self.control.absolute_yaw(collect_yaw) while (not self.control.check_yaw(0.15)): self.rate.sleep() if (count == 2): self.control.publish_data("I start path by ever found path") else: self.control.publish_data("I start path by never found path") result = self.mission_path.find_path() if (result): self.control.publish_data("Congratulation we know you pass path") else: self.control.publish_data("It bad you failure mission path") self.control.absolute_yaw( zeabus_math.bound_radian(collect_yaw + (math.pi / 2))) self.control.publish_data( "Waiting yaw before send process to buoy_straight") while (not self.control.check_yaw(0.15)): self.rate.sleep() self.mission_buoy.start_mission() self.control.publish_data( "Finish play buoy next I will play path move up") self.control.absolute_z(-1) while (not self.control.check_z(0.15)): self.rate.sleep() self.control.publish_data("Waiting xy") while (not self.control.check_xy(0.15, 0.15)): self.rate.sleep() self.control.publish_data("Waiting yaw") while (not self.control.check_yaw(0.15)): self.rate.sleep() self.control.publish_data("Move forward and searching 2.5 meter") self.control.relative_xy(2.5, 0) # Start path move forward and searching count = 0 while (not self.control.check_xy(0.1, 0.1)): self.rate.sleep() self.vision_path.call_data() self.vision_path.echo_data() if (self.vision_path.num_point != 0): count += 1 else: count = 0 if (count == 2): self.control.publish_data( "I found path 2 round at here reset now") self.control.reset_state() self.control.publish_data("Sleep 2 second wait to reset state") rospy.sleep(2) break # End part to search if (count == 2): self.control.publish_data("I start path by ever found path") else: self.control.publish_data("I start path by never found path") result = self.mission_path.find_path() if (result): self.control.publish_data("Congratulation we know you pass path") else: self.control.publish_data("It bad you failure mission path") self.control.absolute_yaw( zeabus_math.bound_radian(collect_yaw - (math.pi / 2))) # End part of play all mission self.control.publish_data("Finish all strategy mission") self.control.deactivate(["x", "y", "z", "roll", "pitch", "yaw"]) def callback_service(self, request): if (request.data == True): # Want to play if (not self.current_play): self.current_play = True else: rospy.logfatal("Warning node alredy play you can't do that") else: rospy.loginfo("Service call to code node") rospy.signal_shutdown("Service call to close or stop mission") return SendBoolResponse()
from gate import Gate from reportee import Police, G4S if __name__ == '__main__': gate = Gate() gate.add_reportee(G4S()) gate.add_reportee(Police()) gate.pass_gate() # alarm gate.insert_coin() # avaneb gate.insert_coin() # tänab gate.pass_gate() # sulgub