def display(self): g.screen.fill(utils.WHITE) if g.toc_showing: g.screen.blit(self.toc.surf, (g.offset, 0)) buttons.draw() return g.screen.blit(self.layout.surf, (g.offset, 0)) if g.jig: self.jig.draw() if g.mouse_locn: x, y = pygame.mouse.get_pos() m = '(' + str(x) + ',' + str(y) + ')' cxy = (g.sx(29), g.sy(1.2)) utils.message(g.screen, g.font1, m, cxy, 5) if g.colors: g.screen.blit(g.colors_img, g.colors_xy) if utils.mouse_on_img(g.colors_img, g.colors_xy): c = g.screen.get_at(pygame.mouse.get_pos()) r, g1, b = '0', '0', '0' if c[0] > 200: r = '255' if c[1] > 200: g1 = '255' if c[2] > 200: b = '255' m = '(' + r + ',' + g1 + ',' + b + ')' cxy = (g.sx(5.3), g.sy(19.5)) utils.message(g.screen, g.font1, m, cxy, 5) if self.layout.movie != None: self.layout.movie.draw() buttons.on(['fd', 'back']) if g.page == 1: buttons.off('back') elif g.page == g.last_page: buttons.off('fd') buttons.draw() if g.rect_on: pygame.draw.rect(g.screen, utils.GREEN, g.rect) if self.popup != None: surf, x, y = self.popup g.screen.blit(surf, (x, y))
def main(): from docopt import docopt args = docopt(__doc__, version=__version__) args_exclude = args.get('--exclude') exclude = [] if args_exclude: exclude = [os.path.realpath(e) for e in args_exclude] version = args.get('--go-version') if args.get('--go-version') is not None else default_version() gopath = find_for_gopath(substitute(args.get('--basedir')), exclude) # we should have _something_ in the GOPATH... if not gopath: gopath = [ os.getcwd() ] quiet = args.get('--quiet') ensure_paths(GOENV_CACHE_HOME, GOENV_CONFIG_HOME, GOLANG_DISTRIBUTIONS_DIR, quiet=quiet) platforms = { "linux": Linux, "darwin": MacOSX, "freebsd": FreeBSD } for key in platforms: if sys.platform.startswith(key): impl = platforms.get(key) break else: message("Your platform '{}' is not supported, sorry!".format(sys.platform), sys.stderr, quiet) install_only = args.get('--install-only') impl(version, *gopath, install_only=install_only, quiet=quiet).go()
def main(): while True: ms=pygame.time.get_ticks() for event in pygame.event.get(): if event.type==QUIT: utils.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # allow any button - left, right or middle glow_off() if click(): break display(); pygame.display.flip() # no pointer in case button pressed bu=buttons.check() if bu<>'':do_button(bu) elif event.type==KEYDOWN: if event.key==K_ESCAPE: utils.exit() if event.key==K_x: g.version_display=not g.version_display if g.player_n==0 and not buttons.active('green'): buttons.on("back") display() aim.do() aim.glow(); player.glow() if g.version_display: g.message=g.app+' Version '+g.ver g.message+=' '+str(g.w)+' x '+str(g.h) g.message+=' '+str(g.frame_rate)+'fps' utils.message(g.screen,g.font1,g.message) mx,my=pygame.mouse.get_pos() if my>g.pointer.get_height(): g.screen.blit(g.pointer,(mx,my)) pygame.display.flip() g.clock.tick(40) d=pygame.time.get_ticks()-ms; g.frame_rate=int(1000/d)
def __str__(self): #this overwrites the classes default string method, so if you call message(player) this is what will print return (message(self.name, 'cyan', returnFormatted=True) + ' is a Lvl ' + message(self.lvl, 'cyan', returnFormatted=True) + ' ' + message(self.race, 'green', returnFormatted=True) + ' ' + message(self.charType, 'green', returnFormatted=True) + ' with ' + formatHPString(self.hp_current, self.hp_max) + 'HP')
def use_item(self, item): """ Attempts to invoke an item's effects. """ if item is not None and item.useable == True: item.use(self) if item.expendable: self.inventory.remove(item) else: utils.message("Cannot use that.")
def deadCheck(self, target, caster): if target.hp_current <= 0: target.dead = True message(target.name + ' is dead!') caster.lvlUp() if target.retaliates and target.dead == False: message(target.name + ' retaliates!') target.attack(caster)
def install_uwsgi(): message("Installing uWSGI ...", color=yellow) # requirements for uWSGI sudo("yum -y install gcc-c++") sudo("yum -y install python-devel") sudo("yum -y install libxml2-python libxml2-devel") # install uWSGI sudo("pip install uwsgi")
def use(self, mob): if self.effect.has_key("healflat"): mob.hp = mob.hp + self.effect["healflat"] if mob.hp > mob.maxhp: mob.hp = mob.maxhp if mob == globals.player: utils.message("Healed " + str(self.effect["healflat"]) + "hp!")
def activate(self, target, caster): #here we are overwriting the base activate method. if target == None: target = caster total_heal_ammount = self.heal_ammount + caster.wisdom target.takeHealing(total_heal_ammount) caster.ap_current -= self.ap_cost message(caster.name + ' casts Greater Heal on ' + target.name + ', healing for ' + str(total_heal_ammount))
def activate(self, target, caster): #all abilties should be initiated by the activate method, which should always take 'target' and 'caster' as its main inputs. target can be none if it is self casted, but must be included in the method #this can be overwritten by making a new activate method on child abilility classes totalDamage = caster.intelligence + self.damage target.takeDamage(totalDamage) caster.ap_current -= self.ap_cost message(caster.name + ' casts fireball! It deals ' + str(totalDamage) + ' to ' + target.name) #all activate methods where the target is taking damage should include deadcheck() at the end self.deadCheck(target, caster)
def heal(self): healAmmount = self.hp_max / 2 if self.hp_current + healAmmount >= self.hp_max: self.hp_current = self.hp_max message(self.name + ' heals to full health, ' + str(self.hp_max), 'magenta') else: self.hp_current += healAmmount message( self.name + ' heals for ' + str(healAmmount) + ' leaving them at ' + str(self.hp_current), 'magenta')
def train(): # Turn on training mode which enables dropout. if args.model == 'QRNN': model.reset() total_loss = 0 start_time = time.time() ntokens = len(corpus.dictionary) hidden = model.init_hidden(args.batch_size) batch, i = 0, 0 while i < train_data.size(0) - 1 - 1: bptt = args.bptt if np.random.random() < 0.95 else args.bptt / 2. # Prevent excessively small or negative sequence lengths seq_len = max(5, int(np.random.normal(bptt, 5))) # There's a very small chance that it could select a very long sequence length resulting in OOM # seq_len = min(seq_len, args.bptt + 10) lr2 = optimizer.param_groups[0]['lr'] optimizer.param_groups[0]['lr'] = lr2 * seq_len / args.bptt model.train() data, targets = get_batch(train_data, i, args, seq_len=seq_len) # Starting each batch, we detach the hidden state from how it was previously produced. # If we didn't, the model would try backpropagating all the way to start of the dataset. hidden = repackage_hidden(hidden) optimizer.zero_grad() output, hidden, rnn_hs, dropped_rnn_hs = model(data, hidden, return_h=True) raw_loss = criterion(output.view(-1, ntokens), targets) loss = raw_loss # Activiation Regularization loss = loss + sum(args.alpha * dropped_rnn_h.pow(2).mean() for dropped_rnn_h in dropped_rnn_hs[-1:]) # Temporal Activation Regularization (slowness) loss = loss + sum(args.beta * (rnn_h[1:] - rnn_h[:-1]).pow(2).mean() for rnn_h in rnn_hs[-1:]) loss.backward() # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. torch.nn.utils.clip_grad_norm(model.parameters(), args.clip) optimizer.step() total_loss += raw_loss.data optimizer.param_groups[0]['lr'] = lr2 if batch % args.log_interval == 0 and batch > 0: cur_loss = total_loss[0] / args.log_interval elapsed = time.time() - start_time message('| epoch {:3d} | {:5d}/{:5d} batches | lr {:02.2f} | ms/batch {:5.2f} | ' 'loss {:5.2f} | ppl {:8.2f}'.format( epoch, batch, len(train_data) // args.bptt, optimizer.param_groups[0]['lr'], elapsed * 1000 / args.log_interval, cur_loss, math.exp(cur_loss))) total_loss = 0 start_time = time.time() ### batch += 1 i += seq_len
def shutdown(self): ''' Shut down the virtual machine.''' if not self.is_running(): message('Virtual machine ({0}) is not currently running !!'.format(self.name), WARNING) return message('Stopping virtual machine ({0})'.format(self.name)) with settings(host_string=self.host): run('virsh shutdown {0}'.format(self.name), shell=False, pty=False) while self.is_running(): sleep(5)
def createFile(self): (name, rc) = QtGui.QInputDialog.getText(self, "Create File", "File Name") if rc: item = self.currentItem() path = item.data(0, DirectoryRole).toString() try: f = open(os.path.join(path, name), "w") f.write("\n") f.close() self.update() except IOError: utils.message("Failed to create file")
def upload_release(): message("Creating an archive from the current Git master branch and uploading it ..", color=yellow) local("git archive --format=tar master | gzip > release.tar.gz") sudo( "mkdir -p /srv/%(project_name)s/releases/%(release)s && chown -R ec2-user:ec2-user /srv/%(project_name)s" % env ) put("release.tar.gz" % env, "/srv/%(project_name)s/releases/%(release)s.tar.gz" % env) run( "cd /srv/%(project_name)s/releases/%(release)s && tar zxf /srv/%(project_name)s/releases/%(release)s.tar.gz" % env ) run("rm /srv/%(project_name)s/releases/%(release)s.tar.gz" % env)
def build(): """" Builds the complete environment and deployes the application into it. """ message("Starting build process ...", color=green) update() install() virtualenv() upload_release() message("Your build is complete!", color=green)
def drop_item(self, item): """ Attempts to drop an item from the inventory. """ if item is not None: item.x = self.x item.y = self.y self.inventory.remove(item) globals.things.append(item) utils.message(item.name.capitalize() + " dropped on the ground.") return True else: if self == globals.player: utils.message("Error - drop_item failed", "red") return False
def start(self): ''' Boot the virtual machine.''' if self.is_running(): message('Virtual machine ({0}) is already running'.format(self.name), WARNING) return message('Starting virtual machine ({0})'.format(self.name)) with settings(host_string=self.host): run('virsh start {0}'.format(self.name), shell=False, pty=False) # TODO: better method to ensure that machine has booted sleep(15)
def createFolder(self): (name, rc) = QtGui.QInputDialog.getText(self, "Create Folder", "Folder Name") if rc: item = self.currentItem() path = item.data(0, DirectoryRole).toString() try: path = os.path.join(path, name) os.mkdir(path) self.update() return path except OSError: utils.message("Failed to create folder") return ""
def remove_changelogs(collection, id_field_name='_id', changelog_field_name='changelog'): for document in collection.find({}): if changelog_field_name in document: collection.update_one({id_field_name: document[id_field_name]}, {'$unset': { changelog_field_name: 1, }}) utils.message('Removed field {} in document id {}'.format( changelog_field_name, document[id_field_name])) else: utils.message('Unchanged document id {}'.format( document[id_field_name]))
def pick_up_item(self, item): """ Attempts to pick up an item from the ground. If there are multiple items, should bring up a list. If there is no item, nothing happens and displays an error. """ if item is not None: self.inventory.append(item) globals.things.remove(item) utils.message(item.name + " picked up and added to " + "inventory.") return True else: if self == globals.player: utils.message("Error - pick_up_item failed", "red") return False
def equip_item(self, item): """ Attempts to wear a piece of equipment. Will remove any items already equipped. """ if item.slot == "chest": if self.slots["chest"] is not None: self.equipment.remove(self.slots["chest"]) self.inventory.append(self.slots["chest"]) utils.message("Removing " + self.slots["chest"].name + " from chest.") if self.slots["chest"] == None: self.inventory.remove(item) self.equipment.append(item) self.slots["chest"] = item utils.message("Equipped " + self.slots["chest"].name + " on chest.")
def load_reference(self, ref_file): seqs = [] with open(ref_file, 'r') as f: for line in f: if line.startswith(">"): if seqs: self.ref_dict.setdefault(chrom, "".join(seqs)) seqs = [] chrom = line.split()[0][1:] else: seqs.append(line.strip()) self.ref_dict.setdefault(chrom, "".join(seqs)) # last chr utils.message("Reference loaded.")
def createFolder(self): (name, rc) = QtGui.QInputDialog.getText(self, "Create Folder", "Folder Name") if rc: item = self.currentItem() path = item.data(0, DirectoryRole).toString() try: path = os.path.join(path, name) os.mkdir(path) self.update() return path except OSError: utils.message("Failed to create folder") return ''
def install_mysql(): message("Installing & configuring MySQL ...", color=yellow) password = make_password(10) sudo("yum -y install mysql mysql-server MySQL-python") sudo("service mysqld start") sudo("chkconfig mysqld on") # Scure the mysql installation # http://dev.mysql.com/doc/refman/5.0/en/default-privileges.html run("mysqladmin -u root password " + password) run("mysql -uroot -p" + password + " -e \"DROP USER ''@'localhost';\"") run("mysql -uroot -p" + password + ' -e "DROP DATABASE test;"') run("mysql -uroot -p" + password + ' -e "FLUSH PRIVILEGES;"')
def update_timestamps(collection, id_field_name='_id', timestamp_field_name='timestamp'): for document in collection.find({}): ts = utils.timestamp_normalize(document[timestamp_field_name]) if ts != document[timestamp_field_name]: collection.update_one({id_field_name: document[id_field_name]}, {'$set': { 'timestamp': ts, }}) utils.message('Updated: id {}, old {}, new {}'.format( document[id_field_name], document['timestamp'], ts)) else: utils.message('Unchanged document id {}, {}'.format( document[id_field_name], document['timestamp']))
def __call__(self, request, *args, **kwargs): ws = web.WebSocketResponse() ws.start(request) ws.send_str(message(mtp="HELLO")) stop = False while not stop: try: msgs = yield from first_completed(ws=ws.receive(), send=self.message_queue.get()) except RuntimeError as e: print(e) break for name, msg in msgs: if name == "ws": if msg.tp == aiohttp.MsgType.close: print("Websocket closed") break elif msg.tp == aiohttp.MsgType.error: print("Websocket error:") break else: if msg.data is None: print(msg) else: self.parse_message(msg.data) elif name == "send": x = ws.send_str(msg) pass print("Cancelling tasks") for command in self.running_commands: try: command.cancel() except: pass return ws
def __init__(self): _cmdline_ = "heap_arenas" #使用方式 价格usage函数 _syntax_ = "%s" % _cmdline_ self.msg = message() super(self.__class__, self).__init__(_syntax_, gdb.COMMAND_USER) return
def run(self, address=None, interval=1.0, **kwargs): device = muse_manager.devices[address] msg = dict(mtp="muse_status", address=address, status="connecting", ) yield from device.connected.wait() print ("Start streaming") time_start = time.time() last_indices = device.get_indices() while not self.cancelled: yield from sleep(0.2) msg = dict(mtp="muse_stream", address=address) for key,ts in device.loggers.items(): last_index = last_indices[key] times = ts.times[last_index:] values = ts.values[last_index:] if len(values)>0: msg[key] = [times, values] last_indices = device.get_indices() json = message(**msg) yield from self.websocket.send(json)
def __init__(self): _cmdline_ = "heap_bins_large" _syntax_ = "%s" % _cmdline_ self.msg = message() super(self.__class__, self).__init__(_syntax_, gdb.COMMAND_USER) return
def run(self, address=None, interval=1.0, **kwargs): if address not in mindwave_manager.devices: self.websocket.send(msg="mindwave_error", error_name="address not connected", description="No device with this address connected.") return device = mindwave_manager.devices[address] last_index = 0 last_indices = device.get_indices() print ("Mindwave Streaming") while True: yield from device.connected.wait() yield from sleep(interval) msg = dict(mtp="mindwave_stream", address=address) for name in value_names: ts = getattr(device, name) last_index = last_indices[name] values = ts.values[last_index:] times = ts.times[last_index:] #print (name, " ", len(values), " ", len(times)) msg[name] = [times, values] yield from self.websocket.send(message(**msg)) last_indices = device.get_indices()
def api_predict(): """ Renvoie un texte decrivant le résultat de la prédiction """ assert isinstance( request.json['title'], str), "The title of the article is not defined or not string" assert isinstance( request.json['text'], str), "The text of the article is not defined or not string" title = request.json['title'] date = request.json['date'] text = request.json['text'] subject = request.json['subject'] # Create dataframe data = formate_dataset( pd.DataFrame(data={ "title": [title], "date": [date], "text": [text], "subject": [subject] })) # Return prediction return jsonify(message(int(prediction(data))))
def attackTurn(self, game_state): monsters = sorted(game_state['monsters'], key=lambda x: x.hp_current) message('These monsters are currently in the room:', 'green') x = 0 for monster in monsters: messageDirect(str(x) + ': ' + str(monster)) x += 1 monster_id = stringPrompt('Which would you like to fight?', 'number next to monster') try: monster_id = int(monster_id) if monster_id >= x or monster_id < 0: raise Exception() except: message('You must choose a valid monster.', 'red') self.getTurnAction(game_state) self.attack(monsters[monster_id])
def __init__(self): # Set background self.addControl(xbmcgui.ControlImage(0, 0, self.w, self.h, utils.background)) self.addControl(xbmcgui.ControlImage(self.shift_left, self.shift_top, self.logo_size, self.logo_size, utils.logo)) self.before = 3 self.after = 3 if utils.username == '': utils.message( "Setting a user name will assist you to defer between users. A user name is a free text that will help you to save your cradentials for next time") self.calCon = calendarutils.CalendarConnection() self.lastSelected = None self.view_controls = [] self.control_to_data = {} self.date_center = datetime.date.today() self.view = utils.default_view print 'wwwwwwwwwwwwwwwwwwwwwwwwwwwwww'+self.view self.load()
def check_epsg(conn): if not conn: return cursor = conn.cursor() try: cursor.execute("SELECT srid FROM spatial_ref_sys WHERE srid = 5514") except StandardError as e: sys.exit("PostGIS doesn't seems to be activated. %s" % e) epsg_exists = bool(cursor.fetchall()) if not epsg_exists: stmt = """INSERT INTO spatial_ref_sys (srid, auth_name, auth_srid, proj4text, srtext) VALUES ( 5514, 'EPSG', 5514, '+proj=krovak +lat_0=49.5 +lon_0=24.83333333333333 +alpha=30.28813972222222 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +units=m +no_defs ', 'PROJCS["S-JTSK / Krovak East North",GEOGCS["S-JTSK",DATUM["System_Jednotne_Trigonometricke_Site_Katastralni",SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],TOWGS84[570.8,85.7,462.8,4.998,1.587,5.261,3.56],AUTHORITY["EPSG","6156"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4156"]],PROJECTION["Krovak"],PARAMETER["latitude_of_center",49.5],PARAMETER["longitude_of_center",24.83333333333333],PARAMETER["azimuth",30.28813972222222],PARAMETER["pseudo_standard_parallel_1",78.5],PARAMETER["scale_factor",0.9999],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",EAST],AXIS["Y",NORTH],AUTHORITY["EPSG","5514"]]')""" cursor.execute(stmt) conn.commit() message("EPSG 5514 defined in DB") cursor.close()
def abilityTurn(self, game_state): #get the player to select an ability message(self.name + ' currently has these abilities:') x = 0 for ability in self.abilities: messageDirect(str(x) + ': ' + str(ability.name)) x += 1 ability_id = stringPrompt('Which ability would you like to use?', 'number next to ability') try: ability_id = int(ability_id) if ability_id >= x or ability_id < 0: raise Exception() except: message('You must choose a valid ability.', 'red') self.getTurnAction(game_state) if self.abilities[ability_id].ap_cost > self.ap_current: message('Not enough AP to use this ability!', 'red') self.getTurnAction(game_state) #if the ability requires a target, select one if self.abilities[ability_id].target_required: monsters = sorted(game_state['monsters'], key=lambda x: x.hp_current) message('These monsters are currently in the room:', 'green') x = 0 for monster in monsters: messageDirect(str(x) + ': ' + str(monster)) x += 1 monster_id = stringPrompt('Which would you like to fight?', 'number next to monster') try: monster_id = int(monster_id) if monster_id >= x or monster_id < 0: raise Exception() except: message('You must choose a valid monster.', 'red') self.getTurnAction(game_state) self.abilities[ability_id].activate(monsters[monster_id], self) else: self.abilities[ability_id].activate(None, self)
def run_script(self, script): ''' Execute commands on virtual machines.''' for vm in self.vms: # Forward port and start virtual machine port = Port() port.forward(self, vm) vm.start() vm_type = vm.type cmds = script.machines[vm_type] message('Running script on {0} (type={1})'.format(vm.name, vm_type)) for cmd in cmds: message('cmd={0}'.format(cmd), 1) with settings(host_string='{0}@localhost:{1}'.format(vm.user, vm.port)): run(cmd) # Shut down the virtual machine and close port vm.shutdown() port.close()
def main(): while True: ms = pygame.time.get_ticks() for event in pygame.event.get(): # check for app close if event.type == QUIT: utils.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # allow any button - left, right or middle button = event.button display() pygame.display.flip() # no pointer in case button pressed anim.running = False if angler.click(): player.reset() break if shape_click(button): break if target_click(button): break if repeat_click(button): break if g.slider.mouse(): if g.level == 6: player.fast_start() break bu = buttons.check() if bu <> '': do_button(bu) elif event.type == KEYDOWN: anim.running = False if event.key == K_ESCAPE: utils.exit() if event.key == K_x: g.version_display = not g.version_display display() if not g.checked: check() animation() if g.version_display: g.message = g.app + ' Version ' + g.ver g.message += ' ' + str(g.w) + ' x ' + str(g.h) g.message += ' ' + str(g.frame_rate) + 'fps' utils.message(g.screen, g.font1, g.message) mx, my = pygame.mouse.get_pos() if my > g.pointer.get_height(): g.screen.blit(g.pointer, (mx, my)) pygame.display.flip() if not player.running and not aim.running: g.clock.tick(40) # 40 frames per second d = pygame.time.get_ticks() - ms g.frame_rate = int(1000 / d)
def lvlUp(self): self.lvl += 1 self.hp_max += (5 + self.constitution) self.hp_current = self.hp_max self.ap_max += (1 + self.wisdom) self.ap_current = self.ap_max self.strength += 1 self.intelligence += 1 self.constitution += 1 self.dexterity += 1 self.wisdom += 1 self.charisma += 1 message(self.name + ' lvls up!') message(self.name + ' is now lvl ' + str(self.lvl)) message('Stats Gained:', 'green') message( 'Strength: 1\nIntelligence: 1\nConstitution: 1\nDexterity: 1\nWisdom: 1\nCharisma: 1', 'green') message( 'Gain ' + str(5 + self.constitution) + 'HP and ' + str(1 + self.intelligence) + 'AP', 'green')
def move_or_interact(self, dx, dy): """ Allows for movement for non-player Mobiles """ X = self.x + dx Y = self.y + dy if globals.map[X][Y].is_passable: target = None for mobile in globals.mobiles: if mobile.x == X and mobile.y == Y: target = mobile if target is not None and target != self: self.attack(target) self.calculate_fov() return True else: self.x, self.y = X, Y self.calculate_fov() return True else: if self == globals.player: utils.message("Oof! You've hit a wall!", "calypso") return False
def run(self, **kwargs): self.device_events = asyncio.Queue() known_addresses = [] print("Looking for devices") while 1: try: bd = AsyncDiscoverer() bd.queue = self.device_events bd.find_devices(lookup_names=False, duration=5) except bluetooth.BluetoothError: # An exception at this stage is a very bad sign. Probably no BT adapter # is available. print("Error encountered while scanning for bluetooth devices.") for i in range(3): try: bd.process_event() except bluetooth._bluetooth.error as e: print(e) pass except TypeError as e: print(e) if bd.done: break try: event = self.device_events.get_nowait() except asyncio.QueueEmpty: yield from sleep(0.1) continue address = event[0] if address not in known_addresses: known_addresses.append(address) name = bluetooth.lookup_name(address, timeout=10) print("Bluetooth device:", address, name) yield from self.websocket.send(message(msg="bluetooth_device_discovered", address=address, name=name)) print("Bluetooth Discovery finished.") yield from self.websocket.send(message(msg="bluetooth_discovery_finished"))
def build_and_fetch(self, project, stage): ''' Build a project and fetch the resulting programs, packages, etc.''' for vm in self.vms: # Forward port and start virtual machine port = Port() port.forward(self, vm) vm.start() # Get updates from code repository project.pull(vm) # Create build directory message('Creating build directory {0}'.format(project.paths.build)) vm.run('mkdir {0}'.format(project.paths.build)) # Build project and fetch packages project.build(vm) project.fetch(vm) # Shut down the virtual machine and close port vm.shutdown() port.close()
def death(self): """ Handles what happens when a mobile dies. """ if self == globals.player: # If the player dies, the game is over. globals.player.dead = True else: # If a non-player mobile dies, it leaves a corpse item. globals.mobiles.remove(self) utils.message("%s is dead, long live %s!" % (self.name, self.name), "burnsand") self.description = "probably rotting corpse" corpse = Item( "%", self.color, self.x, self.y, "%s corpse" % self.name, self.weight, self.description, self.size, "inventory", ["edible", "rots"], ) globals.things.append(corpse) del self
def attack(self, target): ownDamage = self.calculateDamage() target.takeDamage(ownDamage) message(self.name + ' attacks ' + target.name + ' dealing ' + str(ownDamage) + ' damage!') if target.hp_current <= 0: target.dead = True message(target.name + ' is dead!') self.lvlUp() if target.retaliates and target.dead == False: message(target.name + ' retaliates!') target.attack(self)
def attack(self, target): """ Attempts to deal damage to another mobile. """ attack_roll = random.randint(0, 8) + self.brawn + self.attack_bonus miss_chance = target.dodge + target.defense_bonus if attack_roll > miss_chance and target == globals.player: damage_roll = random.randint(0, 2) + self.brawn target.hp -= damage_roll utils.message("%s hits you for %d" % (self.name, damage_roll), "burnsand") elif attack_roll > miss_chance and self == globals.player: damage_roll = random.randint(0, 2) + self.brawn target.hp -= damage_roll utils.message("You hit %s for %d!" % (target.name, damage_roll), "burnsand") elif attack_roll <= target.dodge: if self == globals.player: utils.message("You attack %s and miss!" % target.name, "burnsand") elif target == globals.player: utils.message("%s attacks you and misses!" % self.name, "burnsand") if target.hp <= 0: target.death() globals.player.calculate_fov()
def pprint_bin(bin_idx): msg = message() arena = GlibcArena("main_arena") fw, bk = arena.bin(bin_idx) msg( colorize( "Found base for bin({:d}): fw={:#x}, bk={:#x}".format( bin_idx, fw, bk), "purple")) if bk == fw and ((arena.get_main_arena_addr() & ~0xFFFF) == (bk & ~0xFFFF)): #print("Empty") msg(colorize("Empty", "purple")) return m = "" head = GlibcChunk(bk + 2 * arena.get_arch()).get_fwd_ptr() while fw != head: chunk = GlibcChunk(fw + 2 * arena.get_arch()) m += "{:s} {:s} ".format(right_arrow, str(chunk)) fw = chunk.get_fwd_ptr() msg(colorize("{0}".format(m), "purple")) return
def pprint(self): """ :param self: :return: """ msg = "" if not self.is_used(): msg += "Chunk (free): %#x" % self.chunk_start_addr msg += "\n" msg += self.str_as_freeed() else: msg += "Chunk (used): %#x" % self.chunk_start_addr msg += "\n" msg += self.str_as_alloced() #gdb.write(msg+"\n") #gdb.flush() msg_print = message() msg_print(colorize("{0}".format(msg), "purple")) return
def run(self, address=None, interval=1.0, **kwargs): if address not in bitalino_manager.devices: self.websocket.send(msg="bitalino_error", error_name="address not connected", description="No device with this address connected.") return device = bitalino_manager.devices[address] last_index = device.sample_count print ("Bitalino Streaming") while True: yield from device.connected.wait() yield from sleep(interval) msg = dict(mtp="bitalino_stream", address=address) for i, channel in enumerate(device.analog_channels): ts = device.channel_samples[i] values = ts.values[last_index:] times = ts.times[last_index:] msg["analog_%i" % channel ] = [times, values] s = message(**msg) yield from self.websocket.send(s) last_index = device.sample_count
def getTurnAction(self, game_state): message( 'It is ' + self.name + 's turn, what would you like to do?\n1: Attack\n2: Heal\n3: Inspect Enemies - NOT IMPLEMENTED\n4: Use an ability' ) message(self.name + ' currently has ' + formatHPString(self.hp_current, self.hp_max) + 'HP') turnAction = stringPrompt('What action would you like to take?', 'number next to action') if turnAction not in ['1', '2', '3', '4']: self.getTurnAction(game_state) elif turnAction == '1': self.attackTurn(game_state) elif turnAction == '2': self.heal() elif turnAction == '3': message('Inspecting is not implemented yet!', 'red') self.getTurnAction(game_state) elif turnAction == '4': self.abilityTurn(game_state)
def run(m_name, m_id, epsilon, delay, intervention_file, monitor_file, out_file, error_file, status_file, my_counter_file, global_counter_file, end_date, lock_local, seed): global lock lock = lock_local random.seed(seed) if os.path.exists(out_file): utils.message('Restarting ' + m_name + ' experiment...', out_file) else: utils.message('Starting new ' + m_name + ' experiment...', out_file) pid = os.getpid() utils.message(m_name + ' PID: ' + str(pid), out_file) exprmnt = Experiment(m_name, m_id, epsilon, delay, intervention_file, monitor_file, out_file, error_file, status_file, my_counter_file, global_counter_file, end_date) exprmnt.run()
def main(debug=None): args = docopt(__doc__, argv=debug, options_first=False) check_program_exists("primer3_core") check_program_exists("blastn") # Ensure user has specified a reference. if args["--ref"] is None: exit(message("Must specify a reference with --ref", color="red")) v = primer_vcf(args["<vcf>"], reference=args["--ref"], use_template=args['--template'], polymorphic=args["--polymorphic"]) v.enzymes = args['--enzymes'] v.nprimers = int(args['--nprimers']) # Region if args["--region"]: v.region = args["--region"] else: v.region = None # Samples if args["--samples"]: if args["--samples"] == "ALL": v.output_samples = v.samples else: v.output_samples = args["--samples"].split(",") for sample in v.output_samples: if sample not in v.samples + [ "REF", "ALT", ]: exit(message(sample + " not found in VCF", "red")) v.box_variants = args["--box-variants"] # Needs to be implemented. #v.amplicon_size = args["--size"] # Check for std. input if args["template"]: v.mode = "template" if '-' in args['--size']: try: v.region_size = int(args['--size'].split("-")[0]) message( "Warning: region size set to {s}".format(s=v.region_size)) except: exit(message("Error: Invalid --size")) elif str.isdigit(args['--size']): v.region_size = int(args['--size']) v.amplicon_lower = 0 v.amplicon_upper = 0 elif args["indel"]: message( "--size ignored; size is set dynamically when genotyping indels.") v.mode = "indel" elif args["snip"]: message("--size ignored; Set to 600-800 bp.") v.mode = "snip" v.amplicon_lower = 600 v.amplicon_upper = 800 v.region_size = 500 #x2=1000 elif args["sanger"]: v.mode = "sanger" if args['--size'] is None: size = "600-800" message("Warning: --size set to 600-800 for sanger sequencing.") elif str.isdigit(args['--size']): exit( message( "Error: You must specify a amplicon --size range for Sanger; e.g. 600-800." )) else: size = args['--size'] if "-" in size: try: v.amplicon_lower = int(size.split("-")[0]) v.amplicon_upper = int(size.split("-")[1]) except: exit(message("Error: Invalid --size")) else: v.amplicon_lower = 600 v.amplicon_upper = 800 v.region_size = (v.amplicon_upper // 2) + 100 if (v.amplicon_lower < 300 or 800 < v.amplicon_upper): message( "Warning: --size range should (probably) be between 300-800 for sanger sequencing." ) for variant in v.variant_iterator(): variant.out()
def test_real_article_message(): """ test de la fonction message (prédiction = 0) """ assert utils.message(0) == "This is a fake"
def test_fake_article_message(): """ test de la fonction message (prédiction = 1) """ assert utils.message(1) == "This is a real news article"
default=1.2e-6, help='weight decay applied to all weights') parser.add_argument('--log-file', type=str, default='', help='path to save the log') args = parser.parse_args() set_log_file(args.log_file) # Set the random seed manually for reproducibility. torch.manual_seed(args.seed) if torch.cuda.is_available(): if not args.cuda: message( "WARNING: You have a CUDA device, so you should probably run with --cuda" ) else: torch.cuda.manual_seed(args.seed) ############################################################################### # Load data ############################################################################### corpus = data.Corpus(args.data) eval_batch_size = 10 test_batch_size = 1 train_data = batchify(corpus.train, args.batch_size, args) val_data = batchify(corpus.valid, eval_batch_size, args) test_data = batchify(corpus.test, test_batch_size, args)
def message(self, msg, file=sys.stdout, override=False): return message(msg, file, self.quiet(), override)
initialFF['geometry']['physical']['Nx'], initialFF['geometry']['physical']['Ny'], initialFF['geometry']['physical']['Nz'])) for u, line in enumerate(meanFile): values = line.split() nx = int(values[0]) ny = int(values[1]) nz = int(values[2]) nd = int(values[3]) vel = float(values[4]) if vel <= 1e-8: vel = 0.0 meanVec[nd, nx, ny, nz] = vel ut.message('Closing the physical ASCII file') meanFile.close() data_each_NS = {} for k in files: if whatWereLookingForIs in str(k) and correctFileType in str(k): folderName = k[0:-3]
def check_files(direc): """ Check to see if the ASCII and geometry files exist. We are also going to see if the files are for physical or spectral solutions. If both exist, we can use both. Otherwise we will only use the one present, this presents different code paths to take later on in the code when we have to project the calculated resolvent modes onto the solution. If niether exist the function and the whole process will terminate. INPUTS: direc: the directory where the solution files *should* exist OUTPUTS: a, b: names of the solution files with extensions included a - geometry file b - ascii file with velocity data """ ut.printSectionHeader() ut.printSectionTitle('Checking the ASCII and GEOM files') ut.message('The working directory is: ' + direc) ut.message('Checking to see if the necassary files exist in directory...') # These are strings which are used to check if the necassary files exist in # the directory. If at the end of the check these strings remain unchanged # the files DO NOT exist. a = 'geo' b = 'asc' c = 'spec.ge' d = 'spec.as' files = [fi for fi in os.listdir(direc) if os.path.isfile(os.path.join(direc,fi))] # Now we loop through the files in the directory to find which ones exist. for fi in files: if a in str(fi) and c not in str(fi): a = str(fi) # physical geometry file if c in str(fi): c = str(fi) # spectral geometry file if b in str(fi) and d not in str(fi): b = str(fi) # physical ascii file if d in str(fi): d = str(fi) # spectral ascii file files_in_direc = {} physical = False spectral = False files_in_direc['physical'] = physical files_in_direc['spectral'] = spectral missing_p_geo, missing_p_asc, missing_s_geo, missing_s_asc = '', '', '', '' # Check to see if there are BOTH physical files (ASCII and GEO) if a is 'geo' and b is 'asc': ut.message('MISSING: Physical ASCII and geometry files.') elif a is 'geo' or b is 'asc': # if not, then point out which one is missing...DONT RAISE ERRORS...yet if a is 'geo': ut.message('MISSING: Could not find physical geometry file') missing_p_geo = '\nphysical geometry file' if b is 'asc': ut.message('MISSING: Could not find physical ASCII file') missing_p_asc = '\nphysical ascii file' else: physical = True files_in_direc['physical'] = physical files_in_direc['phy_geo'] = a files_in_direc['phy_asc'] = b # We carry out the same check for the spectral files. if c is 'spec.ge' and d is 'spec.as': ut.message('MISSING: Spectral geometry and ASCII files are not in directory') elif c is 'spec.ge' or d is 'spec.as': # if not, then point out which one is missing...DONT RAISE ERRORS...yet if c is 'spec.ge': ut.message('MISSING: Could not find spectral geometry file') missing_s_geo = '\nspectral geometry file' if d is 'spec.as': ut.message('MISSING: Could not find spectral ASCII file') missing_s_asc = '\nspectral ascii file' else: spectral = True files_in_direc['spectral'] = spectral files_in_direc['spc_geo'] = c files_in_direc['spc_asc'] = d if spectral == True and physical == True: ut.message('We have both physical and spectral files.') elif spectral == False and physical == True: ut.message('We only have PHYSICAL') elif spectral == True and physical == False: ut.message('We only have SPECTRAL') else: # We are missing some files... errmsg = 'Missing the following files:' + missing_p_asc + missing_p_geo + missing_s_asc + missing_s_geo + '\n\nTerminating...' ut.error(errmsg) return files_in_direc
def read_construct_flow_field(direc, dict_files, dict_geometry): """ Construct a dictionary with the contents of the ASCII files split into relevant physical/spectral keys. INPUTS: direc: the directory where the solution files are dict_files: a dictionary containing the file names of the ascii files dict_geometry: a dictionary of the geometrical variables OUTPUTS: dict_flowField: a dictionary of the flow field stored in physical and spectral states. The physical flow field is stored as a 4D array: - (i, nx, ny, nz) The spectral flow field is stored as a 4D array: - (i, kx, ny, kz) """ dict_flowField = {} dict_flowField['is_physical'] = False dict_flowField['is_spectral'] = False if dict_files['physical'] == True: dict_flowField['is_physical'] = True # READ ut.printSectionHeader() ut.printSectionTitle('Reading physical ASCII file') f = ut.openFile(direc + '/' + dict_files['phy_asc']) # CONSTRUCT ut.message('Creating the flow field vector') # Create an empty 4D array to store the velocity data U = np.zeros((dict_geometry['physical']['Nd'], dict_geometry['physical']['Nx'], dict_geometry['physical']['Ny'], dict_geometry['physical']['Nz'])) for i, line in enumerate(f): values = line.split() nx = int(values[0]) ny = int(values[1]) nz = int(values[2]) nd = int(values[3]) vel = float(values[4]) U[nd, nx, ny, nz] = vel ut.message('Closing the physical ASCII file') f.close() dict_flowField['physical'] = U if dict_files['spectral'] == True: dict_flowField['is_spectral'] = True # READ ut.printSectionTitle('Reading spectral ASCII file') f = ut.openFile(direc + '/' + dict_files['spc_asc']) # CONSTRUCT ut.message('Creating the flow field vector') # Create an empty 4D array to store the velocity data U_hat = np.zeros((dict_geometry['spectral']['Nd'], dict_geometry['spectral']['kx'], dict_geometry['spectral']['Ny'], dict_geometry['spectral']['kz']), dtype=np.complex128) for i, line in enumerate(f): values = line.split() nd = int(values[0]) kx = int(values[1]) kz = int(values[2]) ny = int(values[3]) coeff = complex(values[4]) U_hat[nd, kx, ny, kz] = coeff ut.message('Closing the spectral ASCII file') f.close() dict_flowField['spectral'] = U_hat return dict_flowField
def read_construct_geometry(direc, dict_files): """ Construct a dictionary with all the geometry variables inside it. The top- level keys will be physical/spectral, then each value will contain a further dictionary which will store all the key value pairs found in the geo file. INPUTS: direc: the directory where the solution files are dict_files: a dictionary with all the solution files in it. OUTPUTS: var_geo: a dictionary of the geometrical variables that were contained in the geometry file. The key and value is exactly the same as in the file, i.e. the keys are the same labels as in the file. """ dict_geometry = {} if dict_files['physical'] == True: # READ ut.printSectionHeader() ut.printSectionTitle('Reading the physical geometry file') f = ut.openFile(direc + '/' + dict_files['phy_geo']) ut.message('Constructing geometry dictionary') var_geo = {} # CONSTRUCT for i, line in enumerate(f): values = line.split() if values[1] == '%Nx': var_geo['Nx'] = int(values[0]) elif values[1] == '%Ny': var_geo['Ny'] = int(values[0]) elif values[1] == '%Nz': var_geo['Nz'] = int(values[0]) elif values[1] == '%Nd': var_geo['Nd'] = int(values[0]) elif values[1] == '%Lx': var_geo['Lx'] = float(values[0]) elif values[1] == '%Lz': var_geo['Lz'] = float(values[0]) elif values[1] == '%lx=Lx/(2pi)': var_geo['lx'] = float(values[0]) elif values[1] == '%lz=Lz/(2pi)': var_geo['lz'] = float(values[0]) elif values[1] == '%alpha=2pi/Lx': var_geo['alpha'] = float(values[0]) elif values[1] == '%gamma=2pi/Lz': var_geo['gamma'] = float(values[0]) ut.message('Closing physical geometry file') f.close() var_geo['x'] = np.zeros((var_geo['Nx'])) var_geo['y'] = np.zeros((var_geo['Ny'])) var_geo['z'] = np.zeros((var_geo['Nz'])) for nx in range(0, var_geo['Nx']): var_geo['x'][nx] = nx * var_geo['Lx'] / var_geo['Nx'] for ny in range(0, var_geo['Ny']): var_geo['y'][ny] = math.cos(ny*math.pi/(var_geo['Ny']-1)) for nz in range(0, var_geo['Nz']): var_geo['z'][nz] = nz * var_geo['Lz'] / var_geo['Nz'] dict_geometry['is_physical'] = True dict_geometry['physical'] = var_geo else: dict_geometry['is_physical'] = False if dict_files['spectral'] == True: # READ ut.printSectionTitle('Reading the spectral geometry file') f = ut.openFile(direc + '/' + dict_files['spc_geo']) ut.message('Constructing geometry dictionary') spec_geo = {} # CONSTRUCT for i, line in enumerate(f): values = line.split() if values[1] == '%kx': spec_geo['kx'] = int(values[0]) if values[1] == '%kz': spec_geo['kz'] = int(values[0]) if values[1] == '%y': spec_geo['Ny'] = int(values[0]) if values[1] == '%Nd': spec_geo['Nd'] = int(values[0]) ut.message('Closing spectral geometry file') f.close() dict_geometry['is_spectral'] = True dict_geometry['spectral'] = spec_geo else: dict_geometry['is_spectral'] = False return dict_geometry