def cast(self, data=None): tailored = [] targets = self.find_target(data) for card in targets: if card.hp == card.base_hp: continue elif self.amount == -1: # -1 amount means full restoration card.hp = card.base_hp elif card.hp + self.amount > card.base_hp: card.hp = card.base_hp else: card.hp = card.hp + self.amount tailored.append({ 'hp_restored': { 'uid': card.player.uid, 'uuid': card.uuid, 'hp': card.hp, 'textanim': { 'text': "+{0}".format(self.amount), 'harmful': False, 'onhp': True } } }) logger.info("spell> Restore cast result:{0}".format(tailored)) return tailored
def orf_prodigal_train(self): """Runs PRODIGAL to find open reading frames using a training file from complete genomes references.""" training_file = os.path.join(self.training_file) if os.path.exists(training_file): quality = " -t {} ".format(training_file) filename = os.path.basename(self.input_file) stdout = "2> /dev/null" cmd = "prodigal -q -m -a {trans_file} -i {input_file} -o {output_file} -d {nuc_file} -s {potential_genes} {quality} {stdout}" \ .format( trans_file=os.path.join(self.working_directory, "{}.temp.contig.fsa".format(filename)), input_file=self.input_file, output_file=os.path.join(self.working_directory, "{}.temp.draft".format(filename)), quality=quality, stdout=stdout, nuc_file= os.path.join(self.working_directory, "{}.temp.contigToORF.fsa".format(filename)), potential_genes= os.path.join(self.working_directory, "{}.temp.potentialGenes".format(filename)) ) logger.info(cmd) os.system(cmd) if self.clean == True: os.remove( os.path.join(self.working_directory, "{}.temp.draft".format(filename))) else: logger.error("Missing training file: {} ".format(training_file)) exit()
def cast(self, data=None): from server.models import Card tailored = [] targets = self.find_target(data) for player in targets: for i in range(self.amount): newdbcard = Card.objects.get(pk=self.summon_dbid) vcard = newdbcard.to_virtual(player) slot = player.ground.get_available_slot() if slot > -1: vcard.summoned = True # cannot return to hand etc. player.ground.add(vcard, slot) tailored.append({ 'summoned': { 'uid': player.uid, 'uuid': vcard.uuid, 'key': vcard.key, 'slot': slot } }) simple_logger.debug("{0} summoned {1}".format(player.name, vcard.label)) logger.info("spell> SummonSpell cast result:{0}".format(tailored)) return tailored
def get(self, request): """ List all assets. route /assets return List all assets available for tenant. description This method internally calls method list_assets of AssetsClient class. This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl apiEndpoint : GET /api/assetmanagement/v3/assets of asset management service. apiNote List all assets available for the authenticated user. throws MindsphereError if an error occurs while attempting to invoke the sdk call. """ logger.info("assets/assets invoked.") client = sdk_util.build_sdk_client(self.__class__.__name__, request) if request.method == "GET": try: request_object = data_generator.generate_list_assets_input() asset = client.list_assets(request_object) logger.info("Getting response successfully for getallasset" + json.dumps(asset.to_dict())) except exceptions.MindsphereError as err: logger.error("Getting eeror for getallasset " + err) return HttpResponse( err, content_type="application/json", status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) return HttpResponse( json.dumps(asset.to_dict()), content_type="application/json", status=status.HTTP_200_OK )
def cast(self, data=None): tailored = [] targets = self.find_target(data) for card in targets: card.hp += self.hp if self.hp >= 0: tailored.append({ 'hp_increased': { 'uid': card.player.uid, 'uuid': card.uuid, 'hp': card.hp, 'textanim': { 'text': "+{0}".format(self.hp), 'harmful': False, 'onhp': True } } }) else: tailored.append({ 'hp_decreased': { 'uid': card.player.uid, 'uuid': card.uuid, 'hp': card.hp, 'textanim': { 'text': "-{0}".format(self.hp), 'harmful': True, 'onhp': True } } }) logger.info("spell> Hp cast result:{0}".format(tailored)) return tailored
def register(self, key, card, callback, unregister_callback=None): # logger.info("GameEvents.register key:{0} card:{1}".format(key, card.title)) self.events.append( Event(key, card, callback, unregister_callback=unregister_callback)) logger.info("Events> Registered {0} {1} callback={2}".format( key, card.title, callback))
def build_sdk_client(class_name, request): if TOKEN_CIRCULAR_GROUP[TOKEN_SELECTOR] == TOKEN_CIRCULAR_GROUP[1]: if request.META.get('HTTP_AUTHORIZATION') is None: logger.error( 'To work with technical token,' ' application should receieve authorization header.', request.get_full_path()) raise exceptions.MindsphereError( 'To work with technical token,' ' application should receieve authorization header.', request.get_full_path()) else: credentials = UserToken( authorization=str(request.META.get('HTTP_AUTHORIZATION'))[7::]) logger.info('Using User Token for ' + request.get_full_path()) elif TOKEN_CIRCULAR_GROUP[TOKEN_SELECTOR] == TOKEN_CIRCULAR_GROUP[0]: credentials = AppCredentials() else: logger.error('Unpredicted use case, used token type not available', request.get_full_path()) raise exceptions.MindsphereError( 'Unpredicted use case, used token type not available', request.get_full_path()) if _is_locally_hosted(request): config = RestClientConfig() else: config = RestClientConfig() class_name = class_name[0:class_name.rindex('View')] klass = globals()[class_name] instance = klass(config, credentials) return instance
def fix_turn_trigger(self): old_trigger = self.trigger trigger_key = self.trigger if "turn:" in trigger_key: trigger_parts = trigger_key.split(":") # clear triggers when switching spell ownership (like add buff) if trigger_parts[-1] == "ai" or re.search("[0-9]+", trigger_parts[-1]): del trigger_parts[-1] trigger_key = ":".join(trigger_parts) if "player" in trigger_key: trigger_key = "{0}:{1}".format(trigger_key, self.card.player.uid) elif "opponent" in trigger_key: trigger_key = "{0}:{1}".format( trigger_key, self.game.get_opposite_player(self.card.player.uid)) self.trigger = trigger_key logger.info("Spell> TurnTriggerFixed: from={0} to={1}".format( old_trigger, trigger_key))
def cast(self, data=None): tailored = [] targets = self.find_target(data) for card in targets: if card.alive: tailored.append({ 'card_died': { 'uid': card.player.uid, 'uuid': card.uuid, 'attach': 'execute', 'textanim': { 'text': "Executed", 'harmful': True } } }) event_result = card.kill( destroyer=self.card) # trigger game event/auras if event_result: tailored += event_result logger.info("spell> Execute cast result:{0}".format(tailored)) return tailored
def get(self, request, **kwargs): """ filtering asset which of given filter_value type. route filterassetsoftype return List all assets available for tenant with provided filter. param filter_value - specify the value to look for while filtering assets. description This method internally calls method get_assets_starts_with of AssetsClient class. Assets which are of provided type (filter_value) will be returned. This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl apiEndpoint : GET /api/assetmanagement/v3/assets of asset management service. apiNote List all assets available for the authenticated user. throws MindsphereError if an error occurs while attempting to invoke the sdk call. """ logger.info("assets/filterassetsoftype invoked.") client = sdk_util.build_sdk_client(self.__class__.__name__, request) if request.method == "GET": try: response = client.get_assets_of_type(request.GET.get("filterValue", None)) logger.info("Getting response successfully for filterassetsoftype" + json.dumps(response.to_dict)) except exceptions.MindsphereError as err: logger.error("Getting error for filterassetsoftype " + err) return HttpResponse( err, content_type="application/json", status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) return HttpResponse( json.dumps(response.to_dict), content_type="application/json", status=status.HTTP_200_OK )
def cast(self, data=None): tailored = [] targets = self.find_target(data) for card in targets: card.hp -= self.amount tailored.append({ 'dummy': {'uid': card.player.uid, 'uuid': card.uuid, 'textanim': {'text': "-{0}".format(self.amount), 'harmful': True}} }) # if card.is_hp_decreased(): tailored.append({ # if damaged > make bleeding anyway 'hp_decreased': {'uid': card.player.uid, 'uuid': card.uuid, 'hp': card.hp} }) if card.hp <= 0: tailored.append({ 'card_died': {'uid': card.player.uid, 'uuid': card.uuid} }) event_result = card.kill(destroyer=self.card) # trigger game event/auras if event_result: tailored += event_result logger.info("spell> Damage cast result:{0}".format(tailored)) return tailored
def nudge_loose_to_strict(self, loose): """ Nudge loose hits with at least 95 percent identity to be strict hits Parameters ---------- Args: loose (dict): dictionary containing loose hits Returns: nudged (bool): True or False loose (dict): dictionary containing loose or strict hits """ nudged = False # check if there are any loose hits that might be strict for i in loose: if 95 <= int(loose[i]["perc_identity"]) <= 100: # add to strict logger.info("loose hit with at least 95 percent identity push to Strict: {}".format(loose[i]["ARO_name"])) loose[i]["type_match"] = "Strict" loose[i]["nudged"] = True nudged = True return nudged, loose
def main(): logger.info("Starting consumer", version=__version__) consumer = Consumer() try: consumer.run() except KeyboardInterrupt: consumer.stop()
def get(self, request, **kwargs): """ route <str:id>/aspects return List of all aspects for provided asset id. param id : Unique identifier of an asset. (passed in keyword arguments.) description This method internally calls method list_asset_aspects of StructureClient class. This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl apiEndpoint : GET /api/assetmanagement/v3/assets/{id}/aspects of asset management service. apiNote Get all static and dynamic aspects of a given asset. throws Error if an error occurs while attempting to invoke the sdk call. """ logger.info("assets/<str:id>/aspects invoked.") client = sdk_util.build_sdk_client(self.__class__.__name__, request) if request.method == "GET": try: request_object = GetRootAssetRequest(if_none_match=None) asset = client.get_root_asset(request_object) asset = serialization_filter.sanitize_for_serialization(asset) resonse = json.dumps(asset) logger.info(resonse) except exceptions.MindsphereError as err: logger.error(err) return HttpResponse( err, content_type="application/json", status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) return HttpResponse( resonse, content_type="application/json", status=status.HTTP_200_OK )
def get_part_sequence(self, fasta_file, header, start, stop, nterminus, strand, name): """ Pull part sequence from fasta file # https://github.com/mdshw5/pyfaidx # pip install pyfaidx Parameters ---------- Args: fasta_file (str): input fasta file header (str): header for fasta sequence start (str): start coordinate stop (str): stop coordinate nterminus (int): length of missing sequence strand (str): strand name (str): gene name Returns: sequence (str): portion on a sequence """ # remove the last 2 characters from header as this is appended by prodigal header = header[:header.rfind("_")] # logger.info("[PARTIAL] ARO: {} | contig: {} | filename: {}".format(name, header, fasta_file)) genes = Fasta(fasta_file, sequence_always_upper=False, read_long_names=False, one_based_attributes=True) # logger.info(genes.records) logger.info(json.dumps({"strand":strand, "start":start, "stop":stop, "nterminus":nterminus}, indent=2)) if strand == "-": return str(genes.get_spliced_seq( header, [[stop, stop+nterminus]])) elif strand == "+": return str(genes.get_spliced_seq( header, [[start-nterminus, start]]))
def find_suitable_target(self, for_what, from_card): spell = None for spell_item in from_card.spells: if spell_item.trigger == for_what: spell = spell_item logger.info( "AI> find_suitable_target card.{0} found target_key: {1}". format(spell_item.trigger, spell_item.target_key)) break if spell: if "selected" in spell.target_key: # print(">>>", spell.target_key) spell.target_key = spell.target_key.replace( "selected", "random") elif "adjacent" in spell.target_key: return True targets = spell.find_target() if len(targets): return targets else: if for_what == "ondeploy" and spell.type != "damage": # TODO check spell type - if its damage > must select, hp/dp/hpdp not required to have a target return True return False return True
def get(self, request, **kwargs): """ filter asset types which contains route filterassettypecontains return List all asset types available for tenant with provided filter(asset types whose name contains provided filterValue). param filterValue - specify the value for fieldType(name) to look for while filtering asset types.. description This method internally calls method get_asset_types_contains of AssettypeClient class. This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl. apiEndpoint : GET /api/assetmanagement/v3/assettypes of asset management service. apiNote List all asset types. throws MindsphereError if an error occurs while attempting to invoke the sdk call. """ logger.info("assets/filterassettypecontains invoked.") client = sdk_util.build_sdk_client(self.__class__.__name__, request) if request.method == "GET": try: response = client.get_asset_types_contains(field_type=data_generator.FieldTypeEnum.NAME, filter_value=request.GET.get("filterValue", None)) logger.info( "Getting response successfully for create filterassettypecontains " + json.dumps(response.to_dict)) except exceptions.MindsphereError as err: logger.error("Getting error for create filterassettypecontains " + err) return HttpResponse( err, content_type="application/json", status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) return HttpResponse( json.dumps(response.to_dict), content_type="application/json", status=status.HTTP_200_OK )
def get(self, request, **kwargs): """ Create aspect type. route assets/aspects param tenantName - Name of the tenant for which you want to create aspect type. Passed in request. return Created aspect type information object. description This method internally calls method save_aspect_type of AspecttypeClient class. This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl apiEndpoint : PUT /api/assetmanagement/v3/aspecttypes/{id} of asset management service. apiNote Create or Update an aspect type throws MindsphereError if an error occurs while attempting to invoke the sdk call. """ logger.info("assets/aspects invoked.") client = sdk_util.build_sdk_client(self.__class__.__name__, request) if request.method == "GET": try: request_object = data_generator.generate_aspect_input( tenant=request.GET.get("tenantName", None) ) aspect = client.save_aspect_type(request_object) logger.info("Getting response successfully for create aspects " + json.dumps(aspect.to_dict)) except exceptions.MindsphereError as err: logger.error("Getting error for create aspects " + err) return HttpResponse( err, content_type="application/json", status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) return HttpResponse( json.dumps(aspect.to_dict), content_type="application/json", status=status.HTTP_200_OK )
def cast(self, data=None): logger.info("Events> Aura registering {0} {1}".format( self.aura_give.trigger, self.card.title)) self.game.events.register(key=self.aura_give.trigger, card=self.card, callback=self.give_handler, unregister_callback=self.take_handler) return []
def get_available_slot(self, excludes=None): if self.is_full(): return -1 logger.info("Ground> get_available_slots {0}".format(self.slots)) for slotIndex in self.slot_order: if self.slots[slotIndex] is None: return slotIndex return -1
def remove(self, vcard): # logger.info("CardContainer> {0} removing {1}".format(self.container_type, vcard)) if vcard in self.cards: self.cards.remove(vcard) logger.info("{0}.{1}> Rem {2} {3}".format(self.container_type, self.player.uid, vcard.title, self.cards)) else: print("{0}.{1}> CardNotInHand {2} hand.remove {3}".format( self.container_type, self.player.uid, vcard.title, self.cards))
def add(self, vcard): if self.limit and len(self.cards) + 1 > self.limit: return False self.cards.append(vcard) if self.container_type != "GRAVEYARD": logger.info("{0}.{1}> Add {2} {3}".format(self.container_type, self.player.uid, vcard.title, self.cards)) return True
def on_finish(self): if self.token_info: if self.result: base_log = f"IP:{self.request.remote_ip},用户:{self.token_info['account']}" if self.result['status_code'] == 200: logger.info("%s 进行%s操作", base_log, self.__class__.__name__) else: logger.warning("%s,%s", base_log, self.result['data']) else: logger.warning("无效token:%s", self.request.headers.get("token"))
async def callback_door_skip(callback_query: CallbackQuery, **kwargs): logger.info(f'callback data: {callback_query.data}') door_id = get_int(callback_query.data.replace('door_skip_', '')) perco = dp['perco'] await perco.open_door(door_id) await answer_callback_query( callback_query.id, 'Дверь открыта, через 8 сек закроется автоматически') await sleep(8) await perco.close_door(door_id)
def worker(self, input_fasta): o_f_path, o_f_name = os.path.split(os.path.abspath(input_fasta)) cmd = "prodigal -p meta -q -m -i {input_fasta} -d {wd}/{tmp_name}.temp.contigToORF.fsa \ -a {wd}/{tmp_name}.temp.contig.fsa \ -o {wd}/{tmp_name}.temp.draft \ -s {wd}/{tmp_name}.temp.potentialGenes 2> /dev/null".format( input_fasta=input_fasta, wd=self.working_directory, tmp_name=o_f_name) logger.info(cmd) os.system(cmd)
def run(self, data): logger.info("Events> Running trigger:{0} card:{1}".format( self.type, self.card.title)) tailored = self.callback(data) """ for spell in self.card.spells: if spell.trigger == self.type: tailored += spell.cast(data) """ return [] if not tailored else tailored
async def wrapper(*args, **kwargs): message = args[0] if isinstance(message, CallbackQuery): message = message.message if not isinstance(message, Message): logger.info(f'func: {func.__name__}, args: {args}') return if not message or message.chat.username != ADMIN_USERNAME: return await message.reply( 'У вас не достаточно прав для данной операции') logger.info(f'args: {args}, kwargs: {kwargs}') return await func(*args, **kwargs)
def cast(self, data=None): """ :param data: dict :return: list """ target = self.find_target(data)[0] if isinstance(target, Card): target = target.player tailored = [target.draw_card(amount=self.amount, return_tailored=True)] logger.info("spell> Draw cast result:{0}".format(tailored)) return tailored
async def callback_door_close(callback_query: CallbackQuery, **kwargs): logger.info(f'callback data: {callback_query.data}') door_id = get_int(callback_query.data.replace('door_close_', '')) perco = dp['perco'] await perco.close_door(door_id) is_closed = await perco.door_is_closed(door_id) if is_closed is None: message = 'Не удалось подключиться к Perco-WEB' elif is_closed: message = 'Дверь закрыта' else: message = 'Не удалось закрыть' await answer_callback_query(callback_query.id, message)
def fire(self, key, data): logger.info("Events> Firing {0} {1}".format(key, data)) tailored = [] triggered = 0 for event in self.events: if event.type == key: tailored += event.run(data) triggered += 1 if triggered > 0: logger.info("Events> Fired: {0} {1} events triggered!".format( key, triggered)) return tailored