def get_user_active_stats(data): address = data['address'] Mon_ID = data['Mon_ID'] response_data = {} UserActiveStatus = EtheremonDB.DCLUserActiveStatus.objects.filter( Q(address=address)).first() if UserActiveStatus is None: return {"status": "UserActiveStatus not found"} monrecord = EtheremonDB.DCLMonsterData.objects.filter( Q(Mon_ID=Mon_ID)).first() if monrecord.sleep_end_timer <= get_timestamp(): return { "status": "SUCCESS", 'awake': 1, "sleep_end_timer": monrecord.sleep_end_timer } if monrecord.sleep_end_timer > get_timestamp(): return { "status": "SUCCESS", 'awake': 0, "sleep_end_timer": monrecord.sleep_end_timer }
def get_or_create_burn_request(player_address, mon_id, mon_level=1, mon_exp=1, amount_type=BurnRewardTypes.UNDEFINED, amount_value=0, status=BurnStatus.INIT): burn_request = get_burn_request_by_mon(player_address, mon_id)\ .filter(status__in=[BurnStatus.INIT, BurnStatus.PENDING])\ .first() if burn_request: if burn_request.mon_level != mon_level or burn_request.mon_exp != mon_exp: burn_request.mon_level = mon_level burn_request.mon_exp = mon_exp burn_request.save() return burn_request burn_request = EtheremonDB.BurnMonTab( player_address=player_address, mon_id=mon_id, mon_level=mon_level, mon_exp=mon_exp, amount_type=amount_type, amount_value=amount_value, status=status, create_time=get_timestamp(), update_time=get_timestamp(), ) burn_request.save() return burn_request
def update_free_food(): free_food_config = EtheremonDB.DCLItemClassConfig.objects.filter( ItemVariety='beet').first() if free_food_config is None: print 'NO_RELEVANT_DCL_ITEM_CLASS_CONFIG_FOUND' return false ## delete already planted food which are not eaten / plucked yet EtheremonDB.DCLItemWip.objects.filter(growth_state=0).filter( ItemVariety=free_food_config.ItemVariety).delete() # plant a free food - 50% chance for each users who are all logged in two weeks two_weeks = get_timestamp() - (14 * 24 * 3600) #2 weeks users = EtheremonDB.DCLUserActiveStatus.objects.filter( last_seen__gt=two_weeks).all() cursor = connection.cursor() cursor.execute('SELECT DISTINCT host_id from dcl_item_wip') cur_gar = cursor.fetchall() all_gardens = [] for g in cur_gar: all_gardens.append(g[0]) #every user will plant on all host_id..50% chance for user in users: #seed on all gardens for garden in all_gardens: #50% chance if random.choice([True, False]): with transaction.atomic(): exists = EtheremonDB.DCLItemWip.objects.filter( Q(host_id=garden) & Q(meta_id=86) & Q(growth_state=0) & Q(address=user.address)).first() if exists: print 'META_AND_HOST_AND_ADDRESS_ALREADY_EXISTS_IN_GROWING_STATE' continue secs_to_grow = 0 if free_food_config: secs_to_grow = free_food_config.craft_timer #create new wip EtheremonDB.DCLItemWip.objects.create( ItemClass=free_food_config.ItemClass, ItemVariety=free_food_config.ItemVariety, wild='no', wild_count=0, address=user.address, growth_state=0, host_id=garden, meta_id=86, start_timer=get_timestamp(), end_timer=get_timestamp() + secs_to_grow)
def create_transaction(player_uid, player_address, txn_type, txn_info, amount_type, amount_value, status=TxnStatus.INIT, txn_hash=None, extra=None): txn = EtheremonDB.TransactionTab( player_uid=player_uid, player_address=player_address, txn_type=txn_type, txn_info=txn_info, txn_hash=txn_hash, status=status, amount_type=amount_type, amount_value=round(amount_value, 4), extra=extra if extra is None else json.dumps(extra), create_time=get_timestamp(), update_time=get_timestamp(), ) txn.save() return txn
def create_balance_obj(player_uid, player_address, balance_type, init_value, status=BalanceStatus.ACTIVE, extra=None): return EtheremonDB.BalanceTab.objects.create( player_uid=player_uid, player_address=player_address, balance_type=balance_type, balance_value=init_value, status=status, extra=extra, create_time=get_timestamp(), update_time=get_timestamp() )
def free_energy(): print "sdsdsd" with transaction.atomic(): #3 non free mons free_mons = [25, 26, 27] non_free = EtheremonDB.EmaMonsterDataTab.objects.values( 'trainer').annotate(cnt=Count('trainer')).filter( Q(cnt__gte=3)).exclude(class_id__in=free_mons).all() non_free_trainers = [] for rec in non_free: print rec['trainer'] non_free_trainers.append(str(rec['trainer'])) #get mon less than 20 energy for the non free mon holders and recharge them 20 non_free_players_energy = EtheremonDB.EmaPlayerEnergyTab.objects.select_for_update( ).annotate( variance=F('init_amount') + F('free_amount') + F('paid_amount') - F('invalid_amount') - F('consumed_amount')).filter( Q(trainer__in=non_free_trainers) & Q(variance__lt=20)).all() print "energy" for nfp in non_free_players_energy: energy_to_add = 20 - nfp.variance #max 20 nfp.init_amount += energy_to_add nfp.update_time = get_timestamp() nfp.save() #exclude trainers who own paid mons..because they were already recharged above or already having sufficient energy other_mon_holders = EtheremonDB.EmaMonsterDataTab.objects.values( 'trainer').annotate(cnt=Count('trainer')).filter( Q(cnt__gte=3)).exclude(trainer__in=non_free_trainers).all() print "other mon holders" other_mon_trainers = [] for om in other_mon_holders: print om['trainer'] other_mon_trainers.append(str(om['trainer'])) #get mon less than 10 energy for the other mon holders and recharge them 10 other_mon_holders_energy = EtheremonDB.EmaPlayerEnergyTab.objects.select_for_update( ).annotate( variance=F('init_amount') + F('free_amount') + F('paid_amount') - F('invalid_amount') - F('consumed_amount')).filter( Q(trainer__in=other_mon_trainers) & Q(variance__lt=10)).all() print "other energy" for ome in other_mon_holders_energy: energy_to_add = 10 - ome.variance #max 10 ome.init_amount += energy_to_add ome.update_time = get_timestamp() ome.save()
def use_user_fungible(data): dcl_fungible_id = data['dcl_fungible_id'] host_id = data['host_id'] meta_id = data['meta_id'] qty = data['qty'] with transaction.atomic(): record = EtheremonDB.DCLUserFungible.objects.select_for_update( ).filter(Q(dcl_fungible_id=dcl_fungible_id)).first() if not record: return 'USER_FUNGIBLE_MATCHING_THE_ID_NOT_FOUND' exists = EtheremonDB.DCLItemWip.objects.filter( Q(host_id=host_id) & Q(meta_id=meta_id) & Q(growth_state=0) & Q(address=record.address)).first() if exists: return 'META_AND_HOST_AND_ADDRESS_ALREADY_EXISTS_IN_GROWING_STATE' #proceed only if requested qty is available if record.qty >= qty: record.qty -= qty record.save() #fetch time to grow from config secs_to_grow = 60 * 60 config_record = EtheremonDB.DCLItemClassConfig.objects.filter( Q(ItemClass=record.ItemClass) & Q(ItemVariety=record.ItemVariety)).first() if config_record: secs_to_grow = config_record.craft_timer #create new wip EtheremonDB.DCLItemWip.objects.create( ItemClass=record.ItemClass, ItemVariety=record.ItemVariety, wild='no', wild_count=0, address=record.address, growth_state=0, host_id=host_id, meta_id=meta_id, start_timer=get_timestamp(), end_timer=get_timestamp() + secs_to_grow) return 'SAVED' else: return 'NOT_ENOUGH_QTY'
def set_or_create_setting(setting_id, name, value): setting = get_setting(setting_id) if not setting: setting = EtheremonDB.EmaSettingsTab(setting_id=setting_id, name=name, value=value, create_time=get_timestamp(), update_time=get_timestamp()) else: setting.value = value setting.update_time = get_timestamp() setting.save() return setting
def put_mon_to_sleep(data): with transaction.atomic(): Mon_ID = data['Mon_ID'] ts = get_timestamp() monrecord = EtheremonDB.DCLMonsterData.objects.select_for_update( ).filter(Q(Mon_ID=Mon_ID)).first() monrecord.last_saved = ts #SET sleep_end_timer to time require to 1000 Energy #So 1.388 energy per minute or 83,3 per hour or 1000 per 12 hours sleep_end_timer = get_timestamp() + (monrecord.Energy_max - monster.energy_current) * 43.2 monrecord.sleep_end_timer = sleep_end_timer monrecord.save() return "SAVED"
def run(self): start = time.time() logger.log('INFOR', f'Start running {self.source} module') self.subdomains = utils.get_domains(self.target) self.format = utils.check_format(self.format, len(self.subdomains)) timestamp = utils.get_timestamp() name = f'takeover_check_result_{timestamp}' self.path = utils.check_path(self.path, name, self.format) if self.subdomains: logger.log('INFOR', f'Checking subdomain takeover') self.fingerprints = get_fingerprint() self.results.headers = ['subdomain', 'cname'] # 创建待检查的子域队列 for domain in self.subdomains: self.subdomainq.put(domain) # 检查线程 for _ in range(self.thread): check_thread = Thread(target=self.check, daemon=True) check_thread.start() # 进度线程 progress_thread = Thread(target=self.progress, daemon=True) progress_thread.start() self.subdomainq.join() self.save() else: logger.log('FATAL', f'Failed to obtain domain') end = time.time() elapse = round(end - start, 1) logger.log( 'INFOR', f'{self.source} module takes {elapse} seconds, ' f'There are {len(self.results)} subdomains exists takeover') logger.log('INFOR', f'Subdomain takeover results: {self.path}') logger.log('INFOR', f'Finished {self.source} module')
def do(model, prepared_data_root, pretrained_model, use_wakatigaki): logger.info('Start making LSTM training data.') if model.prepared_file_path: # re-use existing directory for f in os.listdir(model.prepared_file_path): os.remove(os.path.join(model.prepared_file_path, f)) else: model.prepared_file_path = os.path.join(prepared_data_root, ds_utils.get_timestamp()) os.mkdir(model.prepared_file_path) if pretrained_model != "-1": trained_model_path = model.trained_model_path if trained_model_path: pretrained_vocab = os.path.join(trained_model_path, 'vocab2.bin') if not os.path.exists(pretrained_vocab): logger.error( "Could not find vocab2.bin file. It is possible that previsou train have failed: {0}" .format(pretrained_vocab)) raise Exception( "Could not find vocab2.bin file. It is possible that previsou train have failed: ", pretrained_vocab) else: pretrained_vocab = '' else: pretrained_vocab = '' input_data_path = make_train_text(model, use_wakatigaki) model.update_and_commit() logger.info('Finish making LSTM training data.') return input_data_path, pretrained_vocab, model
def save_uploaded_file_to_category(self, uploaded_file, category): filename = uploaded_file.filename name, ext = os.path.splitext(filename) ext = ext.lower() if self.type == 'image': if ext not in ('.jpg', '.jpeg', '.png', '.gif'): raise ValueError('Invalid file type.') elif self.type == 'text': if ext not in ('.txt', ): raise ValueError('Invalid file type.') new_filename = os.path.join( self.dataset_path, category, ds_util.get_timestamp() + '_' + secure_filename(filename)) if self.type == 'image': uploaded_file.save(new_filename) elif self.type == 'text': text = uploaded_file.stream.read() if nkf.guess(text) == 'binary': raise ValueError( 'Invalid file type. File must be a text file.') f = open(new_filename, 'w') f.write(text) f.close() self.file_num += 1 self.update_and_commit()
def inspect(self, epoch, uploaded, save_to): name, ext = os.path.splitext(uploaded.filename) ext = ext.lower() if ext not in ('.jpg', '.jpeg', '.gif', '.png'): raise Exception('File extension not allowed.') new_filename = os.path.join(save_to, ds_utils.get_timestamp() + '_' + secure_filename(uploaded.filename)) uploaded.save(new_filename) if self.framework == 'chainer': results = inspection.inspect_by_chainer( new_filename, self.mean_file, self.get_trained_model(epoch), self.labels_text, self.network_path, self.resize_mode, self.channels, gpu=-1 ) elif self.framework == 'tensorflow': results = inspection.inspect_by_tensorflow( new_filename, self.mean_file, self.get_trained_model(epoch), self.labels_text, self.network_path, self.resize_mode, self.channels, gpu=-1 ) return results, new_filename
def add_pending_exp_claim(monster_id): record = EtheremonDB.EmaClaimMonExpTab( monster_id=monster_id, exp=0, status=EmaClaimStatus.STATUS_INIT, update_time=get_timestamp() ) record.save() with transaction.atomic(): exp_record = EtheremonDB.EmaMonsterExpTab.objects.select_for_update().filter(monster_id=monster_id).first() if not exp_record or exp_record.adding_exp == 0: return record # check pending init_records = list(EtheremonDB.EmaClaimMonExpTab.objects.select_for_update().filter(monster_id=monster_id).filter(status=EmaClaimStatus.STATUS_INIT).all()) pending_record = EtheremonDB.EmaClaimMonExpTab.objects.select_for_update().filter(monster_id=monster_id).filter(status=EmaClaimStatus.STATUS_PENDING).first() if pending_record: for init_record in init_records: init_record.status = EmaClaimStatus.STATUS_FAIL init_record.save() return pending_record first_record = init_records[0] for init_record in init_records[1:]: init_record.status = EmaClaimStatus.STATUS_FAIL init_record.save() first_record.exp = exp_record.adding_exp first_record.status = EmaClaimStatus.STATUS_PENDING first_record.save() return first_record
def get_player_quests(player_uid, player_address, quest_type): current_ts = get_timestamp() with transaction.atomic(): quests = EtheremonDB.QuestTab.objects\ .filter(player_uid=player_uid)\ if quest_type != QuestTypes.ALL_TYPES: quests = quests.filter(quest_type=quest_type) quest_map = {} for quest in quests: quest_info = quest_config.QUEST_LIST[quest.quest_id] is_daily_quest = quest_info[ 'quest_type'] == QuestTypes.DAILY or quest_info.get( 'is_daily', False) is_active_daily_quest = is_daily_quest and quest_info.get( "start_time", 0) < current_ts < quest_info.get( "end_time", INFINITY_FUTURE) if is_active_daily_quest or quest.start_time <= current_ts <= quest.end_time: quest_map[quest.quest_id] = quest # Update quest for quest_id, quest_info in quest_config.QUEST_LIST.iteritems(): if quest_type in [QuestTypes.ALL_TYPES, quest_info['quest_type']]\ and quest_info.get("start_time", 0) < current_ts < quest_info.get("end_time", INFINITY_FUTURE): quest_map[quest_id] = create_or_update_quest( player_uid, player_address, quest_id, quest_map.get(quest_id, None)) return quest_map
def add_pending_win_claim(player_id): record = EtheremonDB.EmaClaimRankWinTab( player_id=player_id, count_win=0, count_emont=0, status=EmaClaimStatus.STATUS_INIT, update_time=get_timestamp() ) record.save() with transaction.atomic(): player_data = EtheremonDB.EmaPlayerRankData.objects.select_for_update().filter(player_id=player_id).first() if not player_data: return record available_win = player_data.total_win - player_data.total_claimed if available_win < 1: return record init_records = list(EtheremonDB.EmaClaimRankWinTab.objects.select_for_update().filter(player_id=player_id).filter(status=EmaClaimStatus.STATUS_INIT).all()) pending_record = EtheremonDB.EmaClaimRankWinTab.objects.select_for_update().filter(player_id=player_id).filter(status=EmaClaimStatus.STATUS_PENDING).first() if pending_record: for init_record in init_records: init_record.status = EmaClaimStatus.STATUS_FAIL init_record.save() return pending_record first_record = init_records[0] for init_record in init_records[1:]: init_record.status = EmaClaimStatus.STATUS_FAIL init_record.save() first_record.count_win = available_win first_record.count_emont = WIN_EMONT_REWARD * available_win first_record.status = EmaClaimStatus.STATUS_PENDING first_record.save() player_data.total_claimed += available_win player_data.save() return first_record
def vote(request, data): trainer_address = data["trainer_address"].lower() signature = data["signature"].lower() vote_timestamp = data["vote_timestamp"] explore_eth = round(data["explore_eth"], 5) explore_emont = round(data["explore_emont"], 5) challenge_eth = round(data["challenge_eth"], 5) challenge_emont = round(data["challenge_emont"], 5) # verify information if not Web3.isAddress(data["trainer_address"]): log.warn("trainer_address_invalid|data=%s", data) return api_response_result(request, ResultCode.ERROR_PARAMS, {"error_message": "invald_send_to_address"}) current_ts = get_timestamp() if abs(current_ts - vote_timestamp) > 5 * 60: log.warn("old_vote_time|current_ts=%s,data=%s", current_ts, data) return api_response_result(request, ResultCode.ERROR_PARAMS, {"error_message": "invalid_timestamp"}) # verify signature message = "vote-%s" % vote_timestamp if not _verify_signature(message, signature, trainer_address): log.warn("trainer_invalid_signature|trainer=%s,message=%s", trainer_address, message) return api_response_result(request, ResultCode.ERROR_SIGNATURE) set_adventure_vote(trainer_address, explore_eth, explore_emont, challenge_eth, challenge_emont, vote_timestamp) log.data("update_vote|trainer=%s,explore_eth=%s,explore_emont=%s,challenge_eth=%s,challenge_emont=%s", trainer_address, explore_eth, explore_emont, challenge_eth, challenge_emont) return api_response_result(request, ResultCode.SUCCESS)
def run(self): start = time.time() logger.log('INFOR', f'开始执行{self.source}模块') self.subdomains = utils.get_domains(self.target) self.format = utils.check_format(self.format, len(self.subdomains)) timestamp = utils.get_timestamp() name = f'takeover_check_result_{timestamp}' self.path = utils.check_path(self.path, name, self.format) if self.subdomains: logger.log('INFOR', f'正在检查子域接管风险') self.fingerprints = get_fingerprint() self.results.headers = ['subdomain', 'cname'] # 创建待检查的子域队列 for domain in self.subdomains: self.subdomainq.put(domain) # 检查线程 for _ in range(self.thread): check_thread = Thread(target=self.check, daemon=True) check_thread.start() # 进度线程 progress_thread = Thread(target=self.progress, daemon=True) progress_thread.start() self.subdomainq.join() self.save() else: logger.log('FATAL', f'获取域名失败') end = time.time() elapse = round(end - start, 1) logger.log( 'INFOR', f'{self.source}模块耗时{elapse}秒' f'发现{len(self.results)}个子域存在接管风险') logger.log('INFOR', f'子域接管风险检查结果 {self.path}') logger.log('INFOR', f'结束执行{self.source}模块')
def start_tournaments(): current_time = get_timestamp() tournaments = EtheremonDB.TournamentInfoTab.objects.filter( status=TournamentStatus.REGISTRATION).filter( start_time__lte=current_time) for tournament in tournaments: start_tournament(tournament)
def save(self): logger.log('INFOR', '正在保存检查结果') if self.format == 'txt': data = str(self.results) else: data = self.results.export(self.format) timestamp = utils.get_timestamp() fpath = self.dpath.joinpath(f'takeover_{timestamp}.{self.format}') utils.save_data(fpath, data)
def add_energy(trainer_address, value): record = EtheremonDB.EmaPlayerEnergyTab.objects.filter(trainer=trainer_address).first() if record: record.update_time = get_timestamp() record.init_amount = record.init_amount + value record.save() return record else: return None
def create_emont_claim(uid, amount): current_ts = get_timestamp() record = EtheremonDB.ClaimReferTab(uid=uid, amount=amount, status=ReferClaimStatus.STATUS_PENDING, create_time=current_ts, update_time=current_ts) record.save() return record
def save_uploaded_data(self, uploaded_file, save_raw_file_to, save_to): filename = uploaded_file.filename name, ext = os.path.splitext(filename) if ext not in ('.zip'): raise ValueError('Invalid file type. Only zip file is allowed: ' + filename) timestamp_str = ds_util.get_timestamp() new_filename = secure_filename(re.sub(r'\.zip$', '_' + timestamp_str + '.zip', filename)) uploaded_file.save(os.path.join(save_raw_file_to, new_filename)) # extract zip file extract_to = os.path.join(save_to, timestamp_str) self.dataset_path = extract_to try: os.mkdir(extract_to) except Exception as e: logger.exception('Could not create directory to extract zip file: {0} {1}' .format(extract_to, e)) raise file_num = 0 category_num = 0 try: zf = zipfile.ZipFile(os.path.join(save_raw_file_to, new_filename), 'r') name_list = zf.namelist() encoding = chardet.detect(''.join(name_list)).get('encoding', 'utf-8') for file_name in (file_name.decode(encoding) for file_name in name_list): if ('__MACOSX' in file_name) or ('.DS_Store' in file_name): continue temp_path = os.path.join(extract_to, file_name) if not os.path.exists(os.path.dirname(temp_path)): os.makedirs(temp_path.encode(encoding='utf-8')) category_num += 1 else: temp, ext = os.path.splitext(temp_path) ext = ext.lower() if self.type == 'image': if ext not in ('.jpg', '.jpeg', '.png', '.gif'): continue elif self.type == 'text': if ext not in ('.txt',): continue if os.path.exists(temp_path): uzf = file(temp_path, 'w+b') else: uzf = file(temp_path, 'wb') uzf.write(zf.read(file_name.encode(encoding=encoding))) uzf.close() file_num += 1 except Exception as e: logger.exception('Could not extract zip file: {0}'.format(e)) raise finally: if 'zf' in locals(): zf.close() if 'uzf' in locals(): uzf.close() self.category_num = category_num self.file_num = file_num self.update_and_commit()
def add_purchase(data): pur_record = EtheremonDB.DCLMetazoePurchase( action=data["action"], meta_id=data["meta_id"], host_id=data["host_id"], plot_unique=data["plot_unique"], txn_token=data["txn_token"], eth_from=data["eth_from"], dcl_name=data["dcl_name"], sku=data["sku"], create_date=data["create_date"]) pur_record.save() #sku will come as beet1 or beet3 - get the suffix temp = re.compile("([a-zA-Z]+)([0-9]+)") sku_split = temp.match(data["sku"]).groups() config_record = EtheremonDB.DCLItemClassConfig.objects.filter( Q(metazone_sku=sku_split[0])).first() if config_record is None: return 'NO_RELEVANT_DCL_ITEM_CLASS_CONFIG_FOUND_FOR_SKU ' + sku_split[0] qty = sku_split[1] fungible_record = EtheremonDB.DCLUserFungible.objects.filter( Q(address=data["eth_from"]) & Q(ItemClass=config_record.ItemClass) & Q(ItemVariety=config_record.ItemVariety)).first() if fungible_record is None: new_record = EtheremonDB.DCLUserFungible.objects.update_or_create( address=data["eth_from"], ItemClass=config_record.ItemClass, ItemVariety=config_record.ItemVariety, craft_hierachy=1, qty=qty, create_time=get_timestamp()) new_record.save() else: fungible_record.qty += int(qty) create_time = get_timestamp() fungible_record.save() return 'SAVED'
def claim_reward(request, data): trainer_address = data["trainer_address"].lower() reward_txn_id = data["reward_id"] # verify information if not Web3.isAddress(trainer_address): log.warn("send_to_address_invalid|data=%s", data) return api_response_result( request, ResultCode.ERROR_PARAMS, {"error_message": "invalid_send_to_address"}) txn_info = transaction_manager.get_transaction_by_id(reward_txn_id) if not txn_info or txn_info.player_address != trainer_address: log.warn("invalid_reward|trainer_address=%s", trainer_address) return api_response_result(request, ResultCode.ERROR_PARAMS, {"error_message": "invalid_reward"}) if txn_info.status not in [TxnStatus.INIT, TxnStatus.PENDING]: log.warn("reward_already_claimed|trainer_address=%s", trainer_address) return api_response_result(request, ResultCode.ERROR_PARAMS, {"error_message": "invalid_reward"}) txn_info.status = TxnStatus.PENDING txn_info.save() # Map to contract's reward types if txn_info.amount_type == TxnAmountTypes.ADV_LEVEL_STONE_1: reward_type = EtheremonClaimRewardContract.REWARD_TYPES["level_stone"] reward_value = 1 elif txn_info.amount_type == TxnAmountTypes.ADV_LEVEL_STONE_2: reward_type = EtheremonClaimRewardContract.REWARD_TYPES["level_stone"] reward_value = 2 elif txn_info.amount_type == TxnAmountTypes.MON: reward_type = EtheremonClaimRewardContract.REWARD_TYPES["mon"] reward_value = txn_info.amount_value else: log.warn("reward_not_supported|trainer_address=%s", trainer_address) return api_response_result(request, ResultCode.ERROR_PARAMS, {"error_message": "invalid_reward"}) current_ts = get_timestamp() claim_reward_token = crypt.create_claim_reward_token( txn_info.id, reward_type, reward_value, current_ts) r, s, v = sign_claim_reward(claim_reward_token, trainer_address) response_data = { "token": "0x" + claim_reward_token, "r": r, "s": s, "v": v } log.data("claim_reward|trainer_address=%s,token=0x%s", trainer_address, claim_reward_token) return api_response_result(request, ResultCode.SUCCESS, response_data)
def remove(user, channel_id, name): now = get_timestamp() values = { 'delete_time': now, 'modified_time': now, 'modifier': user.get('name') } change_count = ActivityChannelTab.objects.filter( id=channel_id, name=name).update(**values) return Resp.RESP_OK if change_count else Resp.RESP_ITEM_NOT_EXIST
def add(user, **channel): if ActivityChannelTab.objects.filter(name=channel.get('name'), delete_time=0).exists(): return Resp.RESP_ITEM_EXIST, None now = get_timestamp() model = ActivityChannelTab(**channel) model.created_time = now model.creator = user.get('name') model.save() return Resp.RESP_OK, model_to_dict(model)
def proceed_pending_top_claim(request_id): current_ts = get_timestamp() with transaction.atomic(): request_record = EtheremonDB.EmaClaimRankTopTab.objects.select_for_update().get(id=request_id) if request_record.status != EmaClaimStatus.STATUS_PENDING: return False request_record.status = EmaClaimStatus.STATUS_COMPLETE request_record.update_time = current_ts request_record.save() return True
def crawl_adventure_presale(): infura_client = InfuraClient(INFURA_API_URL) adventure_presale_contract = infura_client.getAdventurePresaleContract() current_ts = get_timestamp() site_id_index = 1 while site_id_index <= 54: site_item_index = 0 while site_item_index < 10: try: (bidder, bid_id, site_id, amount, bid_time ) = adventure_presale_contract.call().getBidBySiteIndex( site_id_index, site_item_index) if bid_id == 0: log.warn( "query_adventure_presale_invalid|site_id=%s,site_index=%s", site_id_index, site_item_index) time.sleep(3) continue except Exception as error: logging.exception( "query_adventure_presale_exception|site_id=%s,site_index=%s", site_id_index, site_item_index) time.sleep(3) continue bidder = bidder.lower() record = EtheremonDB.EmaAdventurePresaleTab.objects.filter( bid_id=bid_id).first() if record: record.site_id = site_id record.bid_id = bid_id record.site_index = site_item_index record.bidder = bidder record.bid_amount = amount record.bid_time = bid_time else: record = EtheremonDB.EmaAdventurePresaleTab( site_id=site_id, site_index=site_item_index, bid_id=bid_id, bidder=bidder, bid_amount=amount, bid_time=bid_time, token_id=0, update_time=current_ts) log.data( "adventure_presale_query|site_id=%s,site_index=%s,bid_id=%s", site_id_index, site_item_index, bid_id) record.save() site_item_index += 1 site_id_index += 1
def update_and_get_claiming_emont(uid): infura_client = get_general_infura_client() refer_contract = infura_client.getReferContract() pending_claim = user_manager.get_pending_emont_claim(uid) if pending_claim: amount = refer_contract.call().getClaimIdInfo(pending_claim.id) if amount == pending_claim.amount: pending_claim.status = ReferClaimStatus.STATUS_COMPLETE pending_claim.update_time = get_timestamp() pending_claim.save() return pending_claim
def sync(self): "" cfg=self.cfg tm=get_timestamp() tm=tm.replace('-','_') touch(tm) # upload_time(cfg['archival_ip'],tm) try: ftp_upload(cfg['archival_ip'],cfg['praco_username'],cfg['praco_password'],tm) except: pass try: ftp_upload(cfg['encoder_ip'],cfg['praco_username'],cfg['praco_password'],tm) except: pass # upload_time(cfg['encoder_ip'],tm) time.sleep(5)
print t2.read_until(">") t2.write("cd FlashDisk/Best"+newline) print t2.read_until("Best") t3=telnetlib.Telnet(cfg['encoder_ip'],port=23) newline = "\n" print t3.read_until("login:"******"admin"+newline) print t3.read_until("Password:"******"BEST"+newline) print t3.read_until(">") t3.write("cd FlashDisk/Best"+newline) print t3.read_until("Best") ### start DAQ program ### t1.write("DAQrad1"+newline) print t1.read_until(">",3) t2.write("DAQArchImuS1"+newline) print t2.read_until(">",3) t3.write("DAQenc_new"+newline) print t3.read_until(">",3) tm=get_timestamp() tm=tm.replace('-','_')+'.time' touch(tm) upload_time(cfg['archival_ip'],tm) upload_time(cfg['encoder_ip'],tm) upload_time(cfg['radiometer']['rad22_ip'],tm) time.sleep(3) os.remove(tm)