def test_is_int(self): self.assertTrue(util.is_int(0)) self.assertTrue(util.is_int(1)) self.assertTrue(util.is_int(1.0)) self.assertTrue(util.is_int('0')) self.assertTrue(util.is_int('1')) self.assertTrue(util.is_int('+122')) self.assertTrue(util.is_int('-3452')) self.assertFalse(util.is_int('-3452.4232')) self.assertTrue(util.is_int(-3452.4232)) # !!!
def on_new_syndicated_post(self, syndpost): """If this source has no username, try to infer one from a syndication URL. Args: syndpost: SyndicatedPost """ url = syndpost.syndication if self.username or not url: return # FB usernames only have letters, numbers, and periods: # https://www.facebook.com/help/105399436216001 author_id = self.gr_source.base_object({'object': {'url': url}})\ .get('author', {}).get('id') if author_id: if author_id != self.inferred_username and not util.is_int(author_id): logging.info('Inferring username %s from syndication url %s', author_id, url) self.inferred_username = author_id self.put() syndpost.syndication = self.canonicalize_url(syndpost.syndication) elif author_id != self.key.id() and author_id not in self.inferred_user_ids: logging.info('Inferring app-scoped user id %s from syndication url %s', author_id, url) self.inferred_user_ids = util.uniquify(self.inferred_user_ids + [author_id]) self.put() syndpost.syndication = self.canonicalize_url(syndpost.syndication)
def place_numbers(loc, level, replace_symbols): "Manipulates array: places numbers around location, returns tiles changes and point stopped" y, x = loc loc_symbol = level[y][x] if loc_symbol == 'A': return [], loc changed_tiles = [] x_size = len(level[0]) y_size = len(level) w = x - 1 if w < 0: w = x_size - 1 e= x + 1 if e > x_size - 1: e = 0 n = y - 1 if n < 0: n = y_size - 1 s = y + 1 if s > y_size - 1: s = 0 points = [(y, w), (y, e), (n, x), (s, x)] for point in points: y, x = point s = level[y][x] if s in replace_symbols: is_int = util.is_int(loc_symbol) if not is_int and loc_symbol != 'A': level[y][x] = 1 elif is_int: level[y][x] = int(level[loc[0]][loc[1]]) + 1 changed_tiles.append((y, x)) return changed_tiles, None
async def command(self, message: discord.Message): if not self.execute_cmd(message): return hour = self.rm_cmd(message) if len(hour) != 0: if not util.is_int(hour): await self.send_message_check(message.channel, "Invalid hour.") return hour = int(hour) if not (0 <= hour <= 23): await self.send_message_check(message.channel, "Invalid hour.") else: self.parent_client.settings.save_user_defaults( notification_time=hour) await self.send_message_check( message.channel, "Birthday messages will be sent at {}:00 EST!".format( hour)) else: self.parent_client.settings.save_user_defaults( notification_time=self.parent_client.settings. default_bot_notification_time) await self.send_message_check( message.channel, "Notification time back to default!")
async def command(self, message: discord.Message): if not self.execute_cmd(message): return skip = self.rm_cmd(message) if len(skip) != 0: if util.is_int(skip): if int(skip) > 0: skip = int(skip) else: skip = 1 else: skip = 1 if self.parent_client.music_handler.is_in_vc(message): if self.parent_client.music_handler.playlist_songs is not None: await self.parent_client.music_handler.next(skip) await self.send_message_check(message.channel, "Next song!") else: await self.send_message_check(message.channel, "There's no playlist on.") else: await self.send_message_check(message.channel, "There's nothing playing.")
def dump_state_variable(self, var): head = self.index.symbol_index[var.symbol] constants = [ arg if util.is_int(arg) else self.index.objects.get_index(arg) for arg in var.args ] return [head, constants]
def _extract_initial_atom_names_and_arguments(self, fd_initial_state): names = [] for atom in fd_initial_state: if isinstance(atom, pddl.Assign): name = atom.fluent.symbol if _check_symbol_in_initial_state(name, self.symbols): args = tuple( int(a) if util.is_int(a) else a for a in atom.fluent.args) value = self.parse_value(atom.expression) names.append((name, args, value)) elif isinstance(atom, pddl.Atom): if atom.negated: raise RuntimeError( "No negations allowed in the initialization of atoms") name = atom.predicate if _check_symbol_in_initial_state(name, self.symbols): names.append((name, atom.args, None)) else: raise RuntimeError( "Unrecognized type of atom '{}'".format(atom)) return names
def on_new_syndicated_post(self, syndpost): """If this source has no username, try to infer one from a syndication URL. Args: syndpost: :class:`models.SyndicatedPost` """ url = syndpost.syndication if self.username or not url: return # FB usernames only have letters, numbers, and periods: # https://www.facebook.com/help/105399436216001 author_id = self.gr_source.base_object({'object': {'url': url}})\ .get('author', {}).get('id') if author_id: if author_id != self.inferred_username and not util.is_int(author_id): logging.info('Inferring username %s from syndication url %s', author_id, url) self.inferred_username = author_id self.put() syndpost.syndication = self.canonicalize_url(syndpost.syndication) elif author_id != self.key.id() and author_id not in self.inferred_user_ids: logging.info('Inferring app-scoped user id %s from syndication url %s', author_id, url) self.inferred_user_ids = util.uniquify(self.inferred_user_ids + [author_id]) self.put() syndpost.syndication = self.canonicalize_url(syndpost.syndication)
def run_simulation(vad, processes): file = "alice.mp3" cpu_count = multiprocessing.cpu_count() if util.is_int(processes): print("assigning " + processes + " processes") processes = int(processes) elif processes.upper() == "MAX": processes = cpu_count else: exit("Invalid processes value") benchmark_name = "processes"+str(processes)+"_vad" + str(vad) logging.info("STARTING BENCHMARK: " + benchmark_name) file_bytes = get_file_bytes(file) t = threading.Thread(target=metrics_logger.logger, args=(benchmark_name + ".log",)) t.start() service = ASRService() result = service.process_audio(file_bytes, "mp3", vad, processes) t.do_run = False t.join() write_results_to_file(benchmark_name + "_result.json", result) logging.info("ENDING BENCHMARK: " + benchmark_name) del file_bytes del service del result
def ant_distance(loc, guide): "Determines ants distance based on level array" y, x = loc if guide[y][x] == 'A': return 0 elif util.is_int(guide[y][x]): return guide[y][x] else: return None
def move_directions(loc, guide): "Returns list sorted by the shortest direction to move" y, x = loc if guide[y][x] == "A": return None surroundings_lookup = surroundings(loc, guide, True) for d in surroundings_lookup: if util.is_int(surroundings_lookup[d]): surroundings_lookup[d] = abs(surroundings_lookup[d]) ###Sets all destinations to zero making them the closest for d in surroundings_lookup: if surroundings_lookup[d] == "D": surroundings_lookup[d] = 0 directions = [] for d in sorted(surroundings_lookup, key=surroundings_lookup.get): if util.is_int(surroundings_lookup[d]): directions.append(d) return directions
def create_comment(self, post_url, author_name, author_url, content): """Creates a new comment in the source silo. Must be implemented by subclasses. Args: post_url: string author_name: string author_url: string content: string Returns: JSON response dict with 'id' and other fields """ if not self.disqus_shortname: resp = util.requests_get(post_url) resp.raise_for_status() self.discover_disqus_shortname(resp.text) if not self.disqus_shortname: raise exc.HTTPBadRequest( "Your Bridgy account isn't fully set up yet: " "we haven't found your Disqus account.") # strip slug, query and fragment from post url parsed = urllib.parse.urlparse(post_url) path = parsed.path.split('/') if not util.is_int(path[-1]): path.pop(-1) post_url = urllib.parse.urlunparse(parsed[:2] + ('/'.join(path), '', '', '')) # get the disqus thread id. details on thread queries: # http://stackoverflow.com/questions/4549282/disqus-api-adding-comment # https://disqus.com/api/docs/threads/details/ resp = self.disqus_call( util.requests_get, DISQUS_API_THREAD_DETAILS_URL, { 'forum': self.disqus_shortname, # ident:[tumblr_post_id] should work, but doesn't :/ 'thread': 'link:%s' % post_url, }) thread_id = resp['id'] # create the comment message = '<a href="%s">%s</a>: %s' % (author_url, author_name, content) resp = self.disqus_call( util.requests_post, DISQUS_API_CREATE_POST_URL, { 'thread': thread_id, 'message': message, # only allowed when authed as moderator/owner # 'state': 'approved', }) return resp
def create_defensive_guide(radius, hills, level): inside_perimeter, destinations = set_defensive_perimeter(int(radius), hills, level) guide = create_guide(destinations, level, depth=5) for point in inside_perimeter: y, x = point if not util.is_int(guide[y][x]): guide[y][x] = -1 else: guide[y][x] = guide[y][x] * -1 return guide, len(destinations)
def setter(self, value: str) -> None: if value: # If value isn't blank, (clearing field) if not is_int(value): # If it isn't a string either print('Could not set number box to [' + value + '].') print(self.valid_options) return # Change value self.entry.clear() self.entry.send_keys(value)
def create_defensive_guide(radius, hills, level, ants): "Creates guide for defensive perimeter" inside_perimeter, destinations = set_defensive_perimeter(int(radius), hills, level) guide, run_status = create_guide(destinations, level, ants, depth=5) for point in inside_perimeter: y, x = point if not util.is_int(guide[y][x]): guide[y][x] = -1 else: guide[y][x] = guide[y][x] * -1 return guide, len(destinations), run_status
def get_level(choose_level, levels, mas): print for i in range(0, len(levels)): print str(i + 1) + ". " + levels[i] # looks like: 1. Novice while not mas: choose_level = raw_input("Choose the number related to the level you would like to play: ") mas = util.is_int(choose_level, [1, 2, 3]) # see if what the user returned is viable if not mas: print "That isn't a 1, 2, or 3....\n" # tell the user to stop messing around skill = levels[int(choose_level) - 1] # assign the level variable to whatever the user chose return skill
def _pre_put_hook(self): """Encode updates['resolved_object_ids'] into resolved_object_ids_json. ...and cap it at MAX_RESOLVED_OBJECT_IDS. """ if self.updates: resolved = self.updates.get("resolved_object_ids") if resolved: keep = heapq.nlargest( MAX_RESOLVED_OBJECT_IDS, (int(id) if util.is_int(id) else id for id in resolved.keys()) ) logging.info("Saving %s resolved Facebook post ids.", len(keep)) self.resolved_object_ids_json = json.dumps({str(id): resolved[str(id)] for id in keep})
def _save_cache(self, name): """Writes resolved_object_ids or post_publics from self.updates to _json.""" if self.updates is None: return assert name in ('resolved_object_ids', 'post_publics') max = globals()['MAX_' + name.upper()] val = self.updates.get(name) if val: keep = heapq.nlargest(max, (int(id) if util.is_int(id) else id for id in val.keys())) setattr(self, name + '_json', json.dumps({str(id): val[str(id)] for id in keep}))
def silo_url(self): """Returns the Facebook account URL, e.g. https://facebook.com/foo. Facebook profile URLS with app-scoped user ids (eg www.facebook.com/ID) no longer work as of April 2018, so if that's all we have, return None instead. https://developers.facebook.com/blog/post/2018/04/19/facebook-login-changes-address-abuse/ """ if self.username or self.inferred_username: return self.gr_source.user_url(self.username or self.inferred_username) for id in [self.key.id()] + self.inferred_user_ids: if util.is_int(id) and int(id) < MIN_APP_SCOPED_ID: return self.gr_source.user_url(id)
def _save_cache(self, name): """Writes resolved_object_ids or post_publics from self.updates to _json.""" if self.updates is None: return assert name in ('resolved_object_ids', 'post_publics') max = globals()['MAX_' + name.upper()] val = self.updates.get(name) if val: keep = heapq.nlargest(max, (int(id) if util.is_int(id) else str(id) for id in val.keys())) setattr(self, name + '_json', json.dumps({str(id): val[str(id)] for id in keep}))
def add(username, password, access_level, restaurant): if (username and password and is_int(access_level) and restaurant): user = User( username = username, password = password, access_level = access_level, token = get_random_string(64), restaurant_id = restaurant.id ) session = get_session() session.add(user) session.commit() return user
def process(): if request.method == 'POST': if util.is_request_underway(): return throw_error_code( 429, "Maximum of one request is permitted at any given time.") if 'file' not in request.files: error = "No File Part" logging.error(error) return throw_error_code(400, "No File Part") file = request.files['file'] if file.filename == '': error = "No selected file" logging.error(error) return throw_error_code(400, error) if file and allowed_file(file.filename): ext = file.filename.rsplit('.', 1)[1].lower() file_bytes = file.read() processes = request.args.get('processes', default="MAX", type=str).upper() cpu_count = multiprocessing.cpu_count() if util.is_int(processes): print("assigning " + processes + " processes") processes = int(processes) if processes > cpu_count: return throw_error_code(400, "Process count must not exceed cpu count of "+ str(cpu_count) + \ " not using the processes argument or assigning it 'MAX' will use the " +\ "maximum processes available") elif processes.upper() == "MAX": processes = cpu_count else: return throw_error_code(400, "Invalid value for arg 'processes'") vad_aggressiveness = request.args.get('vad_aggressiveness', default=1, type=int) if vad_aggressiveness not in [0, 1, 2, 3]: error = "vad_aggressiveness must be an integer between and including 1 and 3" logging.error(error) return throw_error_code(400, error) result = asr.process_audio(file_bytes, ext, vad_aggressiveness, processes) gc.collect() return make_response(jsonify(result), 200)
def create_comment(self, post_url, author_name, author_url, content): """Creates a new comment in the source silo. Must be implemented by subclasses. Args: post_url: string author_name: string author_url: string content: string Returns: JSON response dict with 'id' and other fields """ if not self.disqus_shortname: resp = util.requests_get(post_url) resp.raise_for_status() self.discover_disqus_shortname(resp.text) if not self.disqus_shortname: raise exc.HTTPBadRequest("Your Bridgy account isn't fully set up yet: " "we haven't found your Disqus account.") # strip slug, query and fragment from post url parsed = urlparse.urlparse(post_url) path = parsed.path.split('/') if not util.is_int(path[-1]): path.pop(-1) post_url = urlparse.urlunparse(parsed[:2] + ('/'.join(path), '', '', '')) # get the disqus thread id. details on thread queries: # http://stackoverflow.com/questions/4549282/disqus-api-adding-comment # https://disqus.com/api/docs/threads/details/ resp = self.disqus_call(util.requests_get, DISQUS_API_THREAD_DETAILS_URL, {'forum': self.disqus_shortname, # ident:[tumblr_post_id] should work, but doesn't :/ 'thread': 'link:%s' % post_url, }) thread_id = resp['id'] # create the comment message = '<a href="%s">%s</a>: %s' % (author_url, author_name, content) resp = self.disqus_call(util.requests_post, DISQUS_API_CREATE_POST_URL, {'thread': thread_id, 'message': message.encode('utf-8'), # only allowed when authed as moderator/owner # 'state': 'approved', }) return resp
def choose_spot(self, who): global user_last mas = False move = 0 # winning combinations mentioned earlier: 123, 456, 789, 147, 258, 369, 159, 357 # references represents all of the winning combinations that we have stated above references = [[game_board[0][0], game_board[0][1], game_board[0][2]], [game_board[1][0], game_board[1][1], game_board[1][2]], [game_board[2][0], game_board[2][1], game_board[2][2]], [game_board[0][0], game_board[1][0], game_board[2][0]], [game_board[0][1], game_board[1][1], game_board[2][1]], [game_board[0][2], game_board[0][2], game_board[0][2]], [game_board[0][0], game_board[1][1], game_board[2][2]], [game_board[0][2], game_board[1][1], game_board[2][0]]] if who == "Computer": # this sets the game_mode of the computer based on what the user said earlier if self.game_mode == "Novice": self.beginner() elif self.game_mode == "Intermediate": well = self.defense(references) if not well: self.intermediate() elif self.game_mode == "Expert": # it may not seem like there is much difference between expert and intermediate but # the big thing is, is that expert starts out playing offensively and actually tries # to win if it can done = self.offense(references) if not done: # if the offensive measures didn't do anything just try and block them from winning continue_ = self.defense(references) if not continue_: # if all else fails, just place a coordinate self.intermediate() else: print_board() while not mas: move = raw_input("\nChoose a number that you can see: ") if util.is_int(move, open_moves): move = int(move) user_last = move mas = True else: print "You need to pick from the available numbers...\n" mas = False self.place_tile(move, "user")
def parse_duration(duration): if duration is None: return None if util.is_int(duration): return max(int(duration) * 60, 1) find_duration = re.search('PT(\d+)M([\w.,]+)S', duration) if find_duration is not None: if util.is_float(find_duration.group(2)): return max(int(find_duration.group(1)) * 60 + float(find_duration.group(2)) * 1, 1) find_duration = re.search('PT(\d+)M', duration) if find_duration is not None: return max(int(find_duration.group(1)) * 60, 1) find_duration = re.search('PT(\d+)H(\d+)M', duration) if find_duration is not None: return max(int(find_duration.group(1)) * 3600 + int(find_duration.group(2)) * 60, 1) find_duration = re.search('PT([\w.,]+)S', duration) if find_duration is not None: if util.is_float(find_duration.group(1)): return max(float(find_duration.group(1)) * 1, 1) find_duration = re.search('(\d+):(\d+):(\d+)', duration) if find_duration is not None: return max(int(find_duration.group(1)) * 86400 + int(find_duration.group(2)) * 3600 + int(find_duration.group(3)) * 60, 1) find_duration = re.search('(\d+):(\d+)', duration) if find_duration is not None: return max(int(find_duration.group(1)) * 3600 + int(find_duration.group(2)) * 60, 1) return None
def on_new_syndicated_post(self, syndpost): """If this source has no username, try to infer one from a syndication URL. Args: syndpost: SyndicatedPost """ url = syndpost.syndication if self.username or not url: return # FB usernames only have letters, numbers, and periods: # https://www.facebook.com/help/105399436216001 author_id = self.gr_source.base_object({"object": {"url": url}}).get("author", {}).get("id") if author_id and not util.is_int(author_id): logging.info("Inferring username %s from syndication url %s", author_id, url) self.inferred_username = author_id self.put() syndpost.syndication = self.canonicalize_syndication_url(syndpost.syndication)
def _extract_initial_atom_names_and_arguments(self, fd_initial_state): names = [] for atom in fd_initial_state: if isinstance(atom, pddl.Assign): name = atom.fluent.symbol if _check_symbol_in_initial_state(name, self.symbols): args = tuple(int(a) if util.is_int(a) else a for a in atom.fluent.args) value = self.parse_value(atom.expression) names.append((name, args, value)) elif isinstance(atom, pddl.Atom): if atom.negated: raise RuntimeError("No negations allowed in the initialization of atoms") name = atom.predicate if _check_symbol_in_initial_state(name, self.symbols): names.append((name, atom.args, None)) else: raise RuntimeError("Unrecognized type of atom '{}'".format(atom)) return names
async def command(self, message: discord.Message): if not self.execute_cmd(message): return number = self.rm_cmd(message) if len(number) == 0: output_text = "Volume back to default. " + self.parent_client.music_handler.set_volume( self.parent_client.settings.default_bot_volume) await self.send_message_check(message.channel, output_text) return if util.is_int(number): if 0 <= int(number) <= 100: vol = int(number) / 100 output_text = self.parent_client.music_handler.set_volume(vol) await self.send_message_check(message.channel, output_text) else: await self.send_message_check( message.channel, "Number has to be between 0 and 100.") else: await self.send_message_check(message.channel, "Has to be a number.")
async def command(self, message: discord.Message): if not self.execute_cmd(message): return back = self.rm_cmd(message) if len(back) != 0: if util.is_int(back): if int(back) > 0: back = int(back) else: back = 1 else: back = 1 if self.parent_client.music_handler.is_in_vc(message): if self.parent_client.music_handler.playlist_songs is not None: await self.parent_client.music_handler.previous(back) await self.send_message_check(message.channel, "Previous song!") else: await self.send_message_check(message.channel, "There's no playlist on.") else: await self.send_message_check(message.channel, "There's nothing playing.")
def process_expression(self, exp): """ Process an arbitrary expression """ if isinstance(exp, FunctionalTerm): self.check_declared(exp.symbol) return self.process_functional_expression(exp) elif isinstance(exp, (Atom, NegatedAtom)): self.check_declared(exp.predicate) return self.process_predicative_expression(exp) elif isinstance(exp, ExistentialCondition): # return self.process_existential_expression(exp) return exp elif isinstance(exp, Conjunction): return ConjunctivePredicate(self.process_arguments(exp.parts)) elif isinstance(exp, conditions.Truth): return Truth() elif isinstance(exp, str): if exp[0] == '?': return ParameterExpression(exp) elif is_int(exp): return NumericExpression(exp) else: return ObjectExpression(exp) else: raise ParseException("Unknown expression type for expression '{}'".format(exp))
def load_data(generator, num_docs=None, return_tags=False, return_sent_labels=False): ''' For each document tokenize the words and separate the conglomerate into words and tags. Args ---- generator : Python generator obj that returns the content for each document. num_docs : int / None number of documents to process if None, return all return_tags : boolean if true, tags are returned w/ words in a tuple return_sent_labels : boolean if true, a boolean is returned for whether the token repr. EOS. Returns ------- data : Python generator yields a single token (w/ POS) ''' default_splitter = nltk.data.load('tokenizers/punkt/english.pickle') for (doc_id, doc_con) in generator: if num_docs: # early stop if doc_id > num_docs: break # generate labels using nltk for sentence splitting doc_sents = default_splitter.tokenize(doc_con.strip()) for doc_sent in doc_sents: doc_sent = doc_sent.split() num_tokens_in_sent = len(doc_sent) for cur_token_id, cur_doc_token in enumerate(doc_sent): cur_doc_word, cur_doc_pos = \ nltk.tag.str2tuple(cur_doc_token, sep='/') if cur_doc_pos is None: print "found an item with no tag: {}".format(cur_doc_token) cur_doc_pos = DEFAULT_TAG if util.is_int(cur_doc_pos) or cur_doc_pos == '': cur_doc_pos = DEFAULT_TAG # last token in sentence if cur_token_id == num_tokens_in_sent - 1: cur_sent_label = 1 else: cur_sent_label = 0 if return_tags and return_sent_labels: yield ((cur_doc_word, cur_doc_pos, cur_sent_label)) elif return_tags: yield ((cur_doc_word, cur_doc_pos)) elif return_sent_labels: yield ((cur_doc_word, cur_sent_label)) else: yield cur_doc_word
def serialize_symbol(symbol, table): serialized = symbol if util.is_int(symbol) else table[symbol] return str(serialized)
def test_is_int(): return util.is_int('h')
def make_table(race_no, race_info, table_results, table_awards, table_racecard, bet_info): table = table_results # ----------------- # combine race info # ----------------- for i, row in enumerate(table): if i == 0: table[i].insert(0, "賽道") table[i].insert(0, "場地") table[i].insert(0, "分數範圍") table[i].insert(0, "長度") table[i].insert(0, "班次") table[i].insert(0, "場次") table[i].insert(0, "日期") else: tags = race_info["tag"].split(" - ") y, m, d = util.convert_date(bet_info["date"]) # 賽道 combined = "" if bet_info["place"] == "ST": combined += "田" else: combined += "谷" track = race_info["track"][5:] if track[0] == "草": combined += "草" combined += track.split("\"")[1] else: combined += "泥" table[i].insert(0, combined) # 場地 condition = race_info["cond"][7:] if condition == "好地": table[i].insert(0, "好") elif condition == "好地至快地": table[i].insert(0, "好至快") elif condition == "好地至黏地": table[i].insert(0, "好至黏") elif condition == "濕慢地": table[i].insert(0, "濕慢") else: table[i].insert(0, condition) # 分數範圍 if len(tags) > 2: table[i].insert(0, tags[2]) else: table[i].insert(0, '') # 長度 table[i].insert(0, tags[1]) # 班次 if tags[0][0] == "第": if len(tags[0]) == 3: table[i].insert(0, tags[0][1:2]) else: table[i].insert(0, tags[0][1:2] + "*") elif tags[0][0] == "國": table[i].insert(0, tags[0][2:]) elif tags[0][0] == "條": table[i].insert(0, "*") else: table[i].insert(0, tags[0]) # 場次 table[i].insert(0, race_no) # 日期 table[i].insert(0, "{}/{}/{}".format(y, m, d)) # ---------------- # combine hot info # ---------------- sort_arr = [] for row in table: if util.is_float(row[-1]): sort_arr.append(float(row[-1])) list.sort(sort_arr) hot_flag = False for i, row in enumerate(table): if i == 0: table[i].append("熱門") else: if util.is_float(row[-1]): if math.isclose(float(row[-1]), sort_arr[0], rel_tol=1e-9) and not hot_flag: # 1st hot table[i].append("1st Hot") hot_flag = True elif math.isclose(float(row[-1]), sort_arr[1], rel_tol=1e-9): # 2nd hot table[i].append("2nd Hot") else: table[i].append("-") else: table[i].append("-") # ---------------- # combine bet info # ---------------- have_bet = False thead = table[0] for i, bet in enumerate(bet_info["bet"]): if bet["id"] == race_no: have_bet = True for j, row in enumerate(table): # append bet for this row horse_number = row[thead.index("馬號")] if j == 0: table[j].append("投注") elif not util.is_int(horse_number): table[j].append("-") elif int(horse_number) == bet["WP"]: table[j].append("W P") # see which WP according to number of Bigs if len(bet["Big"]) > 1: for k in range(len(bet["Big"])): table[j][-1] += " Big{}(PQ)".format(k + 1) elif len(bet["Big"]) != 0: table[j][-1] += " Big(PQ)" elif int(horse_number) in bet["Big"]: # see which Big it is if len(bet["Big"]) != 1: for k in range(len(bet["Big"])): if int(horse_number) == bet["Big"][k]: table[j].append("Big{}(PQ)".format(k + 1)) else: table[j].append("Big(PQ)") else: table[j].append("-") if not have_bet: for j, row in enumerate(table): if j == 0: table[j].append("投注") else: table[j].append("-") # --------------------- # combine racecard info # --------------------- thead = table[0] col_horse_no = thead.index("馬號") for i, row in enumerate(table): if i == 0: table[i].append("皇牌") table[i].append("配備") table[i].append("馬齡") table[i].append("評分") table[i].append("評分+/-") else: # print(table_racecard[horse_number]) if row[1] != '' and util.is_int(row[col_horse_no]): horse_number = int(row[col_horse_no]) table[i].append(table_racecard[horse_number][-6]) # 優先參賽次序 table[i].append(table_racecard[horse_number][-5]) # 配備 else: table[i].append('-') table[i].append('-') horse_id = table[i][9].split('(')[1][:-1] table[i].append(get_age(link_horseinfo, horse_id)) # 馬齡 if row[1] != '' and util.is_int(row[col_horse_no]): horse_number = int(row[col_horse_no]) table[i].append(table_racecard[horse_number][10]) # 優先參賽次序 table[i].append(table_racecard[horse_number][11]) # 配備 else: table[i].append('-') table[i].append('-') # ------------------- # combine place & ddy # ------------------- for i, row in enumerate(table): if i == 0: table[i].append("地點") table[i].append("度地儀") else: if bet_info["place"] == "ST": table[i].append("沙田") else: table[i].append("跑馬地") table[i].append(bet_info["ddy"]) # ------------ # combine odds # ------------ for i, row in enumerate(table): if i == 0: table[i].append("P賠率") table[i].append("P賠率2") table[i].append("P賠率3") table[i].append("Queue賠率") table[i].append("PQ賠率") table[i].append("PQ賠率2") table[i].append("PQ賠率3") else: p_awards = table_awards[2][1] q_awards = table_awards[3][1] pq_awards = table_awards[4][1] # P1/2/3 for j in range(len(p_awards)): if p_awards[j][0] == table[i][col_horse_no]: table[i].append(util.str_to_float(p_awards[j][1])) else: table[i].append('') # Queue for j in range(len(q_awards)): horse_number = q_awards[j][0].split(',') if horse_number[0] == table[i][col_horse_no] or horse_number[ 1] == table[i][col_horse_no]: table[i].append(util.str_to_float(q_awards[j][1])) else: table[i].append('') # Pos-Queue for j in range(len(pq_awards)): horse_number = pq_awards[j][0].split(',') if horse_number[0] == table[i][col_horse_no] or horse_number[ 1] == table[i][col_horse_no]: table[i].append(util.str_to_float(pq_awards[j][1])) else: table[i].append('') return table
def test_is_int(self): for arg in 0, 1, -1, '0', '11', 1.0, 12345: self.assertTrue(util.is_int(arg), `arg`) for arg in 0.1, 3.14, '3.0', '3xyz', None, self: self.assertFalse(util.is_int(arg), `arg`)
def make_table(race_no, race_info, table_results, table_awards, table_racecard, bet_info): table = table_results # ----------------- # combine race info # ----------------- for i, row in enumerate(table): if i == 0: table[i].insert(0, "賽道") table[i].insert(0, "場地") table[i].insert(0, "分數範圍") table[i].insert(0, "長度") table[i].insert(0, "班次") table[i].insert(0, "場次") table[i].insert(0, "日期") else: tags = race_info["tag"].split(" - ") y, m, d = util.convert_date(bet_info["date"]) table[i].insert(0, race_info["track"][5:]) table[i].insert(0, race_info["cond"][7:]) # 分數範圍 sometimes does not exist if len(tags) > 2: table[i].insert(0, tags[2]) else: table[i].insert(0, '') table[i].insert(0, tags[1]) table[i].insert(0, tags[0]) table[i].insert(0, race_no) table[i].insert(0, "{}/{}/{}".format(y, m, d)) # ---------------- # combine hot info # ---------------- sort_arr = [] for row in table: if util.is_float(row[-1]): sort_arr.append(float(row[-1])) list.sort(sort_arr) hot_flag = False for i, row in enumerate(table): if i == 0: table[i].append("熱門") else: if util.is_float(row[-1]): if math.isclose(float(row[-1]), sort_arr[0], rel_tol=1e-9) and not hot_flag: # 1st hot table[i].append("1st Hot") hot_flag = True elif math.isclose(float(row[-1]), sort_arr[1], rel_tol=1e-9): # 2nd hot table[i].append("2nd Hot") else: table[i].append("-") else: table[i].append("-") # ---------------- # combine bet info # ---------------- have_bet = False thead = table[0] for i, bet in enumerate(bet_info["bet"]): if bet["id"] == race_no: have_bet = True for j, row in enumerate(table): # append bet for this row horse_number = row[thead.index("馬號")] if j == 0: table[j].append("投注") elif not util.is_int(horse_number): table[j].append("-") elif int(horse_number) == bet["WP"]: table[j].append("W P") # see which WP according to number of Bigs if len(bet["Big"]) > 1: for k in range(len(bet["Big"])): table[j][-1] += " Big{}(PQ)".format(k+1) elif len(bet["Big"]) != 0: table[j][-1] += " Big(PQ)" elif int(horse_number) in bet["Big"]: # see which Big it is if len(bet["Big"]) != 1: for k in range(len(bet["Big"])): if int(horse_number) == bet["Big"][k]: table[j].append("Big{}(PQ)".format(k+1)) else: table[j].append("Big(PQ)") else: table[j].append("-") if not have_bet: for j, row in enumerate(table): if j == 0: table[j].append("投注") else: table[j].append("-") # --------------------- # combine racecard info # --------------------- thead = table[0] col_horse_no = thead.index("馬號") for i, row in enumerate(table): if i == 0: table[i].append("皇牌") table[i].append("配備") table[i].append("操練") else: if row[1] != '' and util.is_int(row[col_horse_no]): horse_number = int(row[col_horse_no]) table[i].append(table_racecard[horse_number][-6]) # 優先參賽次序 table[i].append(table_racecard[horse_number][-5]) # 配備 else: table[i].append('-') table[i].append('-') # TODO TODO TODO table[i].append('') # 操練 # ------------------- # combine place & ddy # ------------------- for i, row in enumerate(table): if i == 0: table[i].append("地點") table[i].append("度地儀") else: if bet_info["place"] == "ST": table[i].append("沙田") else: table[i].append("跑馬地") table[i].append(bet_info["ddy"]) # ------------ # combine odds # ------------ for i, row in enumerate(table): if i == 0: table[i].append("P賠率") table[i].append("P賠率2") table[i].append("P賠率3") table[i].append("Queue賠率") table[i].append("PQ賠率") table[i].append("PQ賠率2") table[i].append("PQ賠率3") else: p_awards = table_awards[2][1] q_awards = table_awards[3][1] pq_awards = table_awards[4][1] # P1/2/3 for j in range(len(p_awards)): if p_awards[j][0] == table[i][col_horse_no]: table[i].append(util.str_to_float(p_awards[j][1])) else: table[i].append('') # Queue for j in range(len(q_awards)): horse_number = q_awards[j][0].split(',') if horse_number[0] == table[i][col_horse_no] or horse_number[1] == table[i][col_horse_no]: table[i].append(util.str_to_float(q_awards[j][1])) else: table[i].append('') # Pos-Queue for j in range(len(pq_awards)): horse_number = pq_awards[j][0].split(',') if horse_number[0] == table[i][col_horse_no] or horse_number[1] == table[i][col_horse_no]: table[i].append(util.str_to_float(pq_awards[j][1])) else: table[i].append('') return table
def handle_command(self, command: str, channel, condition=None): """ Executes bot command if the command is known """ # Default response is help text for the user default_response = "Not sure what you mean." # Finds and executes the given command, filling in response response = "" # Default timestamp timestamp = datetime.datetime.now() # This is where you start to implement more commands! # for handler in task_handlers: # if command.startswith(handler.TASK_COMMAND): # handler.handle_request(command, condition) if command.startswith("next"): response = "next task is {}.".format(self.show_next()) elif command.startswith("done"): commands = command.split(' ') if len(commands) > 1: if is_int(commands[1]): try: target_task = self.task_manager.get_task_by_index(int(commands[1])) response = "{} is done! Well done!\n".format(target_task.description) self.task_manager.done_task(target_task, timestamp) self.task_manager.update_task_list() response += self.show_next() except ValueError as e: response = e.args[0] else: try: self.task_manager.done_task_by_name(commands[1], timestamp) self.task_manager.update_task_list() response = "{} is done! Well done!\n".format(commands[1]) response += self.show_next() except ValueError as e: response = e.args[0] else: self.task_manager.done_task_by_index(0, timestamp) self.task_manager.update_task_list() response = "{} is done! Well done!\n".format(self.displayed_task.description) response += self.show_next() elif command.startswith("postpone"): self.task_manager.postpone(self.displayed_task) response = "postponed {}.\n".format(self.displayed_task.description) response += self.show_next() elif command.startswith("adddaily"): commands = command.split(' ') if len(commands) > 1: if len(commands) > 2 and is_int(commands[2]): frequency = int(commands[2]) else: frequency = 5 gen = {'task_type': 'Unscheduled', 'last_done': datetime.datetime(2018, 9, 16, 12, 30, 0), 'frequency': frequency, 'task': {'priority': 4, 'due': datetime.datetime(2018, 1, 10, 10, 0, 0), 'time_needed': 15, 'description': commands[1], 'time_slot': 'any', 'cancellable': False, 'position': 'home'}} try: self.task_manager.insert_generator(gen) response = "A task {} is added!".format(commands[1]) except: response = "Failed to add task. Something wrong!" elif command.startswith("top"): commands = command.split(' ') length = 10 if len(commands) > 1: try: length = int(commands[1]) except ValueError: length = 10 tasks = self.task_manager.top(length) response = "task list:\n" for index, task in enumerate(tasks): response += "{} {}: {}, {}\n".format(index, task.description, task.priority, task.due.date()) elif command.startswith("task"): print(command) dummy, args = parse_command(['task'], command) print(args) self.task_manager.add_task(args[0]) # Sends the response back to the channel self.slack_client.api_call( "chat.postMessage", channel=channel, text=response or default_response#, # attachments=BUTTON_JSON['attachments'] )
def make_table(race_no, bet_info, race_info, table_awards, table_main): # retrieve awards for easy usage w_awards = table_awards[1][1] p_awards = table_awards[2][1] q_awards = table_awards[3][1] pq_awards = table_awards[4][1] # -------------------------------- # add general info (first 3 lines) # -------------------------------- table = [] table.append(["({}){}".format(race_no, race_info["tag"])]) # win odds, queue odds, !1st hot performance table.append( [util.str_to_float(w_awards[0][1]), util.str_to_float(q_awards[0][1])]) # pos odds, !2nd hot performance for i, pair in enumerate(p_awards): if i == 0: continue table.append([util.str_to_float(p_awards[i][1])]) table[2].append("") # add hot performance H_W, H_Q, H_P, H_L = 0, 0, 0, 0 h_W, h_Q, h_P, h_L = 0, 0, 0, 0 L_W, L_Q, L_P, L_L = 0, 0, 0, 0 thead = table_main[0] for i, row in enumerate(table_main): if i == 0: continue hot = row[thead.index("熱門")] dist = row[thead.index("頭馬距離")] if hot == "1st Hot": if i == 1: H_W += 1 table[1].append("H W + {}".format( table_main[2][thead.index("頭馬距離")])) elif i == 2: H_Q += 1 table[1].append("H Q - {}".format(dist)) elif i == 3: H_P += 1 table[1].append("H P - {}".format(dist)) else: H_L += 1 table[1].append("H {} - {}".format(i, dist)) elif hot == "2nd Hot": if i == 1: h_W += 1 table[2].append("h W + {}".format( table_main[2][thead.index("頭馬距離")])) elif i == 2: h_Q += 1 table[2].append("h Q - {}".format(dist)) elif i == 3: h_P += 1 table[2].append("h P - {}".format(dist)) else: h_L += 1 table[2].append("h {} - {}".format(i, dist)) # ----------------------- # add bet & win/loss info # ----------------------- # init cnt variables total_W, total_P, total_Q, total_PQ = 0, 0, 0, 0 total_result, total_feedback = 0, 0 for bet in bet_info["bet"]: if bet["id"] == race_no: # WP wp_name = "" for i, row in enumerate(table_main): if i == 0: continue if util.is_int(row[thead.index("馬號")]) and bet["WP"] == int( row[thead.index("馬號")]): wp_name = row[thead.index("馬名")][:-6] dist = row[thead.index("頭馬距離")] # WP: append info row table.append([ "{}号 {}".format(bet["WP"], wp_name), '', "W {} P {}".format(bet_info["qty"]["W"], bet_info["qty"]["P"]) ]) # WP: append result row if i == 1: table.append([ '', '', "W + {}".format(table_main[2][thead.index("頭馬距離")]) ]) elif i <= 3: table.append(['', '', "Q - {}".format(dist)]) else: table.append(['', '', "{} - {}".format(i, dist)]) # WP: append win/loss row result, feedback, W, P = calc.wp(wp_no=bet["WP"], qty=bet_info["qty"], table_awards=table_awards, table_main=table_main) table.append(['', '', "${}".format(result)]) total_W += W total_P += P total_result += result total_feedback += feedback # Each Big for big in bet["Big"]: for i, row in enumerate(table_main): if i == 0: continue if util.is_int(row[thead.index("馬號")]) and big == int( row[thead.index("馬號")]): big_name = row[thead.index("馬名")][:-6] dist = row[thead.index("頭馬距離")] # Big: append info row table.append([ "{}号 {} + {}号 {}".format(bet["WP"], wp_name, big, big_name), '', "Q {} PQ {}".format(bet_info["qty"]["Q"], bet_info["qty"]["PQ"]) ]) # Big: append result row if i == 1: table.append([ '', '', "{}号 {} W + {}".format( big, big_name, table_main[2][thead.index("頭馬距離")]) ]) elif i <= 3: table.append([ '', '', "{}号 {} Q - {}".format(big, big_name, dist) ]) else: table.append([ '', '', "{}号 {} {} - {}".format( big, big_name, i, dist) ]) # Big: append win/loss row result, feedback, Q, PQ = calc.big( wp_no=bet["WP"], big_no=big, qty=bet_info["qty"], table_awards=table_awards, table_main=table_main) table.append(['', '', "${}".format(result)]) total_Q += Q total_PQ += PQ total_result += result total_feedback += feedback result_info = { 'result': total_result, 'feedback': total_feedback, 'W-P-Q-PQ': [total_W, total_P, total_Q, total_PQ], 'H': [H_W, H_Q, H_P, H_L], 'h': [h_W, h_Q, h_P, h_L], 'L': [L_W, L_Q, L_P, L_L], } return table, result_info
def __init__(self, symbol, args): self.symbol = symbol self.args = tuple(int(a) if is_int(a) else a for a in args)
def get_problem_id(data): id = data['data']['question']['questionId'] fid = data['data']['question']['questionFrontendId'] if util.is_int(fid): id = fid return id
def dump_state_variable(self, var): head = self.index.symbol_index[var.symbol] constants = [arg if util.is_int(arg) else self.index.objects.get_index(arg) for arg in var.args] return [head, constants]
def main(): parser = OptionParser(usage="usage: %prog [options] filename", version=__version__) parser.add_option("-a", "--autosize", action="store_false", dest="autosize", default=True, help="Disable autosize mode") parser.add_option("-b", "--binmap", action="store", dest="binmap", default=None, help="Binmap should be either 'sbin' or 'hbin'") parser.add_option("-c", "--conf", action="store", dest="user_conf", default=None, help="Load a user configuration file") parser.add_option( "-d", "--demo", action="store", dest="demo", default=None, help= "Generate a Demo WaferMap, integer argument is number of wafers (1-99)" ) parser.add_option("-e", "--theme", action="store", dest="theme", default=None, help="Specify a theme configuration file") parser.add_option("-f", "--flag", action="store_false", dest="flag", default=True, help="Disable flagging multiple die results") parser.add_option( "-g", "--good", action="store", dest="good_die", default=None, help="Specify Good Die Percentage - Applies to Demo ONLY") parser.add_option("-i", "--info", action="store_true", dest="lotinfo", default=None, help="Print Data Summary Info - Does not create map") parser.add_option("-l", "--loglevel", action="store", dest="loglevel", default=None, help="Override default Log Level") parser.add_option("-o", "--output", action="store", dest="outfile", default=None, help="Specify output image file") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="Suppress messages") parser.add_option("-s", "--symbols", action="store_false", dest="symbols", default=True, help="Disable Symbols") parser.add_option( "-t", "--testset", action="store", dest="testset", help="Select testset number - First test is 1, retests are 2,3 ...etc." ) parser.add_option("-v", "--viewer", action="store_true", dest="viewer", default=False, help="Launch MapViewer") parser.add_option("-w", "--wafer", action="store", dest="waferid", default=False, help="Specify a single wafer ID within file") parser.add_option("-x", "--width", action="store", dest="baseWidth", default=None, help="Base Width of map (overrides default)") parser.add_option("-y", "--height", action="store", dest="baseHeight", default=None, help="Base Height of map (overrides default)") parser.add_option("-z", "--dump", action="store_true", dest="dump_lotdata", default=None, help="Dump lot data to screen") (options, args) = parser.parse_args() # Set application default configuration options App.autocfg(options) # Set up logger log = logging.getLogger() default_loglevel = 'logging.' + App.cfg['_loglevel'].upper() log.setLevel(eval(default_loglevel)) if options.loglevel: if options.loglevel.upper() in [ 'NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' ]: logging.getLogger().setLevel(options.loglevel.upper()) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler = logging.handlers.RotatingFileHandler( App.cfg['file']['logfile'], maxBytes=App.cfg['file']['logfile_size'], backupCount=App.cfg['file']['logfile_rotates']) handler.setFormatter(formatter) log.addHandler(handler) # Add a stream handler to print messages to stdout if (options.verbose): ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) log.addHandler(ch) log.info("Configuration information loaded from: {}".format( App.cfg['_config_file'])) pp = pprint.PrettyPrinter(depth=6) if sys.platform == "win32" and args: for arg in args: if '*' in arg: myargs = glob.glob(arg) args.remove(arg) args.extend(myargs) pp.pprint(args) if (args): for eachArg in args: App.cfg['runmode'] = 'stdf' infile = check_infile(eachArg) if infile == None: continue options.infile = infile do_map(options) #Demo = False, make a real map elif options.demo: if not is_int(options.demo, True): parser.error("-d argument must be an integer > 0!") if options.good_die: App.cfg['demo']['random_yield'] = False App.cfg['demo']['fixed_yield'] = float(options.good_die) App.cfg['runmode'] = 'demo' do_map(options) elif options.viewer: mv = Mapviewer() mv.MainLoop() else: #nothing to do parser.print_help() exit(1) for handler in log.handlers: handler.close()
def test_is_int(self): self.assertTrue( util.is_int(self.ione))