id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
244,800
rameshg87/pyremotevbox
pyremotevbox/ZSI/fault.py
FaultFromFaultMessage
def FaultFromFaultMessage(ps): '''Parse the message as a fault. ''' pyobj = ps.Parse(FaultType.typecode) if pyobj.detail == None: detailany = None else: detailany = pyobj.detail.any return Fault(pyobj.faultcode, pyobj.faultstring, pyobj.faultactor, detailany)
python
def FaultFromFaultMessage(ps): '''Parse the message as a fault. ''' pyobj = ps.Parse(FaultType.typecode) if pyobj.detail == None: detailany = None else: detailany = pyobj.detail.any return Fault(pyobj.faultcode, pyobj.faultstring, pyobj.faultactor, detailany)
[ "def", "FaultFromFaultMessage", "(", "ps", ")", ":", "pyobj", "=", "ps", ".", "Parse", "(", "FaultType", ".", "typecode", ")", "if", "pyobj", ".", "detail", "==", "None", ":", "detailany", "=", "None", "else", ":", "detailany", "=", "pyobj", ".", "detail", ".", "any", "return", "Fault", "(", "pyobj", ".", "faultcode", ",", "pyobj", ".", "faultstring", ",", "pyobj", ".", "faultactor", ",", "detailany", ")" ]
Parse the message as a fault.
[ "Parse", "the", "message", "as", "a", "fault", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/fault.py#L250-L259
244,801
rameshg87/pyremotevbox
pyremotevbox/ZSI/fault.py
Fault.serialize
def serialize(self, sw): '''Serialize the object.''' detail = None if self.detail is not None: detail = Detail() detail.any = self.detail pyobj = FaultType(self.code, self.string, self.actor, detail) sw.serialize(pyobj, typed=False)
python
def serialize(self, sw): '''Serialize the object.''' detail = None if self.detail is not None: detail = Detail() detail.any = self.detail pyobj = FaultType(self.code, self.string, self.actor, detail) sw.serialize(pyobj, typed=False)
[ "def", "serialize", "(", "self", ",", "sw", ")", ":", "detail", "=", "None", "if", "self", ".", "detail", "is", "not", "None", ":", "detail", "=", "Detail", "(", ")", "detail", ".", "any", "=", "self", ".", "detail", "pyobj", "=", "FaultType", "(", "self", ".", "code", ",", "self", ".", "string", ",", "self", ".", "actor", ",", "detail", ")", "sw", ".", "serialize", "(", "pyobj", ",", "typed", "=", "False", ")" ]
Serialize the object.
[ "Serialize", "the", "object", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/fault.py#L148-L156
244,802
nefarioustim/parker
parker/parser.py
parse
def parse(page_to_parse): """Return a parse of page.content. Wraps PyQuery.""" global _parsed if not isinstance(page_to_parse, page.Page): raise TypeError("parser.parse requires a parker.Page object.") if page_to_parse.content is None: raise ValueError("parser.parse requires a fetched parker.Page object.") try: parsed = _parsed[page_to_parse] except KeyError: parsed = parsedpage.ParsedPage( page=page_to_parse, parsed=PyQuery(page_to_parse.content, parser='html') ) _parsed[page_to_parse] = parsed return parsed
python
def parse(page_to_parse): """Return a parse of page.content. Wraps PyQuery.""" global _parsed if not isinstance(page_to_parse, page.Page): raise TypeError("parser.parse requires a parker.Page object.") if page_to_parse.content is None: raise ValueError("parser.parse requires a fetched parker.Page object.") try: parsed = _parsed[page_to_parse] except KeyError: parsed = parsedpage.ParsedPage( page=page_to_parse, parsed=PyQuery(page_to_parse.content, parser='html') ) _parsed[page_to_parse] = parsed return parsed
[ "def", "parse", "(", "page_to_parse", ")", ":", "global", "_parsed", "if", "not", "isinstance", "(", "page_to_parse", ",", "page", ".", "Page", ")", ":", "raise", "TypeError", "(", "\"parser.parse requires a parker.Page object.\"", ")", "if", "page_to_parse", ".", "content", "is", "None", ":", "raise", "ValueError", "(", "\"parser.parse requires a fetched parker.Page object.\"", ")", "try", ":", "parsed", "=", "_parsed", "[", "page_to_parse", "]", "except", "KeyError", ":", "parsed", "=", "parsedpage", ".", "ParsedPage", "(", "page", "=", "page_to_parse", ",", "parsed", "=", "PyQuery", "(", "page_to_parse", ".", "content", ",", "parser", "=", "'html'", ")", ")", "_parsed", "[", "page_to_parse", "]", "=", "parsed", "return", "parsed" ]
Return a parse of page.content. Wraps PyQuery.
[ "Return", "a", "parse", "of", "page", ".", "content", ".", "Wraps", "PyQuery", "." ]
ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6
https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/parser.py#L11-L29
244,803
ludeeus/pylaunches
pylaunches/common.py
CommonFunctions.sort_data
async def sort_data(self, data, sort_key, reverse=False): """Sort dataset.""" sorted_data = [] lines = sorted(data, key=lambda k: k[sort_key], reverse=reverse) for line in lines: sorted_data.append(line) return sorted_data
python
async def sort_data(self, data, sort_key, reverse=False): """Sort dataset.""" sorted_data = [] lines = sorted(data, key=lambda k: k[sort_key], reverse=reverse) for line in lines: sorted_data.append(line) return sorted_data
[ "async", "def", "sort_data", "(", "self", ",", "data", ",", "sort_key", ",", "reverse", "=", "False", ")", ":", "sorted_data", "=", "[", "]", "lines", "=", "sorted", "(", "data", ",", "key", "=", "lambda", "k", ":", "k", "[", "sort_key", "]", ",", "reverse", "=", "reverse", ")", "for", "line", "in", "lines", ":", "sorted_data", ".", "append", "(", "line", ")", "return", "sorted_data" ]
Sort dataset.
[ "Sort", "dataset", "." ]
6cc449a9f734cbf789e561564b500a5dca93fe82
https://github.com/ludeeus/pylaunches/blob/6cc449a9f734cbf789e561564b500a5dca93fe82/pylaunches/common.py#L35-L41
244,804
ludeeus/pylaunches
pylaunches/common.py
CommonFunctions.iso
async def iso(self, source): """Convert to timestamp.""" from datetime import datetime unix_timestamp = int(source) return datetime.fromtimestamp(unix_timestamp).isoformat()
python
async def iso(self, source): """Convert to timestamp.""" from datetime import datetime unix_timestamp = int(source) return datetime.fromtimestamp(unix_timestamp).isoformat()
[ "async", "def", "iso", "(", "self", ",", "source", ")", ":", "from", "datetime", "import", "datetime", "unix_timestamp", "=", "int", "(", "source", ")", "return", "datetime", ".", "fromtimestamp", "(", "unix_timestamp", ")", ".", "isoformat", "(", ")" ]
Convert to timestamp.
[ "Convert", "to", "timestamp", "." ]
6cc449a9f734cbf789e561564b500a5dca93fe82
https://github.com/ludeeus/pylaunches/blob/6cc449a9f734cbf789e561564b500a5dca93fe82/pylaunches/common.py#L43-L47
244,805
jgoodlet/punter
punter/api.py
search
def search(api_key, query, offset=0, type='personal'): """Get a list of email addresses for the provided domain. The type of search executed will vary depending on the query provided. Currently this query is restricted to either domain searches, in which the email addresses (and other bits) for the domain are returned, or searches for an email address. The latter is primary meant for checking if an email address exists, although various other useful bits are also provided (for example, the domain where the address was found). :param api_key: Secret client API key. :param query: URL or email address on which to search. :param offset: Specifies the number of emails to skip. :param type: Specifies email type (i.e. generic or personal). """ if not isinstance(api_key, str): raise InvalidAPIKeyException('API key must be a string') if not api_key or len(api_key) < 40: raise InvalidAPIKeyException('Invalid API key.') url = get_endpoint(api_key, query, offset, type) try: return requests.get(url).json() except requests.exceptions.RequestException as err: raise PunterException(err)
python
def search(api_key, query, offset=0, type='personal'): """Get a list of email addresses for the provided domain. The type of search executed will vary depending on the query provided. Currently this query is restricted to either domain searches, in which the email addresses (and other bits) for the domain are returned, or searches for an email address. The latter is primary meant for checking if an email address exists, although various other useful bits are also provided (for example, the domain where the address was found). :param api_key: Secret client API key. :param query: URL or email address on which to search. :param offset: Specifies the number of emails to skip. :param type: Specifies email type (i.e. generic or personal). """ if not isinstance(api_key, str): raise InvalidAPIKeyException('API key must be a string') if not api_key or len(api_key) < 40: raise InvalidAPIKeyException('Invalid API key.') url = get_endpoint(api_key, query, offset, type) try: return requests.get(url).json() except requests.exceptions.RequestException as err: raise PunterException(err)
[ "def", "search", "(", "api_key", ",", "query", ",", "offset", "=", "0", ",", "type", "=", "'personal'", ")", ":", "if", "not", "isinstance", "(", "api_key", ",", "str", ")", ":", "raise", "InvalidAPIKeyException", "(", "'API key must be a string'", ")", "if", "not", "api_key", "or", "len", "(", "api_key", ")", "<", "40", ":", "raise", "InvalidAPIKeyException", "(", "'Invalid API key.'", ")", "url", "=", "get_endpoint", "(", "api_key", ",", "query", ",", "offset", ",", "type", ")", "try", ":", "return", "requests", ".", "get", "(", "url", ")", ".", "json", "(", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "err", ":", "raise", "PunterException", "(", "err", ")" ]
Get a list of email addresses for the provided domain. The type of search executed will vary depending on the query provided. Currently this query is restricted to either domain searches, in which the email addresses (and other bits) for the domain are returned, or searches for an email address. The latter is primary meant for checking if an email address exists, although various other useful bits are also provided (for example, the domain where the address was found). :param api_key: Secret client API key. :param query: URL or email address on which to search. :param offset: Specifies the number of emails to skip. :param type: Specifies email type (i.e. generic or personal).
[ "Get", "a", "list", "of", "email", "addresses", "for", "the", "provided", "domain", "." ]
605ee52a1e5019b360dd643f4bf6861aefa93812
https://github.com/jgoodlet/punter/blob/605ee52a1e5019b360dd643f4bf6861aefa93812/punter/api.py#L10-L38
244,806
LesPatamechanix/patalib
src/patalib/clinamen.py
Clinamen.generate_clinamen
def generate_clinamen(self, input_word, list_of_dict_words, swerve): """ Generate a clinamen. Here we looks for words via the damerau levenshtein distance with a distance of 2. """ results = [] selected_list = [] for i in list_of_dict_words: #produce a subset for efficency if len(i) < len(input_word)+1 and len(i) > len(input_word)/2: if '_' not in i: selected_list.append(i) for i in selected_list: match = self.damerau_levenshtein_distance(input_word,i) if match == swerve: results.append(i) results = {'input' : input_word, 'results' : results, 'category' : 'clinamen'} return results
python
def generate_clinamen(self, input_word, list_of_dict_words, swerve): """ Generate a clinamen. Here we looks for words via the damerau levenshtein distance with a distance of 2. """ results = [] selected_list = [] for i in list_of_dict_words: #produce a subset for efficency if len(i) < len(input_word)+1 and len(i) > len(input_word)/2: if '_' not in i: selected_list.append(i) for i in selected_list: match = self.damerau_levenshtein_distance(input_word,i) if match == swerve: results.append(i) results = {'input' : input_word, 'results' : results, 'category' : 'clinamen'} return results
[ "def", "generate_clinamen", "(", "self", ",", "input_word", ",", "list_of_dict_words", ",", "swerve", ")", ":", "results", "=", "[", "]", "selected_list", "=", "[", "]", "for", "i", "in", "list_of_dict_words", ":", "#produce a subset for efficency", "if", "len", "(", "i", ")", "<", "len", "(", "input_word", ")", "+", "1", "and", "len", "(", "i", ")", ">", "len", "(", "input_word", ")", "/", "2", ":", "if", "'_'", "not", "in", "i", ":", "selected_list", ".", "append", "(", "i", ")", "for", "i", "in", "selected_list", ":", "match", "=", "self", ".", "damerau_levenshtein_distance", "(", "input_word", ",", "i", ")", "if", "match", "==", "swerve", ":", "results", ".", "append", "(", "i", ")", "results", "=", "{", "'input'", ":", "input_word", ",", "'results'", ":", "results", ",", "'category'", ":", "'clinamen'", "}", "return", "results" ]
Generate a clinamen. Here we looks for words via the damerau levenshtein distance with a distance of 2.
[ "Generate", "a", "clinamen", ".", "Here", "we", "looks", "for", "words", "via", "the", "damerau", "levenshtein", "distance", "with", "a", "distance", "of", "2", "." ]
d88cca409b1750fdeb88cece048b308f2a710955
https://github.com/LesPatamechanix/patalib/blob/d88cca409b1750fdeb88cece048b308f2a710955/src/patalib/clinamen.py#L8-L25
244,807
chairbender/fantasy-football-auction
fantasy_football_auction/auction.py
Auction.tick
def tick(self): """ Advances time in the game. Use this once all "choices" have been submitted for the current game state using the other methods. """ if self.state == AuctionState.NOMINATE: # if no nominee submitted, exception if self.nominee is None: raise InvalidActionError("Tick was invoked during nomination but no nominee was selected.") self.state = AuctionState.BID # initialize bids array to hold each owner's bid # this holds the latest bids submitted for the current bidding phase self.bids = [self.bid if i == self.turn_index else 0 for i in range(len(self.owners))] # this holds the bids submitted on a given tick self.tickbids = [0] * len(self.owners) elif self.state == AuctionState.BID: # If no new bids submitted, we're done with this bid and the player gets what they bid for if not any(bid > 0 for bid in self.tickbids): winner = self._winning_owner() winner.buy(self.nominee, self.bid) self._player_ownership[self._nominee_index] = self.winning_owner_index() self.undrafted_players.remove(self.nominee) self.nominee = None self._nominee_index = -1 # check if we're done, or move to the next player who still has space done = True for i in range(len(self.owners)): next_turn = (self.turn_index + 1 + i) % len(self.owners) if self.owners[next_turn].remaining_picks() > 0: self.turn_index = next_turn done = False break # if we didn't move on, we're done if done: self.state = AuctionState.DONE else: self.state = AuctionState.NOMINATE else: # new bids have been submitted, # randomly pick the bid to accept from the highest, # then everyone gets a chance to submit more top_idxs = [i for i, bid in enumerate(self.tickbids) if bid == max(self.tickbids)] accept_idx = random.choice(top_idxs) # set this as the new bid self.bid = self.tickbids[accept_idx] # update the bids for this round self.bids[accept_idx] = self.bid # clear this for the next tick self.tickbids = [0] * len(self.owners)
python
def tick(self): """ Advances time in the game. Use this once all "choices" have been submitted for the current game state using the other methods. """ if self.state == AuctionState.NOMINATE: # if no nominee submitted, exception if self.nominee is None: raise InvalidActionError("Tick was invoked during nomination but no nominee was selected.") self.state = AuctionState.BID # initialize bids array to hold each owner's bid # this holds the latest bids submitted for the current bidding phase self.bids = [self.bid if i == self.turn_index else 0 for i in range(len(self.owners))] # this holds the bids submitted on a given tick self.tickbids = [0] * len(self.owners) elif self.state == AuctionState.BID: # If no new bids submitted, we're done with this bid and the player gets what they bid for if not any(bid > 0 for bid in self.tickbids): winner = self._winning_owner() winner.buy(self.nominee, self.bid) self._player_ownership[self._nominee_index] = self.winning_owner_index() self.undrafted_players.remove(self.nominee) self.nominee = None self._nominee_index = -1 # check if we're done, or move to the next player who still has space done = True for i in range(len(self.owners)): next_turn = (self.turn_index + 1 + i) % len(self.owners) if self.owners[next_turn].remaining_picks() > 0: self.turn_index = next_turn done = False break # if we didn't move on, we're done if done: self.state = AuctionState.DONE else: self.state = AuctionState.NOMINATE else: # new bids have been submitted, # randomly pick the bid to accept from the highest, # then everyone gets a chance to submit more top_idxs = [i for i, bid in enumerate(self.tickbids) if bid == max(self.tickbids)] accept_idx = random.choice(top_idxs) # set this as the new bid self.bid = self.tickbids[accept_idx] # update the bids for this round self.bids[accept_idx] = self.bid # clear this for the next tick self.tickbids = [0] * len(self.owners)
[ "def", "tick", "(", "self", ")", ":", "if", "self", ".", "state", "==", "AuctionState", ".", "NOMINATE", ":", "# if no nominee submitted, exception", "if", "self", ".", "nominee", "is", "None", ":", "raise", "InvalidActionError", "(", "\"Tick was invoked during nomination but no nominee was selected.\"", ")", "self", ".", "state", "=", "AuctionState", ".", "BID", "# initialize bids array to hold each owner's bid", "# this holds the latest bids submitted for the current bidding phase", "self", ".", "bids", "=", "[", "self", ".", "bid", "if", "i", "==", "self", ".", "turn_index", "else", "0", "for", "i", "in", "range", "(", "len", "(", "self", ".", "owners", ")", ")", "]", "# this holds the bids submitted on a given tick", "self", ".", "tickbids", "=", "[", "0", "]", "*", "len", "(", "self", ".", "owners", ")", "elif", "self", ".", "state", "==", "AuctionState", ".", "BID", ":", "# If no new bids submitted, we're done with this bid and the player gets what they bid for", "if", "not", "any", "(", "bid", ">", "0", "for", "bid", "in", "self", ".", "tickbids", ")", ":", "winner", "=", "self", ".", "_winning_owner", "(", ")", "winner", ".", "buy", "(", "self", ".", "nominee", ",", "self", ".", "bid", ")", "self", ".", "_player_ownership", "[", "self", ".", "_nominee_index", "]", "=", "self", ".", "winning_owner_index", "(", ")", "self", ".", "undrafted_players", ".", "remove", "(", "self", ".", "nominee", ")", "self", ".", "nominee", "=", "None", "self", ".", "_nominee_index", "=", "-", "1", "# check if we're done, or move to the next player who still has space", "done", "=", "True", "for", "i", "in", "range", "(", "len", "(", "self", ".", "owners", ")", ")", ":", "next_turn", "=", "(", "self", ".", "turn_index", "+", "1", "+", "i", ")", "%", "len", "(", "self", ".", "owners", ")", "if", "self", ".", "owners", "[", "next_turn", "]", ".", "remaining_picks", "(", ")", ">", "0", ":", "self", ".", "turn_index", "=", "next_turn", "done", "=", "False", "break", "# if we didn't move on, we're done", "if", "done", ":", "self", ".", "state", "=", "AuctionState", ".", "DONE", "else", ":", "self", ".", "state", "=", "AuctionState", ".", "NOMINATE", "else", ":", "# new bids have been submitted,", "# randomly pick the bid to accept from the highest,", "# then everyone gets a chance to submit more", "top_idxs", "=", "[", "i", "for", "i", ",", "bid", "in", "enumerate", "(", "self", ".", "tickbids", ")", "if", "bid", "==", "max", "(", "self", ".", "tickbids", ")", "]", "accept_idx", "=", "random", ".", "choice", "(", "top_idxs", ")", "# set this as the new bid", "self", ".", "bid", "=", "self", ".", "tickbids", "[", "accept_idx", "]", "# update the bids for this round", "self", ".", "bids", "[", "accept_idx", "]", "=", "self", ".", "bid", "# clear this for the next tick", "self", ".", "tickbids", "=", "[", "0", "]", "*", "len", "(", "self", ".", "owners", ")" ]
Advances time in the game. Use this once all "choices" have been submitted for the current game state using the other methods.
[ "Advances", "time", "in", "the", "game", ".", "Use", "this", "once", "all", "choices", "have", "been", "submitted", "for", "the", "current", "game", "state", "using", "the", "other", "methods", "." ]
f54868691ea37691c378b0a05b6b3280c2cbba11
https://github.com/chairbender/fantasy-football-auction/blob/f54868691ea37691c378b0a05b6b3280c2cbba11/fantasy_football_auction/auction.py#L129-L177
244,808
chairbender/fantasy-football-auction
fantasy_football_auction/auction.py
Auction.nominate
def nominate(self, owner_id, player_idx, bid): """ Nominates the player for auctioning. :param int owner_id: index of the owner who is nominating :param int player_idx: index of the player to nominate in the players list :param int bid: starting bid :raise InvalidActionError: if the action is not allowed according to the rules. See the error message for details. """ owner = self.owners[owner_id] nominated_player = self.players[player_idx] if self.state != AuctionState.NOMINATE: raise InvalidActionError("Owner " + str(owner_id) + " tried to nominate, but Auction state " "is not NOMINATE, so nomination is not allowed") elif self.turn_index != owner_id: raise InvalidActionError("Owner " + str(owner_id) + " tried to nominate, but it is currently " + str(self.turn_index) + "'s turn") elif nominated_player not in self.undrafted_players: raise InvalidActionError("Owner " + str(owner_id) + "tried to nominate the player with index " + str(player_idx) + ", named " + nominated_player.name + ", but they have already been purchased and cannot be nominated.") elif bid > owner.max_bid(): raise InvalidActionError("Bid amount was " + str(bid) + " but this owner (Owner " + str(owner_id) + " can only bid a maximum of " + str(owner.max_bid())) elif bid < 1: raise InvalidActionError("Owner " + str(owner_id) + "'s bid amount was " + str(bid) + " but must be greater than 1") elif not owner.can_buy(nominated_player, bid): raise InvalidActionError("Owner " + str(owner_id) + " cannot make this nomination for player with index " + str(player_idx) + ", named " + nominated_player.name + ", because they cannot slot or cannot" " afford the player for the specified bid amount") # nomination successful, bidding time self.nominee = nominated_player self._nominee_index = player_idx self.bid = bid self.tickbids[owner_id] = bid
python
def nominate(self, owner_id, player_idx, bid): """ Nominates the player for auctioning. :param int owner_id: index of the owner who is nominating :param int player_idx: index of the player to nominate in the players list :param int bid: starting bid :raise InvalidActionError: if the action is not allowed according to the rules. See the error message for details. """ owner = self.owners[owner_id] nominated_player = self.players[player_idx] if self.state != AuctionState.NOMINATE: raise InvalidActionError("Owner " + str(owner_id) + " tried to nominate, but Auction state " "is not NOMINATE, so nomination is not allowed") elif self.turn_index != owner_id: raise InvalidActionError("Owner " + str(owner_id) + " tried to nominate, but it is currently " + str(self.turn_index) + "'s turn") elif nominated_player not in self.undrafted_players: raise InvalidActionError("Owner " + str(owner_id) + "tried to nominate the player with index " + str(player_idx) + ", named " + nominated_player.name + ", but they have already been purchased and cannot be nominated.") elif bid > owner.max_bid(): raise InvalidActionError("Bid amount was " + str(bid) + " but this owner (Owner " + str(owner_id) + " can only bid a maximum of " + str(owner.max_bid())) elif bid < 1: raise InvalidActionError("Owner " + str(owner_id) + "'s bid amount was " + str(bid) + " but must be greater than 1") elif not owner.can_buy(nominated_player, bid): raise InvalidActionError("Owner " + str(owner_id) + " cannot make this nomination for player with index " + str(player_idx) + ", named " + nominated_player.name + ", because they cannot slot or cannot" " afford the player for the specified bid amount") # nomination successful, bidding time self.nominee = nominated_player self._nominee_index = player_idx self.bid = bid self.tickbids[owner_id] = bid
[ "def", "nominate", "(", "self", ",", "owner_id", ",", "player_idx", ",", "bid", ")", ":", "owner", "=", "self", ".", "owners", "[", "owner_id", "]", "nominated_player", "=", "self", ".", "players", "[", "player_idx", "]", "if", "self", ".", "state", "!=", "AuctionState", ".", "NOMINATE", ":", "raise", "InvalidActionError", "(", "\"Owner \"", "+", "str", "(", "owner_id", ")", "+", "\" tried to nominate, but Auction state \"", "\"is not NOMINATE, so nomination is not allowed\"", ")", "elif", "self", ".", "turn_index", "!=", "owner_id", ":", "raise", "InvalidActionError", "(", "\"Owner \"", "+", "str", "(", "owner_id", ")", "+", "\" tried to nominate, but it is currently \"", "+", "str", "(", "self", ".", "turn_index", ")", "+", "\"'s turn\"", ")", "elif", "nominated_player", "not", "in", "self", ".", "undrafted_players", ":", "raise", "InvalidActionError", "(", "\"Owner \"", "+", "str", "(", "owner_id", ")", "+", "\"tried to nominate the player with index \"", "+", "str", "(", "player_idx", ")", "+", "\", named \"", "+", "nominated_player", ".", "name", "+", "\", but they have already been purchased and cannot be nominated.\"", ")", "elif", "bid", ">", "owner", ".", "max_bid", "(", ")", ":", "raise", "InvalidActionError", "(", "\"Bid amount was \"", "+", "str", "(", "bid", ")", "+", "\" but this owner (Owner \"", "+", "str", "(", "owner_id", ")", "+", "\" can only bid a maximum of \"", "+", "str", "(", "owner", ".", "max_bid", "(", ")", ")", ")", "elif", "bid", "<", "1", ":", "raise", "InvalidActionError", "(", "\"Owner \"", "+", "str", "(", "owner_id", ")", "+", "\"'s bid amount was \"", "+", "str", "(", "bid", ")", "+", "\" but must be greater than 1\"", ")", "elif", "not", "owner", ".", "can_buy", "(", "nominated_player", ",", "bid", ")", ":", "raise", "InvalidActionError", "(", "\"Owner \"", "+", "str", "(", "owner_id", ")", "+", "\" cannot make this nomination for player with index \"", "+", "str", "(", "player_idx", ")", "+", "\", named \"", "+", "nominated_player", ".", "name", "+", "\", because they cannot slot or cannot\"", "\" afford the player for the specified bid amount\"", ")", "# nomination successful, bidding time", "self", ".", "nominee", "=", "nominated_player", "self", ".", "_nominee_index", "=", "player_idx", "self", ".", "bid", "=", "bid", "self", ".", "tickbids", "[", "owner_id", "]", "=", "bid" ]
Nominates the player for auctioning. :param int owner_id: index of the owner who is nominating :param int player_idx: index of the player to nominate in the players list :param int bid: starting bid :raise InvalidActionError: if the action is not allowed according to the rules. See the error message for details.
[ "Nominates", "the", "player", "for", "auctioning", "." ]
f54868691ea37691c378b0a05b6b3280c2cbba11
https://github.com/chairbender/fantasy-football-auction/blob/f54868691ea37691c378b0a05b6b3280c2cbba11/fantasy_football_auction/auction.py#L204-L247
244,809
sassoo/goldman
goldman/resources/oauth_ropc.py
Resource.on_post
def on_post(self, req, resp): """ Validate the access token request for spec compliance The spec also dictates the JSON based error response on failure & is handled in this responder. """ grant_type = req.get_param('grant_type') password = req.get_param('password') username = req.get_param('username') # errors or not, disable client caching along the way # per the spec resp.disable_caching() if not grant_type or not password or not username: resp.status = falcon.HTTP_400 resp.serialize({ 'error': 'invalid_request', 'error_description': 'A grant_type, username, & password ' 'parameters are all required when ' 'requesting an OAuth access_token', 'error_uri': 'tools.ietf.org/html/rfc6749#section-4.3.2', }) elif grant_type != 'password': resp.status = falcon.HTTP_400 resp.serialize({ 'error': 'unsupported_grant_type', 'error_description': 'The grant_type parameter MUST be set ' 'to "password" not "%s"' % grant_type, 'error_uri': 'tools.ietf.org/html/rfc6749#section-4.3.2', }) else: try: token = self.auth_creds(username, password) resp.serialize({ 'access_token': token, 'token_type': 'Bearer', }) except AuthRejected as exc: resp.status = falcon.HTTP_401 resp.set_header('WWW-Authenticate', self._realm) resp.serialize({ 'error': 'invalid_client', 'error_description': exc.detail, })
python
def on_post(self, req, resp): """ Validate the access token request for spec compliance The spec also dictates the JSON based error response on failure & is handled in this responder. """ grant_type = req.get_param('grant_type') password = req.get_param('password') username = req.get_param('username') # errors or not, disable client caching along the way # per the spec resp.disable_caching() if not grant_type or not password or not username: resp.status = falcon.HTTP_400 resp.serialize({ 'error': 'invalid_request', 'error_description': 'A grant_type, username, & password ' 'parameters are all required when ' 'requesting an OAuth access_token', 'error_uri': 'tools.ietf.org/html/rfc6749#section-4.3.2', }) elif grant_type != 'password': resp.status = falcon.HTTP_400 resp.serialize({ 'error': 'unsupported_grant_type', 'error_description': 'The grant_type parameter MUST be set ' 'to "password" not "%s"' % grant_type, 'error_uri': 'tools.ietf.org/html/rfc6749#section-4.3.2', }) else: try: token = self.auth_creds(username, password) resp.serialize({ 'access_token': token, 'token_type': 'Bearer', }) except AuthRejected as exc: resp.status = falcon.HTTP_401 resp.set_header('WWW-Authenticate', self._realm) resp.serialize({ 'error': 'invalid_client', 'error_description': exc.detail, })
[ "def", "on_post", "(", "self", ",", "req", ",", "resp", ")", ":", "grant_type", "=", "req", ".", "get_param", "(", "'grant_type'", ")", "password", "=", "req", ".", "get_param", "(", "'password'", ")", "username", "=", "req", ".", "get_param", "(", "'username'", ")", "# errors or not, disable client caching along the way", "# per the spec", "resp", ".", "disable_caching", "(", ")", "if", "not", "grant_type", "or", "not", "password", "or", "not", "username", ":", "resp", ".", "status", "=", "falcon", ".", "HTTP_400", "resp", ".", "serialize", "(", "{", "'error'", ":", "'invalid_request'", ",", "'error_description'", ":", "'A grant_type, username, & password '", "'parameters are all required when '", "'requesting an OAuth access_token'", ",", "'error_uri'", ":", "'tools.ietf.org/html/rfc6749#section-4.3.2'", ",", "}", ")", "elif", "grant_type", "!=", "'password'", ":", "resp", ".", "status", "=", "falcon", ".", "HTTP_400", "resp", ".", "serialize", "(", "{", "'error'", ":", "'unsupported_grant_type'", ",", "'error_description'", ":", "'The grant_type parameter MUST be set '", "'to \"password\" not \"%s\"'", "%", "grant_type", ",", "'error_uri'", ":", "'tools.ietf.org/html/rfc6749#section-4.3.2'", ",", "}", ")", "else", ":", "try", ":", "token", "=", "self", ".", "auth_creds", "(", "username", ",", "password", ")", "resp", ".", "serialize", "(", "{", "'access_token'", ":", "token", ",", "'token_type'", ":", "'Bearer'", ",", "}", ")", "except", "AuthRejected", "as", "exc", ":", "resp", ".", "status", "=", "falcon", ".", "HTTP_401", "resp", ".", "set_header", "(", "'WWW-Authenticate'", ",", "self", ".", "_realm", ")", "resp", ".", "serialize", "(", "{", "'error'", ":", "'invalid_client'", ",", "'error_description'", ":", "exc", ".", "detail", ",", "}", ")" ]
Validate the access token request for spec compliance The spec also dictates the JSON based error response on failure & is handled in this responder.
[ "Validate", "the", "access", "token", "request", "for", "spec", "compliance" ]
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/resources/oauth_ropc.py#L52-L97
244,810
LesPatamechanix/patalib
src/patalib/anomaly.py
Anomaly.generate_anomaly
def generate_anomaly(self, input_word, list_of_dict_words, num): """ Generate an anomaly. This is done via a Psuedo-random number generator. """ results = [] for i in range(0,num): index = randint(0,len(list_of_dict_words)-1) name = list_of_dict_words[index] if name != input_word and name not in results: results.append(PataLib().strip_underscore(name)) else: i = i +1 results = {'input' : input_word, 'results' : results, 'category' : 'anomaly'} return results
python
def generate_anomaly(self, input_word, list_of_dict_words, num): """ Generate an anomaly. This is done via a Psuedo-random number generator. """ results = [] for i in range(0,num): index = randint(0,len(list_of_dict_words)-1) name = list_of_dict_words[index] if name != input_word and name not in results: results.append(PataLib().strip_underscore(name)) else: i = i +1 results = {'input' : input_word, 'results' : results, 'category' : 'anomaly'} return results
[ "def", "generate_anomaly", "(", "self", ",", "input_word", ",", "list_of_dict_words", ",", "num", ")", ":", "results", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "num", ")", ":", "index", "=", "randint", "(", "0", ",", "len", "(", "list_of_dict_words", ")", "-", "1", ")", "name", "=", "list_of_dict_words", "[", "index", "]", "if", "name", "!=", "input_word", "and", "name", "not", "in", "results", ":", "results", ".", "append", "(", "PataLib", "(", ")", ".", "strip_underscore", "(", "name", ")", ")", "else", ":", "i", "=", "i", "+", "1", "results", "=", "{", "'input'", ":", "input_word", ",", "'results'", ":", "results", ",", "'category'", ":", "'anomaly'", "}", "return", "results" ]
Generate an anomaly. This is done via a Psuedo-random number generator.
[ "Generate", "an", "anomaly", ".", "This", "is", "done", "via", "a", "Psuedo", "-", "random", "number", "generator", "." ]
d88cca409b1750fdeb88cece048b308f2a710955
https://github.com/LesPatamechanix/patalib/blob/d88cca409b1750fdeb88cece048b308f2a710955/src/patalib/anomaly.py#L9-L23
244,811
glue-viz/echo
echo/qt/connect.py
connect_checkable_button
def connect_checkable_button(instance, prop, widget): """ Connect a boolean callback property with a Qt button widget. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setChecked`` method and the ``toggled`` signal. """ add_callback(instance, prop, widget.setChecked) widget.toggled.connect(partial(setattr, instance, prop)) widget.setChecked(getattr(instance, prop) or False)
python
def connect_checkable_button(instance, prop, widget): """ Connect a boolean callback property with a Qt button widget. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setChecked`` method and the ``toggled`` signal. """ add_callback(instance, prop, widget.setChecked) widget.toggled.connect(partial(setattr, instance, prop)) widget.setChecked(getattr(instance, prop) or False)
[ "def", "connect_checkable_button", "(", "instance", ",", "prop", ",", "widget", ")", ":", "add_callback", "(", "instance", ",", "prop", ",", "widget", ".", "setChecked", ")", "widget", ".", "toggled", ".", "connect", "(", "partial", "(", "setattr", ",", "instance", ",", "prop", ")", ")", "widget", ".", "setChecked", "(", "getattr", "(", "instance", ",", "prop", ")", "or", "False", ")" ]
Connect a boolean callback property with a Qt button widget. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setChecked`` method and the ``toggled`` signal.
[ "Connect", "a", "boolean", "callback", "property", "with", "a", "Qt", "button", "widget", "." ]
6ad54cc5e869de27c34e8716f2619ddc640f08fe
https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L20-L36
244,812
glue-viz/echo
echo/qt/connect.py
connect_text
def connect_text(instance, prop, widget): """ Connect a string callback property with a Qt widget containing text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. """ def update_prop(): val = widget.text() setattr(instance, prop, val) def update_widget(val): if hasattr(widget, 'editingFinished'): widget.blockSignals(True) widget.setText(val) widget.blockSignals(False) widget.editingFinished.emit() else: widget.setText(val) add_callback(instance, prop, update_widget) try: widget.editingFinished.connect(update_prop) except AttributeError: pass update_widget(getattr(instance, prop))
python
def connect_text(instance, prop, widget): """ Connect a string callback property with a Qt widget containing text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. """ def update_prop(): val = widget.text() setattr(instance, prop, val) def update_widget(val): if hasattr(widget, 'editingFinished'): widget.blockSignals(True) widget.setText(val) widget.blockSignals(False) widget.editingFinished.emit() else: widget.setText(val) add_callback(instance, prop, update_widget) try: widget.editingFinished.connect(update_prop) except AttributeError: pass update_widget(getattr(instance, prop))
[ "def", "connect_text", "(", "instance", ",", "prop", ",", "widget", ")", ":", "def", "update_prop", "(", ")", ":", "val", "=", "widget", ".", "text", "(", ")", "setattr", "(", "instance", ",", "prop", ",", "val", ")", "def", "update_widget", "(", "val", ")", ":", "if", "hasattr", "(", "widget", ",", "'editingFinished'", ")", ":", "widget", ".", "blockSignals", "(", "True", ")", "widget", ".", "setText", "(", "val", ")", "widget", ".", "blockSignals", "(", "False", ")", "widget", ".", "editingFinished", ".", "emit", "(", ")", "else", ":", "widget", ".", "setText", "(", "val", ")", "add_callback", "(", "instance", ",", "prop", ",", "update_widget", ")", "try", ":", "widget", ".", "editingFinished", ".", "connect", "(", "update_prop", ")", "except", "AttributeError", ":", "pass", "update_widget", "(", "getattr", "(", "instance", ",", "prop", ")", ")" ]
Connect a string callback property with a Qt widget containing text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal.
[ "Connect", "a", "string", "callback", "property", "with", "a", "Qt", "widget", "containing", "text", "." ]
6ad54cc5e869de27c34e8716f2619ddc640f08fe
https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L39-L74
244,813
glue-viz/echo
echo/qt/connect.py
connect_combo_data
def connect_combo_data(instance, prop, widget): """ Connect a callback property with a QComboBox widget based on the userData. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QComboBox The combo box to connect. See Also -------- connect_combo_text: connect a callback property with a QComboBox widget based on the text. """ def update_widget(value): try: idx = _find_combo_data(widget, value) except ValueError: if value is None: idx = -1 else: raise widget.setCurrentIndex(idx) def update_prop(idx): if idx == -1: setattr(instance, prop, None) else: setattr(instance, prop, widget.itemData(idx)) add_callback(instance, prop, update_widget) widget.currentIndexChanged.connect(update_prop) update_widget(getattr(instance, prop))
python
def connect_combo_data(instance, prop, widget): """ Connect a callback property with a QComboBox widget based on the userData. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QComboBox The combo box to connect. See Also -------- connect_combo_text: connect a callback property with a QComboBox widget based on the text. """ def update_widget(value): try: idx = _find_combo_data(widget, value) except ValueError: if value is None: idx = -1 else: raise widget.setCurrentIndex(idx) def update_prop(idx): if idx == -1: setattr(instance, prop, None) else: setattr(instance, prop, widget.itemData(idx)) add_callback(instance, prop, update_widget) widget.currentIndexChanged.connect(update_prop) update_widget(getattr(instance, prop))
[ "def", "connect_combo_data", "(", "instance", ",", "prop", ",", "widget", ")", ":", "def", "update_widget", "(", "value", ")", ":", "try", ":", "idx", "=", "_find_combo_data", "(", "widget", ",", "value", ")", "except", "ValueError", ":", "if", "value", "is", "None", ":", "idx", "=", "-", "1", "else", ":", "raise", "widget", ".", "setCurrentIndex", "(", "idx", ")", "def", "update_prop", "(", "idx", ")", ":", "if", "idx", "==", "-", "1", ":", "setattr", "(", "instance", ",", "prop", ",", "None", ")", "else", ":", "setattr", "(", "instance", ",", "prop", ",", "widget", ".", "itemData", "(", "idx", ")", ")", "add_callback", "(", "instance", ",", "prop", ",", "update_widget", ")", "widget", ".", "currentIndexChanged", ".", "connect", "(", "update_prop", ")", "update_widget", "(", "getattr", "(", "instance", ",", "prop", ")", ")" ]
Connect a callback property with a QComboBox widget based on the userData. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QComboBox The combo box to connect. See Also -------- connect_combo_text: connect a callback property with a QComboBox widget based on the text.
[ "Connect", "a", "callback", "property", "with", "a", "QComboBox", "widget", "based", "on", "the", "userData", "." ]
6ad54cc5e869de27c34e8716f2619ddc640f08fe
https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L77-L114
244,814
glue-viz/echo
echo/qt/connect.py
connect_combo_text
def connect_combo_text(instance, prop, widget): """ Connect a callback property with a QComboBox widget based on the text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QComboBox The combo box to connect. See Also -------- connect_combo_data: connect a callback property with a QComboBox widget based on the userData. """ def update_widget(value): try: idx = _find_combo_text(widget, value) except ValueError: if value is None: idx = -1 else: raise widget.setCurrentIndex(idx) def update_prop(idx): if idx == -1: setattr(instance, prop, None) else: setattr(instance, prop, widget.itemText(idx)) add_callback(instance, prop, update_widget) widget.currentIndexChanged.connect(update_prop) update_widget(getattr(instance, prop))
python
def connect_combo_text(instance, prop, widget): """ Connect a callback property with a QComboBox widget based on the text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QComboBox The combo box to connect. See Also -------- connect_combo_data: connect a callback property with a QComboBox widget based on the userData. """ def update_widget(value): try: idx = _find_combo_text(widget, value) except ValueError: if value is None: idx = -1 else: raise widget.setCurrentIndex(idx) def update_prop(idx): if idx == -1: setattr(instance, prop, None) else: setattr(instance, prop, widget.itemText(idx)) add_callback(instance, prop, update_widget) widget.currentIndexChanged.connect(update_prop) update_widget(getattr(instance, prop))
[ "def", "connect_combo_text", "(", "instance", ",", "prop", ",", "widget", ")", ":", "def", "update_widget", "(", "value", ")", ":", "try", ":", "idx", "=", "_find_combo_text", "(", "widget", ",", "value", ")", "except", "ValueError", ":", "if", "value", "is", "None", ":", "idx", "=", "-", "1", "else", ":", "raise", "widget", ".", "setCurrentIndex", "(", "idx", ")", "def", "update_prop", "(", "idx", ")", ":", "if", "idx", "==", "-", "1", ":", "setattr", "(", "instance", ",", "prop", ",", "None", ")", "else", ":", "setattr", "(", "instance", ",", "prop", ",", "widget", ".", "itemText", "(", "idx", ")", ")", "add_callback", "(", "instance", ",", "prop", ",", "update_widget", ")", "widget", ".", "currentIndexChanged", ".", "connect", "(", "update_prop", ")", "update_widget", "(", "getattr", "(", "instance", ",", "prop", ")", ")" ]
Connect a callback property with a QComboBox widget based on the text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QComboBox The combo box to connect. See Also -------- connect_combo_data: connect a callback property with a QComboBox widget based on the userData.
[ "Connect", "a", "callback", "property", "with", "a", "QComboBox", "widget", "based", "on", "the", "text", "." ]
6ad54cc5e869de27c34e8716f2619ddc640f08fe
https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L117-L154
244,815
glue-viz/echo
echo/qt/connect.py
connect_float_text
def connect_float_text(instance, prop, widget, fmt="{:g}"): """ Connect a numerical callback property with a Qt widget containing text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. fmt : str or func This should be either a format string (in the ``{}`` notation), or a function that takes a number and returns a string. """ if callable(fmt): format_func = fmt else: def format_func(x): return fmt.format(x) def update_prop(): val = widget.text() try: setattr(instance, prop, float(val)) except ValueError: setattr(instance, prop, 0) def update_widget(val): if val is None: val = 0. widget.setText(format_func(val)) add_callback(instance, prop, update_widget) try: widget.editingFinished.connect(update_prop) except AttributeError: pass update_widget(getattr(instance, prop))
python
def connect_float_text(instance, prop, widget, fmt="{:g}"): """ Connect a numerical callback property with a Qt widget containing text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. fmt : str or func This should be either a format string (in the ``{}`` notation), or a function that takes a number and returns a string. """ if callable(fmt): format_func = fmt else: def format_func(x): return fmt.format(x) def update_prop(): val = widget.text() try: setattr(instance, prop, float(val)) except ValueError: setattr(instance, prop, 0) def update_widget(val): if val is None: val = 0. widget.setText(format_func(val)) add_callback(instance, prop, update_widget) try: widget.editingFinished.connect(update_prop) except AttributeError: pass update_widget(getattr(instance, prop))
[ "def", "connect_float_text", "(", "instance", ",", "prop", ",", "widget", ",", "fmt", "=", "\"{:g}\"", ")", ":", "if", "callable", "(", "fmt", ")", ":", "format_func", "=", "fmt", "else", ":", "def", "format_func", "(", "x", ")", ":", "return", "fmt", ".", "format", "(", "x", ")", "def", "update_prop", "(", ")", ":", "val", "=", "widget", ".", "text", "(", ")", "try", ":", "setattr", "(", "instance", ",", "prop", ",", "float", "(", "val", ")", ")", "except", "ValueError", ":", "setattr", "(", "instance", ",", "prop", ",", "0", ")", "def", "update_widget", "(", "val", ")", ":", "if", "val", "is", "None", ":", "val", "=", "0.", "widget", ".", "setText", "(", "format_func", "(", "val", ")", ")", "add_callback", "(", "instance", ",", "prop", ",", "update_widget", ")", "try", ":", "widget", ".", "editingFinished", ".", "connect", "(", "update_prop", ")", "except", "AttributeError", ":", "pass", "update_widget", "(", "getattr", "(", "instance", ",", "prop", ")", ")" ]
Connect a numerical callback property with a Qt widget containing text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. fmt : str or func This should be either a format string (in the ``{}`` notation), or a function that takes a number and returns a string.
[ "Connect", "a", "numerical", "callback", "property", "with", "a", "Qt", "widget", "containing", "text", "." ]
6ad54cc5e869de27c34e8716f2619ddc640f08fe
https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L157-L200
244,816
glue-viz/echo
echo/qt/connect.py
connect_value
def connect_value(instance, prop, widget, value_range=None, log=False): """ Connect a numerical callback property with a Qt widget representing a value. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. value_range : iterable, optional A pair of two values representing the true range of values (since Qt widgets such as sliders can only have values in certain ranges). log : bool, optional Whether the Qt widget value should be mapped to the log of the callback property. """ if log: if value_range is None: raise ValueError("log option can only be set if value_range is given") else: value_range = math.log10(value_range[0]), math.log10(value_range[1]) def update_prop(): val = widget.value() if value_range is not None: imin, imax = widget.minimum(), widget.maximum() val = (val - imin) / (imax - imin) * (value_range[1] - value_range[0]) + value_range[0] if log: val = 10 ** val setattr(instance, prop, val) def update_widget(val): if val is None: widget.setValue(0) return if log: val = math.log10(val) if value_range is not None: imin, imax = widget.minimum(), widget.maximum() val = (val - value_range[0]) / (value_range[1] - value_range[0]) * (imax - imin) + imin widget.setValue(val) add_callback(instance, prop, update_widget) widget.valueChanged.connect(update_prop) update_widget(getattr(instance, prop))
python
def connect_value(instance, prop, widget, value_range=None, log=False): """ Connect a numerical callback property with a Qt widget representing a value. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. value_range : iterable, optional A pair of two values representing the true range of values (since Qt widgets such as sliders can only have values in certain ranges). log : bool, optional Whether the Qt widget value should be mapped to the log of the callback property. """ if log: if value_range is None: raise ValueError("log option can only be set if value_range is given") else: value_range = math.log10(value_range[0]), math.log10(value_range[1]) def update_prop(): val = widget.value() if value_range is not None: imin, imax = widget.minimum(), widget.maximum() val = (val - imin) / (imax - imin) * (value_range[1] - value_range[0]) + value_range[0] if log: val = 10 ** val setattr(instance, prop, val) def update_widget(val): if val is None: widget.setValue(0) return if log: val = math.log10(val) if value_range is not None: imin, imax = widget.minimum(), widget.maximum() val = (val - value_range[0]) / (value_range[1] - value_range[0]) * (imax - imin) + imin widget.setValue(val) add_callback(instance, prop, update_widget) widget.valueChanged.connect(update_prop) update_widget(getattr(instance, prop))
[ "def", "connect_value", "(", "instance", ",", "prop", ",", "widget", ",", "value_range", "=", "None", ",", "log", "=", "False", ")", ":", "if", "log", ":", "if", "value_range", "is", "None", ":", "raise", "ValueError", "(", "\"log option can only be set if value_range is given\"", ")", "else", ":", "value_range", "=", "math", ".", "log10", "(", "value_range", "[", "0", "]", ")", ",", "math", ".", "log10", "(", "value_range", "[", "1", "]", ")", "def", "update_prop", "(", ")", ":", "val", "=", "widget", ".", "value", "(", ")", "if", "value_range", "is", "not", "None", ":", "imin", ",", "imax", "=", "widget", ".", "minimum", "(", ")", ",", "widget", ".", "maximum", "(", ")", "val", "=", "(", "val", "-", "imin", ")", "/", "(", "imax", "-", "imin", ")", "*", "(", "value_range", "[", "1", "]", "-", "value_range", "[", "0", "]", ")", "+", "value_range", "[", "0", "]", "if", "log", ":", "val", "=", "10", "**", "val", "setattr", "(", "instance", ",", "prop", ",", "val", ")", "def", "update_widget", "(", "val", ")", ":", "if", "val", "is", "None", ":", "widget", ".", "setValue", "(", "0", ")", "return", "if", "log", ":", "val", "=", "math", ".", "log10", "(", "val", ")", "if", "value_range", "is", "not", "None", ":", "imin", ",", "imax", "=", "widget", ".", "minimum", "(", ")", ",", "widget", ".", "maximum", "(", ")", "val", "=", "(", "val", "-", "value_range", "[", "0", "]", ")", "/", "(", "value_range", "[", "1", "]", "-", "value_range", "[", "0", "]", ")", "*", "(", "imax", "-", "imin", ")", "+", "imin", "widget", ".", "setValue", "(", "val", ")", "add_callback", "(", "instance", ",", "prop", ",", "update_widget", ")", "widget", ".", "valueChanged", ".", "connect", "(", "update_prop", ")", "update_widget", "(", "getattr", "(", "instance", ",", "prop", ")", ")" ]
Connect a numerical callback property with a Qt widget representing a value. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. value_range : iterable, optional A pair of two values representing the true range of values (since Qt widgets such as sliders can only have values in certain ranges). log : bool, optional Whether the Qt widget value should be mapped to the log of the callback property.
[ "Connect", "a", "numerical", "callback", "property", "with", "a", "Qt", "widget", "representing", "a", "value", "." ]
6ad54cc5e869de27c34e8716f2619ddc640f08fe
https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L203-L253
244,817
glue-viz/echo
echo/qt/connect.py
connect_button
def connect_button(instance, prop, widget): """ Connect a button with a callback method Parameters ---------- instance : object The class instance that the callback method is attached to prop : str The name of the callback method widget : QtWidget The Qt widget to connect. This should implement the ``clicked`` method """ widget.clicked.connect(getattr(instance, prop))
python
def connect_button(instance, prop, widget): """ Connect a button with a callback method Parameters ---------- instance : object The class instance that the callback method is attached to prop : str The name of the callback method widget : QtWidget The Qt widget to connect. This should implement the ``clicked`` method """ widget.clicked.connect(getattr(instance, prop))
[ "def", "connect_button", "(", "instance", ",", "prop", ",", "widget", ")", ":", "widget", ".", "clicked", ".", "connect", "(", "getattr", "(", "instance", ",", "prop", ")", ")" ]
Connect a button with a callback method Parameters ---------- instance : object The class instance that the callback method is attached to prop : str The name of the callback method widget : QtWidget The Qt widget to connect. This should implement the ``clicked`` method
[ "Connect", "a", "button", "with", "a", "callback", "method" ]
6ad54cc5e869de27c34e8716f2619ddc640f08fe
https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L256-L269
244,818
glue-viz/echo
echo/qt/connect.py
_find_combo_data
def _find_combo_data(widget, value): """ Returns the index in a combo box where itemData == value Raises a ValueError if data is not found """ # Here we check that the result is True, because some classes may overload # == and return other kinds of objects whether true or false. for idx in range(widget.count()): if widget.itemData(idx) is value or (widget.itemData(idx) == value) is True: return idx else: raise ValueError("%s not found in combo box" % (value,))
python
def _find_combo_data(widget, value): """ Returns the index in a combo box where itemData == value Raises a ValueError if data is not found """ # Here we check that the result is True, because some classes may overload # == and return other kinds of objects whether true or false. for idx in range(widget.count()): if widget.itemData(idx) is value or (widget.itemData(idx) == value) is True: return idx else: raise ValueError("%s not found in combo box" % (value,))
[ "def", "_find_combo_data", "(", "widget", ",", "value", ")", ":", "# Here we check that the result is True, because some classes may overload", "# == and return other kinds of objects whether true or false.", "for", "idx", "in", "range", "(", "widget", ".", "count", "(", ")", ")", ":", "if", "widget", ".", "itemData", "(", "idx", ")", "is", "value", "or", "(", "widget", ".", "itemData", "(", "idx", ")", "==", "value", ")", "is", "True", ":", "return", "idx", "else", ":", "raise", "ValueError", "(", "\"%s not found in combo box\"", "%", "(", "value", ",", ")", ")" ]
Returns the index in a combo box where itemData == value Raises a ValueError if data is not found
[ "Returns", "the", "index", "in", "a", "combo", "box", "where", "itemData", "==", "value" ]
6ad54cc5e869de27c34e8716f2619ddc640f08fe
https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L272-L284
244,819
glue-viz/echo
echo/qt/connect.py
_find_combo_text
def _find_combo_text(widget, value): """ Returns the index in a combo box where text == value Raises a ValueError if data is not found """ i = widget.findText(value) if i == -1: raise ValueError("%s not found in combo box" % value) else: return i
python
def _find_combo_text(widget, value): """ Returns the index in a combo box where text == value Raises a ValueError if data is not found """ i = widget.findText(value) if i == -1: raise ValueError("%s not found in combo box" % value) else: return i
[ "def", "_find_combo_text", "(", "widget", ",", "value", ")", ":", "i", "=", "widget", ".", "findText", "(", "value", ")", "if", "i", "==", "-", "1", ":", "raise", "ValueError", "(", "\"%s not found in combo box\"", "%", "value", ")", "else", ":", "return", "i" ]
Returns the index in a combo box where text == value Raises a ValueError if data is not found
[ "Returns", "the", "index", "in", "a", "combo", "box", "where", "text", "==", "value" ]
6ad54cc5e869de27c34e8716f2619ddc640f08fe
https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L287-L297
244,820
twidi/py-dataql
dataql/utils.py
class_repr
def class_repr(value): """Returns a representation of the value class. Arguments --------- value A class or a class instance Returns ------- str The "module.name" representation of the value class. Example ------- >>> from datetime import date >>> class_repr(date) 'datetime.date' >>> class_repr(date.today()) 'datetime.date' """ klass = value if not isinstance(value, type): klass = klass.__class__ return '.'.join([klass.__module__, klass.__name__])
python
def class_repr(value): """Returns a representation of the value class. Arguments --------- value A class or a class instance Returns ------- str The "module.name" representation of the value class. Example ------- >>> from datetime import date >>> class_repr(date) 'datetime.date' >>> class_repr(date.today()) 'datetime.date' """ klass = value if not isinstance(value, type): klass = klass.__class__ return '.'.join([klass.__module__, klass.__name__])
[ "def", "class_repr", "(", "value", ")", ":", "klass", "=", "value", "if", "not", "isinstance", "(", "value", ",", "type", ")", ":", "klass", "=", "klass", ".", "__class__", "return", "'.'", ".", "join", "(", "[", "klass", ".", "__module__", ",", "klass", ".", "__name__", "]", ")" ]
Returns a representation of the value class. Arguments --------- value A class or a class instance Returns ------- str The "module.name" representation of the value class. Example ------- >>> from datetime import date >>> class_repr(date) 'datetime.date' >>> class_repr(date.today()) 'datetime.date'
[ "Returns", "a", "representation", "of", "the", "value", "class", "." ]
5841a3fd559829193ed709c255166085bdde1c52
https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/utils.py#L7-L31
244,821
mbodenhamer/syn
syn/base_utils/rand.py
rand_unicode
def rand_unicode(min_char=MIN_UNICHR, max_char=MAX_UNICHR, min_len=MIN_STRLEN, max_len=MAX_STRLEN, **kwargs): '''For values in the unicode range, regardless of Python version. ''' from syn.five import unichr return unicode(rand_str(min_char, max_char, min_len, max_len, unichr))
python
def rand_unicode(min_char=MIN_UNICHR, max_char=MAX_UNICHR, min_len=MIN_STRLEN, max_len=MAX_STRLEN, **kwargs): '''For values in the unicode range, regardless of Python version. ''' from syn.five import unichr return unicode(rand_str(min_char, max_char, min_len, max_len, unichr))
[ "def", "rand_unicode", "(", "min_char", "=", "MIN_UNICHR", ",", "max_char", "=", "MAX_UNICHR", ",", "min_len", "=", "MIN_STRLEN", ",", "max_len", "=", "MAX_STRLEN", ",", "*", "*", "kwargs", ")", ":", "from", "syn", ".", "five", "import", "unichr", "return", "unicode", "(", "rand_str", "(", "min_char", ",", "max_char", ",", "min_len", ",", "max_len", ",", "unichr", ")", ")" ]
For values in the unicode range, regardless of Python version.
[ "For", "values", "in", "the", "unicode", "range", "regardless", "of", "Python", "version", "." ]
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/rand.py#L96-L101
244,822
GemHQ/round-py
round/users.py
Users.create
def create(self, email, device_name, passphrase=None, api_token=None, redirect_uri=None, **kwargs): """Create a new User object and add it to this Users collection. In addition to creating a user, this call will create a device for that user, whose device_token will be returned from this call. Store the device_token, as it's required to complete Gem-Device authentication after the user approves the device at the end of their signup flow. If you lose the device_token returned from users.create, you'll have to create a new device for the user to gain access to their account again. Also, after this call, be sure to redirect the user to the location in `mfa_uri` (second return value of this function) to complete their account. If you get a 409 Conflict error, then the user already exists in the Gem system and you'll want to do a `client.user(email).devices.create(device_name)` Args: email (str) device_name (str): Human-readable name for the device through which your Application will be authorized to access the new User's account. passphrase (str, optional): A passphrase with which to encrypt a user wallet. If not provided, a default_wallet parameter must be passed in kwargs. api_token (str, optional): Your app's API token. This is optional if and only if the Client which will be calling this function already has Gem-Application or Gem-Identify authentication. redirect_uri (str, optional): A URI to which to redirect the User after they confirm their Gem account. **kwargs Returns: device_token """ if not passphrase and u'default_wallet' not in kwargs: raise ValueError("Usage: users.create(email, passphrase, device_name" ", api_token, redirect_uri)") elif passphrase: default_wallet = generate(passphrase, ['primary'])['primary'] else: default_wallet = kwargs['default_wallet'] default_wallet['name'] = 'default' default_wallet['primary_private_seed'] = default_wallet['encrypted_seed'] default_wallet['primary_public_seed'] = default_wallet['public_seed'] del default_wallet['encrypted_seed'] del default_wallet['public_seed'] del default_wallet['private_seed'] # If not supplied, we assume the client already has an api_token param. if api_token: self.client.authenticate_identify(api_token) user_data = dict(email=email, default_wallet=default_wallet, device_name=device_name) if redirect_uri: user_data['redirect_uri'] = redirect_uri if 'first_name' in kwargs: user_data['first_name'] = kwargs['first_name'] if 'last_name' in kwargs: user_data['last_name'] = kwargs['last_name'] try: resource = self.resource.create(user_data) except ResponseError as e: if "conflict" in e.message: raise ConflictError( "This user already exists. Use " "client.user(email).devices.create(name) to request " "authorization from the user.") raise e return resource.attributes['metadata']['device_token']
python
def create(self, email, device_name, passphrase=None, api_token=None, redirect_uri=None, **kwargs): """Create a new User object and add it to this Users collection. In addition to creating a user, this call will create a device for that user, whose device_token will be returned from this call. Store the device_token, as it's required to complete Gem-Device authentication after the user approves the device at the end of their signup flow. If you lose the device_token returned from users.create, you'll have to create a new device for the user to gain access to their account again. Also, after this call, be sure to redirect the user to the location in `mfa_uri` (second return value of this function) to complete their account. If you get a 409 Conflict error, then the user already exists in the Gem system and you'll want to do a `client.user(email).devices.create(device_name)` Args: email (str) device_name (str): Human-readable name for the device through which your Application will be authorized to access the new User's account. passphrase (str, optional): A passphrase with which to encrypt a user wallet. If not provided, a default_wallet parameter must be passed in kwargs. api_token (str, optional): Your app's API token. This is optional if and only if the Client which will be calling this function already has Gem-Application or Gem-Identify authentication. redirect_uri (str, optional): A URI to which to redirect the User after they confirm their Gem account. **kwargs Returns: device_token """ if not passphrase and u'default_wallet' not in kwargs: raise ValueError("Usage: users.create(email, passphrase, device_name" ", api_token, redirect_uri)") elif passphrase: default_wallet = generate(passphrase, ['primary'])['primary'] else: default_wallet = kwargs['default_wallet'] default_wallet['name'] = 'default' default_wallet['primary_private_seed'] = default_wallet['encrypted_seed'] default_wallet['primary_public_seed'] = default_wallet['public_seed'] del default_wallet['encrypted_seed'] del default_wallet['public_seed'] del default_wallet['private_seed'] # If not supplied, we assume the client already has an api_token param. if api_token: self.client.authenticate_identify(api_token) user_data = dict(email=email, default_wallet=default_wallet, device_name=device_name) if redirect_uri: user_data['redirect_uri'] = redirect_uri if 'first_name' in kwargs: user_data['first_name'] = kwargs['first_name'] if 'last_name' in kwargs: user_data['last_name'] = kwargs['last_name'] try: resource = self.resource.create(user_data) except ResponseError as e: if "conflict" in e.message: raise ConflictError( "This user already exists. Use " "client.user(email).devices.create(name) to request " "authorization from the user.") raise e return resource.attributes['metadata']['device_token']
[ "def", "create", "(", "self", ",", "email", ",", "device_name", ",", "passphrase", "=", "None", ",", "api_token", "=", "None", ",", "redirect_uri", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "passphrase", "and", "u'default_wallet'", "not", "in", "kwargs", ":", "raise", "ValueError", "(", "\"Usage: users.create(email, passphrase, device_name\"", "\", api_token, redirect_uri)\"", ")", "elif", "passphrase", ":", "default_wallet", "=", "generate", "(", "passphrase", ",", "[", "'primary'", "]", ")", "[", "'primary'", "]", "else", ":", "default_wallet", "=", "kwargs", "[", "'default_wallet'", "]", "default_wallet", "[", "'name'", "]", "=", "'default'", "default_wallet", "[", "'primary_private_seed'", "]", "=", "default_wallet", "[", "'encrypted_seed'", "]", "default_wallet", "[", "'primary_public_seed'", "]", "=", "default_wallet", "[", "'public_seed'", "]", "del", "default_wallet", "[", "'encrypted_seed'", "]", "del", "default_wallet", "[", "'public_seed'", "]", "del", "default_wallet", "[", "'private_seed'", "]", "# If not supplied, we assume the client already has an api_token param.", "if", "api_token", ":", "self", ".", "client", ".", "authenticate_identify", "(", "api_token", ")", "user_data", "=", "dict", "(", "email", "=", "email", ",", "default_wallet", "=", "default_wallet", ",", "device_name", "=", "device_name", ")", "if", "redirect_uri", ":", "user_data", "[", "'redirect_uri'", "]", "=", "redirect_uri", "if", "'first_name'", "in", "kwargs", ":", "user_data", "[", "'first_name'", "]", "=", "kwargs", "[", "'first_name'", "]", "if", "'last_name'", "in", "kwargs", ":", "user_data", "[", "'last_name'", "]", "=", "kwargs", "[", "'last_name'", "]", "try", ":", "resource", "=", "self", ".", "resource", ".", "create", "(", "user_data", ")", "except", "ResponseError", "as", "e", ":", "if", "\"conflict\"", "in", "e", ".", "message", ":", "raise", "ConflictError", "(", "\"This user already exists. Use \"", "\"client.user(email).devices.create(name) to request \"", "\"authorization from the user.\"", ")", "raise", "e", "return", "resource", ".", "attributes", "[", "'metadata'", "]", "[", "'device_token'", "]" ]
Create a new User object and add it to this Users collection. In addition to creating a user, this call will create a device for that user, whose device_token will be returned from this call. Store the device_token, as it's required to complete Gem-Device authentication after the user approves the device at the end of their signup flow. If you lose the device_token returned from users.create, you'll have to create a new device for the user to gain access to their account again. Also, after this call, be sure to redirect the user to the location in `mfa_uri` (second return value of this function) to complete their account. If you get a 409 Conflict error, then the user already exists in the Gem system and you'll want to do a `client.user(email).devices.create(device_name)` Args: email (str) device_name (str): Human-readable name for the device through which your Application will be authorized to access the new User's account. passphrase (str, optional): A passphrase with which to encrypt a user wallet. If not provided, a default_wallet parameter must be passed in kwargs. api_token (str, optional): Your app's API token. This is optional if and only if the Client which will be calling this function already has Gem-Application or Gem-Identify authentication. redirect_uri (str, optional): A URI to which to redirect the User after they confirm their Gem account. **kwargs Returns: device_token
[ "Create", "a", "new", "User", "object", "and", "add", "it", "to", "this", "Users", "collection", "." ]
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/users.py#L20-L97
244,823
GemHQ/round-py
round/users.py
User.subscriptions
def subscriptions(self): """Fetch and return Subscriptions associated with this user.""" if not hasattr(self, '_subscriptions'): subscriptions_resource = self.resource.subscriptions self._subscriptions = Subscriptions( subscriptions_resource, self.client) return self._subscriptions
python
def subscriptions(self): """Fetch and return Subscriptions associated with this user.""" if not hasattr(self, '_subscriptions'): subscriptions_resource = self.resource.subscriptions self._subscriptions = Subscriptions( subscriptions_resource, self.client) return self._subscriptions
[ "def", "subscriptions", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_subscriptions'", ")", ":", "subscriptions_resource", "=", "self", ".", "resource", ".", "subscriptions", "self", ".", "_subscriptions", "=", "Subscriptions", "(", "subscriptions_resource", ",", "self", ".", "client", ")", "return", "self", ".", "_subscriptions" ]
Fetch and return Subscriptions associated with this user.
[ "Fetch", "and", "return", "Subscriptions", "associated", "with", "this", "user", "." ]
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/users.py#L148-L154
244,824
GemHQ/round-py
round/users.py
User.verify_mfa
def verify_mfa(self, mfa_token): """Verify an SMS or TOTP MFA token for this user. Args: mfa_token (str): An alphanumeric code from either a User's TOTP application or sent to them via SMS. Returns: True if the mfa_token is valid, False otherwise. """ response = self.resource.verify_mfa({'mfa_token': mfa_token}) return (response['valid'] == True or response['valid'] == 'true')
python
def verify_mfa(self, mfa_token): """Verify an SMS or TOTP MFA token for this user. Args: mfa_token (str): An alphanumeric code from either a User's TOTP application or sent to them via SMS. Returns: True if the mfa_token is valid, False otherwise. """ response = self.resource.verify_mfa({'mfa_token': mfa_token}) return (response['valid'] == True or response['valid'] == 'true')
[ "def", "verify_mfa", "(", "self", ",", "mfa_token", ")", ":", "response", "=", "self", ".", "resource", ".", "verify_mfa", "(", "{", "'mfa_token'", ":", "mfa_token", "}", ")", "return", "(", "response", "[", "'valid'", "]", "==", "True", "or", "response", "[", "'valid'", "]", "==", "'true'", ")" ]
Verify an SMS or TOTP MFA token for this user. Args: mfa_token (str): An alphanumeric code from either a User's TOTP application or sent to them via SMS. Returns: True if the mfa_token is valid, False otherwise.
[ "Verify", "an", "SMS", "or", "TOTP", "MFA", "token", "for", "this", "user", "." ]
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/users.py#L160-L171
244,825
prestontimmons/django-synctool
synctool/functions.py
reset_sequence
def reset_sequence(app_label): """ Reset the primary key sequence for the tables in an application. This is necessary if any local edits have happened to the table. """ puts("Resetting primary key sequence for {0}".format(app_label)) cursor = connection.cursor() cmd = get_reset_command(app_label) cursor.execute(cmd)
python
def reset_sequence(app_label): """ Reset the primary key sequence for the tables in an application. This is necessary if any local edits have happened to the table. """ puts("Resetting primary key sequence for {0}".format(app_label)) cursor = connection.cursor() cmd = get_reset_command(app_label) cursor.execute(cmd)
[ "def", "reset_sequence", "(", "app_label", ")", ":", "puts", "(", "\"Resetting primary key sequence for {0}\"", ".", "format", "(", "app_label", ")", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cmd", "=", "get_reset_command", "(", "app_label", ")", "cursor", ".", "execute", "(", "cmd", ")" ]
Reset the primary key sequence for the tables in an application. This is necessary if any local edits have happened to the table.
[ "Reset", "the", "primary", "key", "sequence", "for", "the", "tables", "in", "an", "application", ".", "This", "is", "necessary", "if", "any", "local", "edits", "have", "happened", "to", "the", "table", "." ]
bfacaacd3a4f98facd524e16c0ce2b3ab2ef30a7
https://github.com/prestontimmons/django-synctool/blob/bfacaacd3a4f98facd524e16c0ce2b3ab2ef30a7/synctool/functions.py#L77-L87
244,826
collectiveacuity/labPack
labpack/platforms/docker.py
dockerClient._validate_install
def _validate_install(self): ''' a method to validate docker is installed ''' from subprocess import check_output, STDOUT sys_command = 'docker --help' try: check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8') # call(sys_command, stdout=open(devnull, 'wb')) except Exception as err: raise Exception('"docker" not installed. GoTo: https://www.docker.com') return True
python
def _validate_install(self): ''' a method to validate docker is installed ''' from subprocess import check_output, STDOUT sys_command = 'docker --help' try: check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8') # call(sys_command, stdout=open(devnull, 'wb')) except Exception as err: raise Exception('"docker" not installed. GoTo: https://www.docker.com') return True
[ "def", "_validate_install", "(", "self", ")", ":", "from", "subprocess", "import", "check_output", ",", "STDOUT", "sys_command", "=", "'docker --help'", "try", ":", "check_output", "(", "sys_command", ",", "shell", "=", "True", ",", "stderr", "=", "STDOUT", ")", ".", "decode", "(", "'utf-8'", ")", "# call(sys_command, stdout=open(devnull, 'wb'))\r", "except", "Exception", "as", "err", ":", "raise", "Exception", "(", "'\"docker\" not installed. GoTo: https://www.docker.com'", ")", "return", "True" ]
a method to validate docker is installed
[ "a", "method", "to", "validate", "docker", "is", "installed" ]
52949ece35e72e3cc308f54d9ffa6bfbd96805b8
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L104-L116
244,827
collectiveacuity/labPack
labpack/platforms/docker.py
dockerClient._images
def _images(self, sys_output): ''' a helper method for parsing docker image output ''' import re gap_pattern = re.compile('\t|\s{2,}') image_list = [] output_lines = sys_output.split('\n') column_headers = gap_pattern.split(output_lines[0]) for i in range(1,len(output_lines)): columns = gap_pattern.split(output_lines[i]) if len(columns) == len(column_headers): image_details = {} for j in range(len(columns)): image_details[column_headers[j]] = columns[j] image_list.append(image_details) return image_list
python
def _images(self, sys_output): ''' a helper method for parsing docker image output ''' import re gap_pattern = re.compile('\t|\s{2,}') image_list = [] output_lines = sys_output.split('\n') column_headers = gap_pattern.split(output_lines[0]) for i in range(1,len(output_lines)): columns = gap_pattern.split(output_lines[i]) if len(columns) == len(column_headers): image_details = {} for j in range(len(columns)): image_details[column_headers[j]] = columns[j] image_list.append(image_details) return image_list
[ "def", "_images", "(", "self", ",", "sys_output", ")", ":", "import", "re", "gap_pattern", "=", "re", ".", "compile", "(", "'\\t|\\s{2,}'", ")", "image_list", "=", "[", "]", "output_lines", "=", "sys_output", ".", "split", "(", "'\\n'", ")", "column_headers", "=", "gap_pattern", ".", "split", "(", "output_lines", "[", "0", "]", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "output_lines", ")", ")", ":", "columns", "=", "gap_pattern", ".", "split", "(", "output_lines", "[", "i", "]", ")", "if", "len", "(", "columns", ")", "==", "len", "(", "column_headers", ")", ":", "image_details", "=", "{", "}", "for", "j", "in", "range", "(", "len", "(", "columns", ")", ")", ":", "image_details", "[", "column_headers", "[", "j", "]", "]", "=", "columns", "[", "j", "]", "image_list", ".", "append", "(", "image_details", ")", "return", "image_list" ]
a helper method for parsing docker image output
[ "a", "helper", "method", "for", "parsing", "docker", "image", "output" ]
52949ece35e72e3cc308f54d9ffa6bfbd96805b8
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L183-L200
244,828
collectiveacuity/labPack
labpack/platforms/docker.py
dockerClient._ps
def _ps(self, sys_output): ''' a helper method for parsing docker ps output ''' import re gap_pattern = re.compile('\t|\s{2,}') container_list = [] output_lines = sys_output.split('\n') column_headers = gap_pattern.split(output_lines[0]) for i in range(1,len(output_lines)): columns = gap_pattern.split(output_lines[i]) container_details = {} if len(columns) > 1: for j in range(len(column_headers)): container_details[column_headers[j]] = '' if j <= len(columns) - 1: container_details[column_headers[j]] = columns[j] # stupid hack for possible empty port column if container_details['PORTS'] and not container_details['NAMES']: from copy import deepcopy container_details['NAMES'] = deepcopy(container_details['PORTS']) container_details['PORTS'] = '' container_list.append(container_details) return container_list
python
def _ps(self, sys_output): ''' a helper method for parsing docker ps output ''' import re gap_pattern = re.compile('\t|\s{2,}') container_list = [] output_lines = sys_output.split('\n') column_headers = gap_pattern.split(output_lines[0]) for i in range(1,len(output_lines)): columns = gap_pattern.split(output_lines[i]) container_details = {} if len(columns) > 1: for j in range(len(column_headers)): container_details[column_headers[j]] = '' if j <= len(columns) - 1: container_details[column_headers[j]] = columns[j] # stupid hack for possible empty port column if container_details['PORTS'] and not container_details['NAMES']: from copy import deepcopy container_details['NAMES'] = deepcopy(container_details['PORTS']) container_details['PORTS'] = '' container_list.append(container_details) return container_list
[ "def", "_ps", "(", "self", ",", "sys_output", ")", ":", "import", "re", "gap_pattern", "=", "re", ".", "compile", "(", "'\\t|\\s{2,}'", ")", "container_list", "=", "[", "]", "output_lines", "=", "sys_output", ".", "split", "(", "'\\n'", ")", "column_headers", "=", "gap_pattern", ".", "split", "(", "output_lines", "[", "0", "]", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "output_lines", ")", ")", ":", "columns", "=", "gap_pattern", ".", "split", "(", "output_lines", "[", "i", "]", ")", "container_details", "=", "{", "}", "if", "len", "(", "columns", ")", ">", "1", ":", "for", "j", "in", "range", "(", "len", "(", "column_headers", ")", ")", ":", "container_details", "[", "column_headers", "[", "j", "]", "]", "=", "''", "if", "j", "<=", "len", "(", "columns", ")", "-", "1", ":", "container_details", "[", "column_headers", "[", "j", "]", "]", "=", "columns", "[", "j", "]", "# stupid hack for possible empty port column\r", "if", "container_details", "[", "'PORTS'", "]", "and", "not", "container_details", "[", "'NAMES'", "]", ":", "from", "copy", "import", "deepcopy", "container_details", "[", "'NAMES'", "]", "=", "deepcopy", "(", "container_details", "[", "'PORTS'", "]", ")", "container_details", "[", "'PORTS'", "]", "=", "''", "container_list", ".", "append", "(", "container_details", ")", "return", "container_list" ]
a helper method for parsing docker ps output
[ "a", "helper", "method", "for", "parsing", "docker", "ps", "output" ]
52949ece35e72e3cc308f54d9ffa6bfbd96805b8
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L202-L226
244,829
collectiveacuity/labPack
labpack/platforms/docker.py
dockerClient._synopsis
def _synopsis(self, container_settings, container_status=''): ''' a helper method for summarizing container settings ''' # compose default response settings = { 'container_status': container_settings['State']['Status'], 'container_exit': container_settings['State']['ExitCode'], 'container_ip': container_settings['NetworkSettings']['IPAddress'], 'image_name': container_settings['Config']['Image'], 'container_alias': container_settings['Name'].replace('/',''), 'container_variables': {}, 'mapped_ports': {}, 'mounted_volumes': {}, 'container_networks': [] } # parse fields nested in container settings import re num_pattern = re.compile('\d+') if container_settings['NetworkSettings']['Ports']: for key, value in container_settings['NetworkSettings']['Ports'].items(): if value: port = num_pattern.findall(value[0]['HostPort'])[0] settings['mapped_ports'][port] = num_pattern.findall(key)[0] elif container_settings['HostConfig']['PortBindings']: for key, value in container_settings['HostConfig']['PortBindings'].items(): port = num_pattern.findall(value[0]['HostPort'])[0] settings['mapped_ports'][port] = num_pattern.findall(key)[0] if container_settings['Config']['Env']: for variable in container_settings['Config']['Env']: k, v = variable.split('=') settings['container_variables'][k] = v for volume in container_settings['Mounts']: system_path = volume['Source'] container_path = volume['Destination'] settings['mounted_volumes'][system_path] = container_path if container_settings['NetworkSettings']: if container_settings['NetworkSettings']['Networks']: for key in container_settings['NetworkSettings']['Networks'].keys(): settings['container_networks'].append(key) # determine stopped status if settings['container_status'] == 'exited': if not container_status: try: from subprocess import check_output, STDOUT sys_command = 'docker logs --tail 1 %s' % settings['container_alias'] check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8') settings['container_status'] = 'stopped' except: pass else: settings['container_status'] = container_status return settings
python
def _synopsis(self, container_settings, container_status=''): ''' a helper method for summarizing container settings ''' # compose default response settings = { 'container_status': container_settings['State']['Status'], 'container_exit': container_settings['State']['ExitCode'], 'container_ip': container_settings['NetworkSettings']['IPAddress'], 'image_name': container_settings['Config']['Image'], 'container_alias': container_settings['Name'].replace('/',''), 'container_variables': {}, 'mapped_ports': {}, 'mounted_volumes': {}, 'container_networks': [] } # parse fields nested in container settings import re num_pattern = re.compile('\d+') if container_settings['NetworkSettings']['Ports']: for key, value in container_settings['NetworkSettings']['Ports'].items(): if value: port = num_pattern.findall(value[0]['HostPort'])[0] settings['mapped_ports'][port] = num_pattern.findall(key)[0] elif container_settings['HostConfig']['PortBindings']: for key, value in container_settings['HostConfig']['PortBindings'].items(): port = num_pattern.findall(value[0]['HostPort'])[0] settings['mapped_ports'][port] = num_pattern.findall(key)[0] if container_settings['Config']['Env']: for variable in container_settings['Config']['Env']: k, v = variable.split('=') settings['container_variables'][k] = v for volume in container_settings['Mounts']: system_path = volume['Source'] container_path = volume['Destination'] settings['mounted_volumes'][system_path] = container_path if container_settings['NetworkSettings']: if container_settings['NetworkSettings']['Networks']: for key in container_settings['NetworkSettings']['Networks'].keys(): settings['container_networks'].append(key) # determine stopped status if settings['container_status'] == 'exited': if not container_status: try: from subprocess import check_output, STDOUT sys_command = 'docker logs --tail 1 %s' % settings['container_alias'] check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8') settings['container_status'] = 'stopped' except: pass else: settings['container_status'] = container_status return settings
[ "def", "_synopsis", "(", "self", ",", "container_settings", ",", "container_status", "=", "''", ")", ":", "# compose default response\r", "settings", "=", "{", "'container_status'", ":", "container_settings", "[", "'State'", "]", "[", "'Status'", "]", ",", "'container_exit'", ":", "container_settings", "[", "'State'", "]", "[", "'ExitCode'", "]", ",", "'container_ip'", ":", "container_settings", "[", "'NetworkSettings'", "]", "[", "'IPAddress'", "]", ",", "'image_name'", ":", "container_settings", "[", "'Config'", "]", "[", "'Image'", "]", ",", "'container_alias'", ":", "container_settings", "[", "'Name'", "]", ".", "replace", "(", "'/'", ",", "''", ")", ",", "'container_variables'", ":", "{", "}", ",", "'mapped_ports'", ":", "{", "}", ",", "'mounted_volumes'", ":", "{", "}", ",", "'container_networks'", ":", "[", "]", "}", "# parse fields nested in container settings\r", "import", "re", "num_pattern", "=", "re", ".", "compile", "(", "'\\d+'", ")", "if", "container_settings", "[", "'NetworkSettings'", "]", "[", "'Ports'", "]", ":", "for", "key", ",", "value", "in", "container_settings", "[", "'NetworkSettings'", "]", "[", "'Ports'", "]", ".", "items", "(", ")", ":", "if", "value", ":", "port", "=", "num_pattern", ".", "findall", "(", "value", "[", "0", "]", "[", "'HostPort'", "]", ")", "[", "0", "]", "settings", "[", "'mapped_ports'", "]", "[", "port", "]", "=", "num_pattern", ".", "findall", "(", "key", ")", "[", "0", "]", "elif", "container_settings", "[", "'HostConfig'", "]", "[", "'PortBindings'", "]", ":", "for", "key", ",", "value", "in", "container_settings", "[", "'HostConfig'", "]", "[", "'PortBindings'", "]", ".", "items", "(", ")", ":", "port", "=", "num_pattern", ".", "findall", "(", "value", "[", "0", "]", "[", "'HostPort'", "]", ")", "[", "0", "]", "settings", "[", "'mapped_ports'", "]", "[", "port", "]", "=", "num_pattern", ".", "findall", "(", "key", ")", "[", "0", "]", "if", "container_settings", "[", "'Config'", "]", "[", "'Env'", "]", ":", "for", "variable", "in", "container_settings", "[", "'Config'", "]", "[", "'Env'", "]", ":", "k", ",", "v", "=", "variable", ".", "split", "(", "'='", ")", "settings", "[", "'container_variables'", "]", "[", "k", "]", "=", "v", "for", "volume", "in", "container_settings", "[", "'Mounts'", "]", ":", "system_path", "=", "volume", "[", "'Source'", "]", "container_path", "=", "volume", "[", "'Destination'", "]", "settings", "[", "'mounted_volumes'", "]", "[", "system_path", "]", "=", "container_path", "if", "container_settings", "[", "'NetworkSettings'", "]", ":", "if", "container_settings", "[", "'NetworkSettings'", "]", "[", "'Networks'", "]", ":", "for", "key", "in", "container_settings", "[", "'NetworkSettings'", "]", "[", "'Networks'", "]", ".", "keys", "(", ")", ":", "settings", "[", "'container_networks'", "]", ".", "append", "(", "key", ")", "# determine stopped status\r", "if", "settings", "[", "'container_status'", "]", "==", "'exited'", ":", "if", "not", "container_status", ":", "try", ":", "from", "subprocess", "import", "check_output", ",", "STDOUT", "sys_command", "=", "'docker logs --tail 1 %s'", "%", "settings", "[", "'container_alias'", "]", "check_output", "(", "sys_command", ",", "shell", "=", "True", ",", "stderr", "=", "STDOUT", ")", ".", "decode", "(", "'utf-8'", ")", "settings", "[", "'container_status'", "]", "=", "'stopped'", "except", ":", "pass", "else", ":", "settings", "[", "'container_status'", "]", "=", "container_status", "return", "settings" ]
a helper method for summarizing container settings
[ "a", "helper", "method", "for", "summarizing", "container", "settings" ]
52949ece35e72e3cc308f54d9ffa6bfbd96805b8
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L228-L283
244,830
ikalnytskyi/dooku
dooku/itertools.py
chunk_by
def chunk_by(n, iterable, fillvalue=None): """ Iterate over a given ``iterable`` by ``n`` elements at a time. >>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]): ... # iteration no 1: x=1, y=2 ... # iteration no 2: x=3, y=4 ... # iteration no 3: x=5, y=None :param n: (int) a chunk size number :param iterable: (iterator) an input iterator :param fillvalue: (any) a value to be used to fit chunk size if there not enough values in input iterator :returns: (iterator) an output iterator that iterates over the input one by chunks of size ``n`` """ args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue)
python
def chunk_by(n, iterable, fillvalue=None): """ Iterate over a given ``iterable`` by ``n`` elements at a time. >>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]): ... # iteration no 1: x=1, y=2 ... # iteration no 2: x=3, y=4 ... # iteration no 3: x=5, y=None :param n: (int) a chunk size number :param iterable: (iterator) an input iterator :param fillvalue: (any) a value to be used to fit chunk size if there not enough values in input iterator :returns: (iterator) an output iterator that iterates over the input one by chunks of size ``n`` """ args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue)
[ "def", "chunk_by", "(", "n", ",", "iterable", ",", "fillvalue", "=", "None", ")", ":", "args", "=", "[", "iter", "(", "iterable", ")", "]", "*", "n", "return", "zip_longest", "(", "*", "args", ",", "fillvalue", "=", "fillvalue", ")" ]
Iterate over a given ``iterable`` by ``n`` elements at a time. >>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]): ... # iteration no 1: x=1, y=2 ... # iteration no 2: x=3, y=4 ... # iteration no 3: x=5, y=None :param n: (int) a chunk size number :param iterable: (iterator) an input iterator :param fillvalue: (any) a value to be used to fit chunk size if there not enough values in input iterator :returns: (iterator) an output iterator that iterates over the input one by chunks of size ``n``
[ "Iterate", "over", "a", "given", "iterable", "by", "n", "elements", "at", "a", "time", "." ]
77e6c82c9c41211c86ee36ae5e591d477945fedf
https://github.com/ikalnytskyi/dooku/blob/77e6c82c9c41211c86ee36ae5e591d477945fedf/dooku/itertools.py#L20-L37
244,831
pip-services3-python/pip-services3-components-python
pip_services3_components/config/ConfigReader.py
ConfigReader._parameterize
def _parameterize(self, config, parameters): """ Parameterized configuration template given as string with dynamic parameters. :param config: a string with configuration template to be parameterized :param parameters: dynamic parameters to inject into the template :return: a parameterized configuration string. """ parameters = self._parameters.override(parameters) return pystache.render(config, parameters)
python
def _parameterize(self, config, parameters): """ Parameterized configuration template given as string with dynamic parameters. :param config: a string with configuration template to be parameterized :param parameters: dynamic parameters to inject into the template :return: a parameterized configuration string. """ parameters = self._parameters.override(parameters) return pystache.render(config, parameters)
[ "def", "_parameterize", "(", "self", ",", "config", ",", "parameters", ")", ":", "parameters", "=", "self", ".", "_parameters", ".", "override", "(", "parameters", ")", "return", "pystache", ".", "render", "(", "config", ",", "parameters", ")" ]
Parameterized configuration template given as string with dynamic parameters. :param config: a string with configuration template to be parameterized :param parameters: dynamic parameters to inject into the template :return: a parameterized configuration string.
[ "Parameterized", "configuration", "template", "given", "as", "string", "with", "dynamic", "parameters", "." ]
1de9c1bb544cf1891111e9a5f5d67653f62c9b52
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/config/ConfigReader.py#L58-L69
244,832
toastdriven/alligator
alligator/gator.py
Gator.build_backend
def build_backend(self, conn_string): """ Given a DSN, returns an instantiated backend class. Ex:: backend = gator.build_backend('locmem://') # ...or... backend = gator.build_backend('redis://127.0.0.1:6379/0') :param conn_string: A DSN for connecting to the queue. Passed along to the backend. :type conn_string: string :returns: A backend ``Client`` instance """ backend_name, _ = conn_string.split(':', 1) backend_path = 'alligator.backends.{}_backend'.format(backend_name) client_class = import_attr(backend_path, 'Client') return client_class(conn_string)
python
def build_backend(self, conn_string): """ Given a DSN, returns an instantiated backend class. Ex:: backend = gator.build_backend('locmem://') # ...or... backend = gator.build_backend('redis://127.0.0.1:6379/0') :param conn_string: A DSN for connecting to the queue. Passed along to the backend. :type conn_string: string :returns: A backend ``Client`` instance """ backend_name, _ = conn_string.split(':', 1) backend_path = 'alligator.backends.{}_backend'.format(backend_name) client_class = import_attr(backend_path, 'Client') return client_class(conn_string)
[ "def", "build_backend", "(", "self", ",", "conn_string", ")", ":", "backend_name", ",", "_", "=", "conn_string", ".", "split", "(", "':'", ",", "1", ")", "backend_path", "=", "'alligator.backends.{}_backend'", ".", "format", "(", "backend_name", ")", "client_class", "=", "import_attr", "(", "backend_path", ",", "'Client'", ")", "return", "client_class", "(", "conn_string", ")" ]
Given a DSN, returns an instantiated backend class. Ex:: backend = gator.build_backend('locmem://') # ...or... backend = gator.build_backend('redis://127.0.0.1:6379/0') :param conn_string: A DSN for connecting to the queue. Passed along to the backend. :type conn_string: string :returns: A backend ``Client`` instance
[ "Given", "a", "DSN", "returns", "an", "instantiated", "backend", "class", "." ]
f18bcb35b350fc6b0886393f5246d69c892b36c7
https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L51-L70
244,833
toastdriven/alligator
alligator/gator.py
Gator.push
def push(self, task, func, *args, **kwargs): """ Pushes a configured task onto the queue. Typically, you'll favor using the ``Gator.task`` method or ``Gator.options`` context manager for creating a task. Call this only if you have specific needs or know what you're doing. If the ``Task`` has the ``async = False`` option, the task will be run immediately (in-process). This is useful for development and in testing. Ex:: task = Task(async=False, retries=3) finished = gator.push(task, increment, incr_by=2) :param task: A mostly-configured task :type task: A ``Task`` instance :param func: The callable with business logic to execute :type func: callable :param args: Positional arguments to pass to the callable task :type args: list :param kwargs: Keyword arguments to pass to the callable task :type kwargs: dict :returns: The ``Task`` instance """ task.to_call(func, *args, **kwargs) data = task.serialize() if task.async: task.task_id = self.backend.push( self.queue_name, task.task_id, data ) else: self.execute(task) return task
python
def push(self, task, func, *args, **kwargs): """ Pushes a configured task onto the queue. Typically, you'll favor using the ``Gator.task`` method or ``Gator.options`` context manager for creating a task. Call this only if you have specific needs or know what you're doing. If the ``Task`` has the ``async = False`` option, the task will be run immediately (in-process). This is useful for development and in testing. Ex:: task = Task(async=False, retries=3) finished = gator.push(task, increment, incr_by=2) :param task: A mostly-configured task :type task: A ``Task`` instance :param func: The callable with business logic to execute :type func: callable :param args: Positional arguments to pass to the callable task :type args: list :param kwargs: Keyword arguments to pass to the callable task :type kwargs: dict :returns: The ``Task`` instance """ task.to_call(func, *args, **kwargs) data = task.serialize() if task.async: task.task_id = self.backend.push( self.queue_name, task.task_id, data ) else: self.execute(task) return task
[ "def", "push", "(", "self", ",", "task", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "task", ".", "to_call", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "data", "=", "task", ".", "serialize", "(", ")", "if", "task", ".", "async", ":", "task", ".", "task_id", "=", "self", ".", "backend", ".", "push", "(", "self", ".", "queue_name", ",", "task", ".", "task_id", ",", "data", ")", "else", ":", "self", ".", "execute", "(", "task", ")", "return", "task" ]
Pushes a configured task onto the queue. Typically, you'll favor using the ``Gator.task`` method or ``Gator.options`` context manager for creating a task. Call this only if you have specific needs or know what you're doing. If the ``Task`` has the ``async = False`` option, the task will be run immediately (in-process). This is useful for development and in testing. Ex:: task = Task(async=False, retries=3) finished = gator.push(task, increment, incr_by=2) :param task: A mostly-configured task :type task: A ``Task`` instance :param func: The callable with business logic to execute :type func: callable :param args: Positional arguments to pass to the callable task :type args: list :param kwargs: Keyword arguments to pass to the callable task :type kwargs: dict :returns: The ``Task`` instance
[ "Pushes", "a", "configured", "task", "onto", "the", "queue", "." ]
f18bcb35b350fc6b0886393f5246d69c892b36c7
https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L80-L123
244,834
toastdriven/alligator
alligator/gator.py
Gator.pop
def pop(self): """ Pops a task off the front of the queue & runs it. Typically, you'll favor using a ``Worker`` to handle processing the queue (to constantly consume). However, if you need to custom-process the queue in-order, this method is useful. Ex:: # Tasks were previously added, maybe by a different process or # machine... finished_topmost_task = gator.pop() :returns: The completed ``Task`` instance """ data = self.backend.pop(self.queue_name) if data: task = self.task_class.deserialize(data) return self.execute(task)
python
def pop(self): """ Pops a task off the front of the queue & runs it. Typically, you'll favor using a ``Worker`` to handle processing the queue (to constantly consume). However, if you need to custom-process the queue in-order, this method is useful. Ex:: # Tasks were previously added, maybe by a different process or # machine... finished_topmost_task = gator.pop() :returns: The completed ``Task`` instance """ data = self.backend.pop(self.queue_name) if data: task = self.task_class.deserialize(data) return self.execute(task)
[ "def", "pop", "(", "self", ")", ":", "data", "=", "self", ".", "backend", ".", "pop", "(", "self", ".", "queue_name", ")", "if", "data", ":", "task", "=", "self", ".", "task_class", ".", "deserialize", "(", "data", ")", "return", "self", ".", "execute", "(", "task", ")" ]
Pops a task off the front of the queue & runs it. Typically, you'll favor using a ``Worker`` to handle processing the queue (to constantly consume). However, if you need to custom-process the queue in-order, this method is useful. Ex:: # Tasks were previously added, maybe by a different process or # machine... finished_topmost_task = gator.pop() :returns: The completed ``Task`` instance
[ "Pops", "a", "task", "off", "the", "front", "of", "the", "queue", "&", "runs", "it", "." ]
f18bcb35b350fc6b0886393f5246d69c892b36c7
https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L125-L145
244,835
toastdriven/alligator
alligator/gator.py
Gator.get
def get(self, task_id): """ Gets a specific task, by ``task_id`` off the queue & runs it. Using this is not as performant (because it has to search the queue), but can be useful if you need to specifically handle a task *right now*. Ex:: # Tasks were previously added, maybe by a different process or # machine... finished_task = gator.get('a-specific-uuid-here') :param task_id: The identifier of the task to process :type task_id: string :returns: The completed ``Task`` instance """ data = self.backend.get(self.queue_name, task_id) if data: task = self.task_class.deserialize(data) return self.execute(task)
python
def get(self, task_id): """ Gets a specific task, by ``task_id`` off the queue & runs it. Using this is not as performant (because it has to search the queue), but can be useful if you need to specifically handle a task *right now*. Ex:: # Tasks were previously added, maybe by a different process or # machine... finished_task = gator.get('a-specific-uuid-here') :param task_id: The identifier of the task to process :type task_id: string :returns: The completed ``Task`` instance """ data = self.backend.get(self.queue_name, task_id) if data: task = self.task_class.deserialize(data) return self.execute(task)
[ "def", "get", "(", "self", ",", "task_id", ")", ":", "data", "=", "self", ".", "backend", ".", "get", "(", "self", ".", "queue_name", ",", "task_id", ")", "if", "data", ":", "task", "=", "self", ".", "task_class", ".", "deserialize", "(", "data", ")", "return", "self", ".", "execute", "(", "task", ")" ]
Gets a specific task, by ``task_id`` off the queue & runs it. Using this is not as performant (because it has to search the queue), but can be useful if you need to specifically handle a task *right now*. Ex:: # Tasks were previously added, maybe by a different process or # machine... finished_task = gator.get('a-specific-uuid-here') :param task_id: The identifier of the task to process :type task_id: string :returns: The completed ``Task`` instance
[ "Gets", "a", "specific", "task", "by", "task_id", "off", "the", "queue", "&", "runs", "it", "." ]
f18bcb35b350fc6b0886393f5246d69c892b36c7
https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L147-L169
244,836
toastdriven/alligator
alligator/gator.py
Gator.cancel
def cancel(self, task_id): """ Takes an existing task & cancels it before it is processed. Returns the canceled task, as that could be useful in creating a new task. Ex:: task = gator.task(add, 18, 9) # Whoops, didn't mean to do that. gator.cancel(task.task_id) :param task_id: The identifier of the task to process :type task_id: string :returns: The canceled ``Task`` instance """ data = self.backend.get(self.queue_name, task_id) if data: task = self.task_class.deserialize(data) task.to_canceled() return task
python
def cancel(self, task_id): """ Takes an existing task & cancels it before it is processed. Returns the canceled task, as that could be useful in creating a new task. Ex:: task = gator.task(add, 18, 9) # Whoops, didn't mean to do that. gator.cancel(task.task_id) :param task_id: The identifier of the task to process :type task_id: string :returns: The canceled ``Task`` instance """ data = self.backend.get(self.queue_name, task_id) if data: task = self.task_class.deserialize(data) task.to_canceled() return task
[ "def", "cancel", "(", "self", ",", "task_id", ")", ":", "data", "=", "self", ".", "backend", ".", "get", "(", "self", ".", "queue_name", ",", "task_id", ")", "if", "data", ":", "task", "=", "self", ".", "task_class", ".", "deserialize", "(", "data", ")", "task", ".", "to_canceled", "(", ")", "return", "task" ]
Takes an existing task & cancels it before it is processed. Returns the canceled task, as that could be useful in creating a new task. Ex:: task = gator.task(add, 18, 9) # Whoops, didn't mean to do that. gator.cancel(task.task_id) :param task_id: The identifier of the task to process :type task_id: string :returns: The canceled ``Task`` instance
[ "Takes", "an", "existing", "task", "&", "cancels", "it", "before", "it", "is", "processed", "." ]
f18bcb35b350fc6b0886393f5246d69c892b36c7
https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L171-L195
244,837
toastdriven/alligator
alligator/gator.py
Gator.execute
def execute(self, task): """ Given a task instance, this runs it. This includes handling retries & re-raising exceptions. Ex:: task = Task(async=False, retries=5) task.to_call(add, 101, 35) finished_task = gator.execute(task) :param task_id: The identifier of the task to process :type task_id: string :returns: The completed ``Task`` instance """ try: return task.run() except Exception: if task.retries > 0: task.retries -= 1 task.to_retrying() if task.async: # Place it back on the queue. data = task.serialize() task.task_id = self.backend.push( self.queue_name, task.task_id, data ) else: return self.execute(task) else: raise
python
def execute(self, task): """ Given a task instance, this runs it. This includes handling retries & re-raising exceptions. Ex:: task = Task(async=False, retries=5) task.to_call(add, 101, 35) finished_task = gator.execute(task) :param task_id: The identifier of the task to process :type task_id: string :returns: The completed ``Task`` instance """ try: return task.run() except Exception: if task.retries > 0: task.retries -= 1 task.to_retrying() if task.async: # Place it back on the queue. data = task.serialize() task.task_id = self.backend.push( self.queue_name, task.task_id, data ) else: return self.execute(task) else: raise
[ "def", "execute", "(", "self", ",", "task", ")", ":", "try", ":", "return", "task", ".", "run", "(", ")", "except", "Exception", ":", "if", "task", ".", "retries", ">", "0", ":", "task", ".", "retries", "-=", "1", "task", ".", "to_retrying", "(", ")", "if", "task", ".", "async", ":", "# Place it back on the queue.", "data", "=", "task", ".", "serialize", "(", ")", "task", ".", "task_id", "=", "self", ".", "backend", ".", "push", "(", "self", ".", "queue_name", ",", "task", ".", "task_id", ",", "data", ")", "else", ":", "return", "self", ".", "execute", "(", "task", ")", "else", ":", "raise" ]
Given a task instance, this runs it. This includes handling retries & re-raising exceptions. Ex:: task = Task(async=False, retries=5) task.to_call(add, 101, 35) finished_task = gator.execute(task) :param task_id: The identifier of the task to process :type task_id: string :returns: The completed ``Task`` instance
[ "Given", "a", "task", "instance", "this", "runs", "it", "." ]
f18bcb35b350fc6b0886393f5246d69c892b36c7
https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L197-L232
244,838
ronaldguillen/wave
wave/fields.py
is_simple_callable
def is_simple_callable(obj): """ True if the object is a callable that takes no arguments. """ function = inspect.isfunction(obj) method = inspect.ismethod(obj) if not (function or method): return False args, _, _, defaults = inspect.getargspec(obj) len_args = len(args) if function else len(args) - 1 len_defaults = len(defaults) if defaults else 0 return len_args <= len_defaults
python
def is_simple_callable(obj): """ True if the object is a callable that takes no arguments. """ function = inspect.isfunction(obj) method = inspect.ismethod(obj) if not (function or method): return False args, _, _, defaults = inspect.getargspec(obj) len_args = len(args) if function else len(args) - 1 len_defaults = len(defaults) if defaults else 0 return len_args <= len_defaults
[ "def", "is_simple_callable", "(", "obj", ")", ":", "function", "=", "inspect", ".", "isfunction", "(", "obj", ")", "method", "=", "inspect", ".", "ismethod", "(", "obj", ")", "if", "not", "(", "function", "or", "method", ")", ":", "return", "False", "args", ",", "_", ",", "_", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "obj", ")", "len_args", "=", "len", "(", "args", ")", "if", "function", "else", "len", "(", "args", ")", "-", "1", "len_defaults", "=", "len", "(", "defaults", ")", "if", "defaults", "else", "0", "return", "len_args", "<=", "len_defaults" ]
True if the object is a callable that takes no arguments.
[ "True", "if", "the", "object", "is", "a", "callable", "that", "takes", "no", "arguments", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L49-L62
244,839
ronaldguillen/wave
wave/fields.py
flatten_choices_dict
def flatten_choices_dict(choices): """ Convert a group choices dict into a flat dict of choices. flatten_choices({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'} flatten_choices({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'} """ ret = OrderedDict() for key, value in choices.items(): if isinstance(value, dict): # grouped choices (category, sub choices) for sub_key, sub_value in value.items(): ret[sub_key] = sub_value else: # choice (key, display value) ret[key] = value return ret
python
def flatten_choices_dict(choices): """ Convert a group choices dict into a flat dict of choices. flatten_choices({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'} flatten_choices({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'} """ ret = OrderedDict() for key, value in choices.items(): if isinstance(value, dict): # grouped choices (category, sub choices) for sub_key, sub_value in value.items(): ret[sub_key] = sub_value else: # choice (key, display value) ret[key] = value return ret
[ "def", "flatten_choices_dict", "(", "choices", ")", ":", "ret", "=", "OrderedDict", "(", ")", "for", "key", ",", "value", "in", "choices", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "# grouped choices (category, sub choices)", "for", "sub_key", ",", "sub_value", "in", "value", ".", "items", "(", ")", ":", "ret", "[", "sub_key", "]", "=", "sub_value", "else", ":", "# choice (key, display value)", "ret", "[", "key", "]", "=", "value", "return", "ret" ]
Convert a group choices dict into a flat dict of choices. flatten_choices({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'} flatten_choices({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'}
[ "Convert", "a", "group", "choices", "dict", "into", "a", "flat", "dict", "of", "choices", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L144-L160
244,840
ronaldguillen/wave
wave/fields.py
iter_options
def iter_options(grouped_choices, cutoff=None, cutoff_text=None): """ Helper function for options and option groups in templates. """ class StartOptionGroup(object): start_option_group = True end_option_group = False def __init__(self, label): self.label = label class EndOptionGroup(object): start_option_group = False end_option_group = True class Option(object): start_option_group = False end_option_group = False def __init__(self, value, display_text, disabled=False): self.value = value self.display_text = display_text self.disabled = disabled count = 0 for key, value in grouped_choices.items(): if cutoff and count >= cutoff: break if isinstance(value, dict): yield StartOptionGroup(label=key) for sub_key, sub_value in value.items(): if cutoff and count >= cutoff: break yield Option(value=sub_key, display_text=sub_value) count += 1 yield EndOptionGroup() else: yield Option(value=key, display_text=value) count += 1 if cutoff and count >= cutoff and cutoff_text: cutoff_text = cutoff_text.format(count=cutoff) yield Option(value='n/a', display_text=cutoff_text, disabled=True)
python
def iter_options(grouped_choices, cutoff=None, cutoff_text=None): """ Helper function for options and option groups in templates. """ class StartOptionGroup(object): start_option_group = True end_option_group = False def __init__(self, label): self.label = label class EndOptionGroup(object): start_option_group = False end_option_group = True class Option(object): start_option_group = False end_option_group = False def __init__(self, value, display_text, disabled=False): self.value = value self.display_text = display_text self.disabled = disabled count = 0 for key, value in grouped_choices.items(): if cutoff and count >= cutoff: break if isinstance(value, dict): yield StartOptionGroup(label=key) for sub_key, sub_value in value.items(): if cutoff and count >= cutoff: break yield Option(value=sub_key, display_text=sub_value) count += 1 yield EndOptionGroup() else: yield Option(value=key, display_text=value) count += 1 if cutoff and count >= cutoff and cutoff_text: cutoff_text = cutoff_text.format(count=cutoff) yield Option(value='n/a', display_text=cutoff_text, disabled=True)
[ "def", "iter_options", "(", "grouped_choices", ",", "cutoff", "=", "None", ",", "cutoff_text", "=", "None", ")", ":", "class", "StartOptionGroup", "(", "object", ")", ":", "start_option_group", "=", "True", "end_option_group", "=", "False", "def", "__init__", "(", "self", ",", "label", ")", ":", "self", ".", "label", "=", "label", "class", "EndOptionGroup", "(", "object", ")", ":", "start_option_group", "=", "False", "end_option_group", "=", "True", "class", "Option", "(", "object", ")", ":", "start_option_group", "=", "False", "end_option_group", "=", "False", "def", "__init__", "(", "self", ",", "value", ",", "display_text", ",", "disabled", "=", "False", ")", ":", "self", ".", "value", "=", "value", "self", ".", "display_text", "=", "display_text", "self", ".", "disabled", "=", "disabled", "count", "=", "0", "for", "key", ",", "value", "in", "grouped_choices", ".", "items", "(", ")", ":", "if", "cutoff", "and", "count", ">=", "cutoff", ":", "break", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "yield", "StartOptionGroup", "(", "label", "=", "key", ")", "for", "sub_key", ",", "sub_value", "in", "value", ".", "items", "(", ")", ":", "if", "cutoff", "and", "count", ">=", "cutoff", ":", "break", "yield", "Option", "(", "value", "=", "sub_key", ",", "display_text", "=", "sub_value", ")", "count", "+=", "1", "yield", "EndOptionGroup", "(", ")", "else", ":", "yield", "Option", "(", "value", "=", "key", ",", "display_text", "=", "value", ")", "count", "+=", "1", "if", "cutoff", "and", "count", ">=", "cutoff", "and", "cutoff_text", ":", "cutoff_text", "=", "cutoff_text", ".", "format", "(", "count", "=", "cutoff", ")", "yield", "Option", "(", "value", "=", "'n/a'", ",", "display_text", "=", "cutoff_text", ",", "disabled", "=", "True", ")" ]
Helper function for options and option groups in templates.
[ "Helper", "function", "for", "options", "and", "option", "groups", "in", "templates", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L163-L207
244,841
ronaldguillen/wave
wave/fields.py
Field.get_default
def get_default(self): """ Return the default value to use when validating data if no input is provided for this field. If a default has not been set for this field then this will simply return `empty`, indicating that no value should be set in the validated data for this field. """ if self.default is empty: raise SkipField() if callable(self.default): if hasattr(self.default, 'set_context'): self.default.set_context(self) return self.default() return self.default
python
def get_default(self): """ Return the default value to use when validating data if no input is provided for this field. If a default has not been set for this field then this will simply return `empty`, indicating that no value should be set in the validated data for this field. """ if self.default is empty: raise SkipField() if callable(self.default): if hasattr(self.default, 'set_context'): self.default.set_context(self) return self.default() return self.default
[ "def", "get_default", "(", "self", ")", ":", "if", "self", ".", "default", "is", "empty", ":", "raise", "SkipField", "(", ")", "if", "callable", "(", "self", ".", "default", ")", ":", "if", "hasattr", "(", "self", ".", "default", ",", "'set_context'", ")", ":", "self", ".", "default", ".", "set_context", "(", "self", ")", "return", "self", ".", "default", "(", ")", "return", "self", ".", "default" ]
Return the default value to use when validating data if no input is provided for this field. If a default has not been set for this field then this will simply return `empty`, indicating that no value should be set in the validated data for this field.
[ "Return", "the", "default", "value", "to", "use", "when", "validating", "data", "if", "no", "input", "is", "provided", "for", "this", "field", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L424-L439
244,842
ronaldguillen/wave
wave/fields.py
Field.run_validators
def run_validators(self, value): """ Test the given value against all the validators on the field, and either raise a `ValidationError` or simply return. """ errors = [] for validator in self.validators: if hasattr(validator, 'set_context'): validator.set_context(self) try: validator(value) except ValidationError as exc: # If the validation error contains a mapping of fields to # errors then simply raise it immediately rather than # attempting to accumulate a list of errors. if isinstance(exc.detail, dict): raise errors.extend(exc.detail) except DjangoValidationError as exc: errors.extend(exc.messages) if errors: raise ValidationError(errors)
python
def run_validators(self, value): """ Test the given value against all the validators on the field, and either raise a `ValidationError` or simply return. """ errors = [] for validator in self.validators: if hasattr(validator, 'set_context'): validator.set_context(self) try: validator(value) except ValidationError as exc: # If the validation error contains a mapping of fields to # errors then simply raise it immediately rather than # attempting to accumulate a list of errors. if isinstance(exc.detail, dict): raise errors.extend(exc.detail) except DjangoValidationError as exc: errors.extend(exc.messages) if errors: raise ValidationError(errors)
[ "def", "run_validators", "(", "self", ",", "value", ")", ":", "errors", "=", "[", "]", "for", "validator", "in", "self", ".", "validators", ":", "if", "hasattr", "(", "validator", ",", "'set_context'", ")", ":", "validator", ".", "set_context", "(", "self", ")", "try", ":", "validator", "(", "value", ")", "except", "ValidationError", "as", "exc", ":", "# If the validation error contains a mapping of fields to", "# errors then simply raise it immediately rather than", "# attempting to accumulate a list of errors.", "if", "isinstance", "(", "exc", ".", "detail", ",", "dict", ")", ":", "raise", "errors", ".", "extend", "(", "exc", ".", "detail", ")", "except", "DjangoValidationError", "as", "exc", ":", "errors", ".", "extend", "(", "exc", ".", "messages", ")", "if", "errors", ":", "raise", "ValidationError", "(", "errors", ")" ]
Test the given value against all the validators on the field, and either raise a `ValidationError` or simply return.
[ "Test", "the", "given", "value", "against", "all", "the", "validators", "on", "the", "field", "and", "either", "raise", "a", "ValidationError", "or", "simply", "return", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L486-L508
244,843
ronaldguillen/wave
wave/fields.py
Field.root
def root(self): """ Returns the top-level serializer for this field. """ root = self while root.parent is not None: root = root.parent return root
python
def root(self): """ Returns the top-level serializer for this field. """ root = self while root.parent is not None: root = root.parent return root
[ "def", "root", "(", "self", ")", ":", "root", "=", "self", "while", "root", ".", "parent", "is", "not", "None", ":", "root", "=", "root", ".", "parent", "return", "root" ]
Returns the top-level serializer for this field.
[ "Returns", "the", "top", "-", "level", "serializer", "for", "this", "field", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L547-L554
244,844
ronaldguillen/wave
wave/fields.py
DecimalField.to_internal_value
def to_internal_value(self, data): """ Validate that the input is a decimal number and return a Decimal instance. """ data = smart_text(data).strip() if len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: value = decimal.Decimal(data) except decimal.DecimalException: self.fail('invalid') # Check for NaN. It is the only value that isn't equal to itself, # so we can use this to identify NaN values. if value != value: self.fail('invalid') # Check for infinity and negative infinity. if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')): self.fail('invalid') return self.validate_precision(value)
python
def to_internal_value(self, data): """ Validate that the input is a decimal number and return a Decimal instance. """ data = smart_text(data).strip() if len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: value = decimal.Decimal(data) except decimal.DecimalException: self.fail('invalid') # Check for NaN. It is the only value that isn't equal to itself, # so we can use this to identify NaN values. if value != value: self.fail('invalid') # Check for infinity and negative infinity. if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')): self.fail('invalid') return self.validate_precision(value)
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "data", "=", "smart_text", "(", "data", ")", ".", "strip", "(", ")", "if", "len", "(", "data", ")", ">", "self", ".", "MAX_STRING_LENGTH", ":", "self", ".", "fail", "(", "'max_string_length'", ")", "try", ":", "value", "=", "decimal", ".", "Decimal", "(", "data", ")", "except", "decimal", ".", "DecimalException", ":", "self", ".", "fail", "(", "'invalid'", ")", "# Check for NaN. It is the only value that isn't equal to itself,", "# so we can use this to identify NaN values.", "if", "value", "!=", "value", ":", "self", ".", "fail", "(", "'invalid'", ")", "# Check for infinity and negative infinity.", "if", "value", "in", "(", "decimal", ".", "Decimal", "(", "'Inf'", ")", ",", "decimal", ".", "Decimal", "(", "'-Inf'", ")", ")", ":", "self", ".", "fail", "(", "'invalid'", ")", "return", "self", ".", "validate_precision", "(", "value", ")" ]
Validate that the input is a decimal number and return a Decimal instance.
[ "Validate", "that", "the", "input", "is", "a", "decimal", "number", "and", "return", "a", "Decimal", "instance", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L917-L940
244,845
ronaldguillen/wave
wave/fields.py
DecimalField.validate_precision
def validate_precision(self, value): """ Ensure that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. Override this method to disable the precision validation for input values or to enhance it in any way you need to. """ sign, digittuple, exponent = value.as_tuple() if exponent >= 0: # 1234500.0 total_digits = len(digittuple) + exponent whole_digits = total_digits decimal_places = 0 elif len(digittuple) > abs(exponent): # 123.45 total_digits = len(digittuple) whole_digits = total_digits - abs(exponent) decimal_places = abs(exponent) else: # 0.001234 total_digits = abs(exponent) whole_digits = 0 decimal_places = total_digits if self.max_digits is not None and total_digits > self.max_digits: self.fail('max_digits', max_digits=self.max_digits) if self.decimal_places is not None and decimal_places > self.decimal_places: self.fail('max_decimal_places', max_decimal_places=self.decimal_places) if self.max_whole_digits is not None and whole_digits > self.max_whole_digits: self.fail('max_whole_digits', max_whole_digits=self.max_whole_digits) return value
python
def validate_precision(self, value): """ Ensure that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. Override this method to disable the precision validation for input values or to enhance it in any way you need to. """ sign, digittuple, exponent = value.as_tuple() if exponent >= 0: # 1234500.0 total_digits = len(digittuple) + exponent whole_digits = total_digits decimal_places = 0 elif len(digittuple) > abs(exponent): # 123.45 total_digits = len(digittuple) whole_digits = total_digits - abs(exponent) decimal_places = abs(exponent) else: # 0.001234 total_digits = abs(exponent) whole_digits = 0 decimal_places = total_digits if self.max_digits is not None and total_digits > self.max_digits: self.fail('max_digits', max_digits=self.max_digits) if self.decimal_places is not None and decimal_places > self.decimal_places: self.fail('max_decimal_places', max_decimal_places=self.decimal_places) if self.max_whole_digits is not None and whole_digits > self.max_whole_digits: self.fail('max_whole_digits', max_whole_digits=self.max_whole_digits) return value
[ "def", "validate_precision", "(", "self", ",", "value", ")", ":", "sign", ",", "digittuple", ",", "exponent", "=", "value", ".", "as_tuple", "(", ")", "if", "exponent", ">=", "0", ":", "# 1234500.0", "total_digits", "=", "len", "(", "digittuple", ")", "+", "exponent", "whole_digits", "=", "total_digits", "decimal_places", "=", "0", "elif", "len", "(", "digittuple", ")", ">", "abs", "(", "exponent", ")", ":", "# 123.45", "total_digits", "=", "len", "(", "digittuple", ")", "whole_digits", "=", "total_digits", "-", "abs", "(", "exponent", ")", "decimal_places", "=", "abs", "(", "exponent", ")", "else", ":", "# 0.001234", "total_digits", "=", "abs", "(", "exponent", ")", "whole_digits", "=", "0", "decimal_places", "=", "total_digits", "if", "self", ".", "max_digits", "is", "not", "None", "and", "total_digits", ">", "self", ".", "max_digits", ":", "self", ".", "fail", "(", "'max_digits'", ",", "max_digits", "=", "self", ".", "max_digits", ")", "if", "self", ".", "decimal_places", "is", "not", "None", "and", "decimal_places", ">", "self", ".", "decimal_places", ":", "self", ".", "fail", "(", "'max_decimal_places'", ",", "max_decimal_places", "=", "self", ".", "decimal_places", ")", "if", "self", ".", "max_whole_digits", "is", "not", "None", "and", "whole_digits", ">", "self", ".", "max_whole_digits", ":", "self", ".", "fail", "(", "'max_whole_digits'", ",", "max_whole_digits", "=", "self", ".", "max_whole_digits", ")", "return", "value" ]
Ensure that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. Override this method to disable the precision validation for input values or to enhance it in any way you need to.
[ "Ensure", "that", "there", "are", "no", "more", "than", "max_digits", "in", "the", "number", "and", "no", "more", "than", "decimal_places", "digits", "after", "the", "decimal", "point", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L942-L975
244,846
ronaldguillen/wave
wave/fields.py
DecimalField.quantize
def quantize(self, value): """ Quantize the decimal value to the configured precision. """ context = decimal.getcontext().copy() context.prec = self.max_digits return value.quantize( decimal.Decimal('.1') ** self.decimal_places, context=context)
python
def quantize(self, value): """ Quantize the decimal value to the configured precision. """ context = decimal.getcontext().copy() context.prec = self.max_digits return value.quantize( decimal.Decimal('.1') ** self.decimal_places, context=context)
[ "def", "quantize", "(", "self", ",", "value", ")", ":", "context", "=", "decimal", ".", "getcontext", "(", ")", ".", "copy", "(", ")", "context", ".", "prec", "=", "self", ".", "max_digits", "return", "value", ".", "quantize", "(", "decimal", ".", "Decimal", "(", "'.1'", ")", "**", "self", ".", "decimal_places", ",", "context", "=", "context", ")" ]
Quantize the decimal value to the configured precision.
[ "Quantize", "the", "decimal", "value", "to", "the", "configured", "precision", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L989-L997
244,847
ronaldguillen/wave
wave/fields.py
DictField.to_representation
def to_representation(self, value): """ List of object instances -> List of dicts of primitive datatypes. """ return { six.text_type(key): self.child.to_representation(val) for key, val in value.items() }
python
def to_representation(self, value): """ List of object instances -> List of dicts of primitive datatypes. """ return { six.text_type(key): self.child.to_representation(val) for key, val in value.items() }
[ "def", "to_representation", "(", "self", ",", "value", ")", ":", "return", "{", "six", ".", "text_type", "(", "key", ")", ":", "self", ".", "child", ".", "to_representation", "(", "val", ")", "for", "key", ",", "val", "in", "value", ".", "items", "(", ")", "}" ]
List of object instances -> List of dicts of primitive datatypes.
[ "List", "of", "object", "instances", "-", ">", "List", "of", "dicts", "of", "primitive", "datatypes", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L1524-L1531
244,848
KnightHawk3/Hummingbird
hummingbird/__init__.py
Hummingbird._query_
def _query_(self, path, method, params={}): """Used internally for requests. :param str path: The path to hit. :param str method: The method to use, either `'GET'` or `'POST.` :param dict data: The optional paramters to the `GET` or the data to `POST`. :returns: Requests object -- Requires you to handle the status codes yourself. """ if method == "POST": url = '{API_URL}{API_PATH}'.format(API_URL=self.api_url, API_PATH=path) r = requests.post(url, data=json.dumps(params), headers=self.headers) return r elif method == "GET": url = '{API_URL}{API_PATH}'.format(API_URL=self.api_url, API_PATH=path) r = requests.get(url, params=params, headers=self.headers) return r
python
def _query_(self, path, method, params={}): """Used internally for requests. :param str path: The path to hit. :param str method: The method to use, either `'GET'` or `'POST.` :param dict data: The optional paramters to the `GET` or the data to `POST`. :returns: Requests object -- Requires you to handle the status codes yourself. """ if method == "POST": url = '{API_URL}{API_PATH}'.format(API_URL=self.api_url, API_PATH=path) r = requests.post(url, data=json.dumps(params), headers=self.headers) return r elif method == "GET": url = '{API_URL}{API_PATH}'.format(API_URL=self.api_url, API_PATH=path) r = requests.get(url, params=params, headers=self.headers) return r
[ "def", "_query_", "(", "self", ",", "path", ",", "method", ",", "params", "=", "{", "}", ")", ":", "if", "method", "==", "\"POST\"", ":", "url", "=", "'{API_URL}{API_PATH}'", ".", "format", "(", "API_URL", "=", "self", ".", "api_url", ",", "API_PATH", "=", "path", ")", "r", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "params", ")", ",", "headers", "=", "self", ".", "headers", ")", "return", "r", "elif", "method", "==", "\"GET\"", ":", "url", "=", "'{API_URL}{API_PATH}'", ".", "format", "(", "API_URL", "=", "self", ".", "api_url", ",", "API_PATH", "=", "path", ")", "r", "=", "requests", ".", "get", "(", "url", ",", "params", "=", "params", ",", "headers", "=", "self", ".", "headers", ")", "return", "r" ]
Used internally for requests. :param str path: The path to hit. :param str method: The method to use, either `'GET'` or `'POST.` :param dict data: The optional paramters to the `GET` or the data to `POST`. :returns: Requests object -- Requires you to handle the status codes yourself.
[ "Used", "internally", "for", "requests", "." ]
10b918534b112c95a93f04dd76bfb7479c4f3f21
https://github.com/KnightHawk3/Hummingbird/blob/10b918534b112c95a93f04dd76bfb7479c4f3f21/hummingbird/__init__.py#L27-L50
244,849
KnightHawk3/Hummingbird
hummingbird/__init__.py
Hummingbird.authenticate
def authenticate(self, username, password): """Authenticates your user and returns an auth token. :param str username: Hummingbird username. :param str password: Hummingbird password. :returns: str -- The Auth Token :raises: ValueError -- If the Authentication is wrong """ r = self._query_('/users/authenticate', 'POST', params={'username': username, 'password': password}) if r.status_code == 201: return r.text.strip('"') else: raise ValueError('Authentication invalid.')
python
def authenticate(self, username, password): """Authenticates your user and returns an auth token. :param str username: Hummingbird username. :param str password: Hummingbird password. :returns: str -- The Auth Token :raises: ValueError -- If the Authentication is wrong """ r = self._query_('/users/authenticate', 'POST', params={'username': username, 'password': password}) if r.status_code == 201: return r.text.strip('"') else: raise ValueError('Authentication invalid.')
[ "def", "authenticate", "(", "self", ",", "username", ",", "password", ")", ":", "r", "=", "self", ".", "_query_", "(", "'/users/authenticate'", ",", "'POST'", ",", "params", "=", "{", "'username'", ":", "username", ",", "'password'", ":", "password", "}", ")", "if", "r", ".", "status_code", "==", "201", ":", "return", "r", ".", "text", ".", "strip", "(", "'\"'", ")", "else", ":", "raise", "ValueError", "(", "'Authentication invalid.'", ")" ]
Authenticates your user and returns an auth token. :param str username: Hummingbird username. :param str password: Hummingbird password. :returns: str -- The Auth Token :raises: ValueError -- If the Authentication is wrong
[ "Authenticates", "your", "user", "and", "returns", "an", "auth", "token", "." ]
10b918534b112c95a93f04dd76bfb7479c4f3f21
https://github.com/KnightHawk3/Hummingbird/blob/10b918534b112c95a93f04dd76bfb7479c4f3f21/hummingbird/__init__.py#L52-L67
244,850
KnightHawk3/Hummingbird
hummingbird/__init__.py
Hummingbird.get_anime
def get_anime(self, anime_id, title_language='canonical'): """Fetches the Anime Object of the given id or slug. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str title_language: The PREFERED title language can be any of `'canonical'`, `'english'`, `'romanized'` :returns: Anime Object -- The Anime you requested. """ r = self._query_('/anime/%s' % anime_id, 'GET', params={'title_language_preference': title_language}) return Anime(r.json())
python
def get_anime(self, anime_id, title_language='canonical'): """Fetches the Anime Object of the given id or slug. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str title_language: The PREFERED title language can be any of `'canonical'`, `'english'`, `'romanized'` :returns: Anime Object -- The Anime you requested. """ r = self._query_('/anime/%s' % anime_id, 'GET', params={'title_language_preference': title_language}) return Anime(r.json())
[ "def", "get_anime", "(", "self", ",", "anime_id", ",", "title_language", "=", "'canonical'", ")", ":", "r", "=", "self", ".", "_query_", "(", "'/anime/%s'", "%", "anime_id", ",", "'GET'", ",", "params", "=", "{", "'title_language_preference'", ":", "title_language", "}", ")", "return", "Anime", "(", "r", ".", "json", "(", ")", ")" ]
Fetches the Anime Object of the given id or slug. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str title_language: The PREFERED title language can be any of `'canonical'`, `'english'`, `'romanized'` :returns: Anime Object -- The Anime you requested.
[ "Fetches", "the", "Anime", "Object", "of", "the", "given", "id", "or", "slug", "." ]
10b918534b112c95a93f04dd76bfb7479c4f3f21
https://github.com/KnightHawk3/Hummingbird/blob/10b918534b112c95a93f04dd76bfb7479c4f3f21/hummingbird/__init__.py#L69-L81
244,851
KnightHawk3/Hummingbird
hummingbird/__init__.py
Hummingbird.search_anime
def search_anime(self, query): """Fuzzy searches the Anime Database for the query. :param str query: The text to fuzzy search. :returns: List of Anime Objects. This list can be empty. """ r = self._query_('/search/anime', 'GET', params={'query': query}) results = [Anime(item) for item in r.json()] return results
python
def search_anime(self, query): """Fuzzy searches the Anime Database for the query. :param str query: The text to fuzzy search. :returns: List of Anime Objects. This list can be empty. """ r = self._query_('/search/anime', 'GET', params={'query': query}) results = [Anime(item) for item in r.json()] return results
[ "def", "search_anime", "(", "self", ",", "query", ")", ":", "r", "=", "self", ".", "_query_", "(", "'/search/anime'", ",", "'GET'", ",", "params", "=", "{", "'query'", ":", "query", "}", ")", "results", "=", "[", "Anime", "(", "item", ")", "for", "item", "in", "r", ".", "json", "(", ")", "]", "return", "results" ]
Fuzzy searches the Anime Database for the query. :param str query: The text to fuzzy search. :returns: List of Anime Objects. This list can be empty.
[ "Fuzzy", "searches", "the", "Anime", "Database", "for", "the", "query", "." ]
10b918534b112c95a93f04dd76bfb7479c4f3f21
https://github.com/KnightHawk3/Hummingbird/blob/10b918534b112c95a93f04dd76bfb7479c4f3f21/hummingbird/__init__.py#L83-L94
244,852
KnightHawk3/Hummingbird
hummingbird/__init__.py
Hummingbird.get_library
def get_library(self, username, status=None): """Fetches a users library. :param str username: The user to get the library from. :param str status: only return the items with the supplied status. Can be one of `currently-watching`, `plan-to-watch`, `completed`, `on-hold` or `dropped`. :returns: List of Library objects. """ r = self._query_('/users/%s/library' % username, 'GET', params={'status': status}) results = [LibraryEntry(item) for item in r.json()] return results
python
def get_library(self, username, status=None): """Fetches a users library. :param str username: The user to get the library from. :param str status: only return the items with the supplied status. Can be one of `currently-watching`, `plan-to-watch`, `completed`, `on-hold` or `dropped`. :returns: List of Library objects. """ r = self._query_('/users/%s/library' % username, 'GET', params={'status': status}) results = [LibraryEntry(item) for item in r.json()] return results
[ "def", "get_library", "(", "self", ",", "username", ",", "status", "=", "None", ")", ":", "r", "=", "self", ".", "_query_", "(", "'/users/%s/library'", "%", "username", ",", "'GET'", ",", "params", "=", "{", "'status'", ":", "status", "}", ")", "results", "=", "[", "LibraryEntry", "(", "item", ")", "for", "item", "in", "r", ".", "json", "(", ")", "]", "return", "results" ]
Fetches a users library. :param str username: The user to get the library from. :param str status: only return the items with the supplied status. Can be one of `currently-watching`, `plan-to-watch`, `completed`, `on-hold` or `dropped`. :returns: List of Library objects.
[ "Fetches", "a", "users", "library", "." ]
10b918534b112c95a93f04dd76bfb7479c4f3f21
https://github.com/KnightHawk3/Hummingbird/blob/10b918534b112c95a93f04dd76bfb7479c4f3f21/hummingbird/__init__.py#L96-L111
244,853
KnightHawk3/Hummingbird
hummingbird/__init__.py
Hummingbird.get_feed
def get_feed(self, username): """Gets a user's feed. :param str username: User to fetch feed from. """ r = self._query_('/users/%s/feed' % username, 'GET') results = [Story(item) for item in r.json()] return results
python
def get_feed(self, username): """Gets a user's feed. :param str username: User to fetch feed from. """ r = self._query_('/users/%s/feed' % username, 'GET') results = [Story(item) for item in r.json()] return results
[ "def", "get_feed", "(", "self", ",", "username", ")", ":", "r", "=", "self", ".", "_query_", "(", "'/users/%s/feed'", "%", "username", ",", "'GET'", ")", "results", "=", "[", "Story", "(", "item", ")", "for", "item", "in", "r", ".", "json", "(", ")", "]", "return", "results" ]
Gets a user's feed. :param str username: User to fetch feed from.
[ "Gets", "a", "user", "s", "feed", "." ]
10b918534b112c95a93f04dd76bfb7479c4f3f21
https://github.com/KnightHawk3/Hummingbird/blob/10b918534b112c95a93f04dd76bfb7479c4f3f21/hummingbird/__init__.py#L124-L134
244,854
KnightHawk3/Hummingbird
hummingbird/__init__.py
Hummingbird.get_favorites
def get_favorites(self, username): """Get a user's favorite anime. :param str username: User to get favorites from. """ r = self._query_('/users/%s/favorite_anime' % username, 'GET') results = [Favorite(item) for item in r.json()] return results
python
def get_favorites(self, username): """Get a user's favorite anime. :param str username: User to get favorites from. """ r = self._query_('/users/%s/favorite_anime' % username, 'GET') results = [Favorite(item) for item in r.json()] return results
[ "def", "get_favorites", "(", "self", ",", "username", ")", ":", "r", "=", "self", ".", "_query_", "(", "'/users/%s/favorite_anime'", "%", "username", ",", "'GET'", ")", "results", "=", "[", "Favorite", "(", "item", ")", "for", "item", "in", "r", ".", "json", "(", ")", "]", "return", "results" ]
Get a user's favorite anime. :param str username: User to get favorites from.
[ "Get", "a", "user", "s", "favorite", "anime", "." ]
10b918534b112c95a93f04dd76bfb7479c4f3f21
https://github.com/KnightHawk3/Hummingbird/blob/10b918534b112c95a93f04dd76bfb7479c4f3f21/hummingbird/__init__.py#L136-L145
244,855
KnightHawk3/Hummingbird
hummingbird/__init__.py
Hummingbird.update_entry
def update_entry(self, anime_id, status=None, privacy=None, rating=None, sane_rating_update=None, rewatched_times=None, notes=None, episodes_watched=None, increment_episodes=None): """Creates or updates the Library entry with the provided values. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str auth_token: User authentication token. :param str status: Can be one of `'currently-watching'`, `'plan-to-watch'`, `'completed'`, `'on-hold'`, `'dropped'`. :param str privacy: Can be one of `'public'`, `'private'`. Making an entry private will hide it from public view. :param rating: Can be one of `0`, `0.5`, `1`, `1.5`, `2`, `2.5`, `3`, `3.5`, `4`, `4.5`, `5`. Setting it to the current value or 0 will remove the rating. :type rating: str, int or float :param sane_rating_update: Can be any one of the values for rating. Setting it to 0 will remove the rating. This should be used instead of rating if you don't want to unset the rating when setting it to its current value. :type sane_rating_update: str, int or float :param int rewatched_times: Number of rewatches. Can be 0 or above. :param str notes: The personal notes for the entry. :param int episodes_watched: Number of watched episodes. Can be between 0 and the total number of episodes. If equal to total number of episodes, status should be set to completed. :param bool increment_episodes: If set to true, increments watched episodes by one. If used along with episodes_watched, provided value will be incremented. :raises: ValueError -- if Authentication Token is invalid (it shouldn't be), or if there is a `500 Internal Server Error` or if the response is `Invalid JSON Object`. """ r = self._query_('/libraries/%s' % anime_id, 'POST', { 'auth_token': self.auth_token, 'status': status, 'privacy': privacy, 'rating': rating, 'sane_rating_update': sane_rating_update, 'rewatched_times': rewatched_times, 'notes': notes, 'episodes_watched': episodes_watched, 'increment_episodes': increment_episodes}) if not (r.status_code == 200 or r.status_code == 201): raise ValueError
python
def update_entry(self, anime_id, status=None, privacy=None, rating=None, sane_rating_update=None, rewatched_times=None, notes=None, episodes_watched=None, increment_episodes=None): """Creates or updates the Library entry with the provided values. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str auth_token: User authentication token. :param str status: Can be one of `'currently-watching'`, `'plan-to-watch'`, `'completed'`, `'on-hold'`, `'dropped'`. :param str privacy: Can be one of `'public'`, `'private'`. Making an entry private will hide it from public view. :param rating: Can be one of `0`, `0.5`, `1`, `1.5`, `2`, `2.5`, `3`, `3.5`, `4`, `4.5`, `5`. Setting it to the current value or 0 will remove the rating. :type rating: str, int or float :param sane_rating_update: Can be any one of the values for rating. Setting it to 0 will remove the rating. This should be used instead of rating if you don't want to unset the rating when setting it to its current value. :type sane_rating_update: str, int or float :param int rewatched_times: Number of rewatches. Can be 0 or above. :param str notes: The personal notes for the entry. :param int episodes_watched: Number of watched episodes. Can be between 0 and the total number of episodes. If equal to total number of episodes, status should be set to completed. :param bool increment_episodes: If set to true, increments watched episodes by one. If used along with episodes_watched, provided value will be incremented. :raises: ValueError -- if Authentication Token is invalid (it shouldn't be), or if there is a `500 Internal Server Error` or if the response is `Invalid JSON Object`. """ r = self._query_('/libraries/%s' % anime_id, 'POST', { 'auth_token': self.auth_token, 'status': status, 'privacy': privacy, 'rating': rating, 'sane_rating_update': sane_rating_update, 'rewatched_times': rewatched_times, 'notes': notes, 'episodes_watched': episodes_watched, 'increment_episodes': increment_episodes}) if not (r.status_code == 200 or r.status_code == 201): raise ValueError
[ "def", "update_entry", "(", "self", ",", "anime_id", ",", "status", "=", "None", ",", "privacy", "=", "None", ",", "rating", "=", "None", ",", "sane_rating_update", "=", "None", ",", "rewatched_times", "=", "None", ",", "notes", "=", "None", ",", "episodes_watched", "=", "None", ",", "increment_episodes", "=", "None", ")", ":", "r", "=", "self", ".", "_query_", "(", "'/libraries/%s'", "%", "anime_id", ",", "'POST'", ",", "{", "'auth_token'", ":", "self", ".", "auth_token", ",", "'status'", ":", "status", ",", "'privacy'", ":", "privacy", ",", "'rating'", ":", "rating", ",", "'sane_rating_update'", ":", "sane_rating_update", ",", "'rewatched_times'", ":", "rewatched_times", ",", "'notes'", ":", "notes", ",", "'episodes_watched'", ":", "episodes_watched", ",", "'increment_episodes'", ":", "increment_episodes", "}", ")", "if", "not", "(", "r", ".", "status_code", "==", "200", "or", "r", ".", "status_code", "==", "201", ")", ":", "raise", "ValueError" ]
Creates or updates the Library entry with the provided values. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str auth_token: User authentication token. :param str status: Can be one of `'currently-watching'`, `'plan-to-watch'`, `'completed'`, `'on-hold'`, `'dropped'`. :param str privacy: Can be one of `'public'`, `'private'`. Making an entry private will hide it from public view. :param rating: Can be one of `0`, `0.5`, `1`, `1.5`, `2`, `2.5`, `3`, `3.5`, `4`, `4.5`, `5`. Setting it to the current value or 0 will remove the rating. :type rating: str, int or float :param sane_rating_update: Can be any one of the values for rating. Setting it to 0 will remove the rating. This should be used instead of rating if you don't want to unset the rating when setting it to its current value. :type sane_rating_update: str, int or float :param int rewatched_times: Number of rewatches. Can be 0 or above. :param str notes: The personal notes for the entry. :param int episodes_watched: Number of watched episodes. Can be between 0 and the total number of episodes. If equal to total number of episodes, status should be set to completed. :param bool increment_episodes: If set to true, increments watched episodes by one. If used along with episodes_watched, provided value will be incremented. :raises: ValueError -- if Authentication Token is invalid (it shouldn't be), or if there is a `500 Internal Server Error` or if the response is `Invalid JSON Object`.
[ "Creates", "or", "updates", "the", "Library", "entry", "with", "the", "provided", "values", "." ]
10b918534b112c95a93f04dd76bfb7479c4f3f21
https://github.com/KnightHawk3/Hummingbird/blob/10b918534b112c95a93f04dd76bfb7479c4f3f21/hummingbird/__init__.py#L147-L195
244,856
KnightHawk3/Hummingbird
hummingbird/__init__.py
Hummingbird.remove_entry
def remove_entry(self, anime_id): """Removes an entry from the user's library. :param anime_id: The Anime ID or slug. """ r = self._query_('libraries/%s/remove' % anime_id, 'POST') if not r.status_code == 200: raise ValueError
python
def remove_entry(self, anime_id): """Removes an entry from the user's library. :param anime_id: The Anime ID or slug. """ r = self._query_('libraries/%s/remove' % anime_id, 'POST') if not r.status_code == 200: raise ValueError
[ "def", "remove_entry", "(", "self", ",", "anime_id", ")", ":", "r", "=", "self", ".", "_query_", "(", "'libraries/%s/remove'", "%", "anime_id", ",", "'POST'", ")", "if", "not", "r", ".", "status_code", "==", "200", ":", "raise", "ValueError" ]
Removes an entry from the user's library. :param anime_id: The Anime ID or slug.
[ "Removes", "an", "entry", "from", "the", "user", "s", "library", "." ]
10b918534b112c95a93f04dd76bfb7479c4f3f21
https://github.com/KnightHawk3/Hummingbird/blob/10b918534b112c95a93f04dd76bfb7479c4f3f21/hummingbird/__init__.py#L197-L206
244,857
collectiveacuity/labPack
labpack/platforms/aws/ssh.py
sshClient.terminal
def terminal(self, confirmation=True): ''' method to open an SSH terminal inside AWS instance :param confirmation: [optional] boolean to prompt keypair confirmation :return: True ''' title = '%s.terminal' % self.__class__.__name__ # construct ssh command if confirmation: override_cmd = ' ' else: override_cmd = ' -o CheckHostIP=no ' sys_command = 'ssh -i %s%s%s@%s' % (self.pem_file, override_cmd, self.login_name, self.instance_ip) self.ec2.iam.printer(sys_command) # send shell script command to open up terminal if self.localhost.os.sysname in ('Windows'): raise Exception('%s is not supported on Windows. try using putty.exe') try: import os os.system(sys_command) # TODO: check into making sys_command OS independent except: raise AWSConnectionError(title) return True
python
def terminal(self, confirmation=True): ''' method to open an SSH terminal inside AWS instance :param confirmation: [optional] boolean to prompt keypair confirmation :return: True ''' title = '%s.terminal' % self.__class__.__name__ # construct ssh command if confirmation: override_cmd = ' ' else: override_cmd = ' -o CheckHostIP=no ' sys_command = 'ssh -i %s%s%s@%s' % (self.pem_file, override_cmd, self.login_name, self.instance_ip) self.ec2.iam.printer(sys_command) # send shell script command to open up terminal if self.localhost.os.sysname in ('Windows'): raise Exception('%s is not supported on Windows. try using putty.exe') try: import os os.system(sys_command) # TODO: check into making sys_command OS independent except: raise AWSConnectionError(title) return True
[ "def", "terminal", "(", "self", ",", "confirmation", "=", "True", ")", ":", "title", "=", "'%s.terminal'", "%", "self", ".", "__class__", ".", "__name__", "# construct ssh command", "if", "confirmation", ":", "override_cmd", "=", "' '", "else", ":", "override_cmd", "=", "' -o CheckHostIP=no '", "sys_command", "=", "'ssh -i %s%s%s@%s'", "%", "(", "self", ".", "pem_file", ",", "override_cmd", ",", "self", ".", "login_name", ",", "self", ".", "instance_ip", ")", "self", ".", "ec2", ".", "iam", ".", "printer", "(", "sys_command", ")", "# send shell script command to open up terminal", "if", "self", ".", "localhost", ".", "os", ".", "sysname", "in", "(", "'Windows'", ")", ":", "raise", "Exception", "(", "'%s is not supported on Windows. try using putty.exe'", ")", "try", ":", "import", "os", "os", ".", "system", "(", "sys_command", ")", "# TODO: check into making sys_command OS independent", "except", ":", "raise", "AWSConnectionError", "(", "title", ")", "return", "True" ]
method to open an SSH terminal inside AWS instance :param confirmation: [optional] boolean to prompt keypair confirmation :return: True
[ "method", "to", "open", "an", "SSH", "terminal", "inside", "AWS", "instance" ]
52949ece35e72e3cc308f54d9ffa6bfbd96805b8
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/aws/ssh.py#L197-L226
244,858
collectiveacuity/labPack
labpack/platforms/aws/ssh.py
sshClient.responsive
def responsive(self, port=80, timeout=600): ''' a method for waiting until web server on AWS instance has restarted :param port: integer with port number to check :param timeout: integer with number of seconds to continue to check :return: string with response code ''' title = '%s.wait' % self.__class__.__name__ from time import sleep # validate inputs input_fields = { 'port': port, 'timeout': timeout } for key, value in input_fields.items(): object_title = '%s(%s=%s)' % (title, key, str(value)) self.fields.validate(value, '.%s' % key, object_title) # construct parameters for request loop import requests waiting_msg = 'Waiting for http 200 response from %s' % self.instance_ip nonres_msg = 'Instance %s is not responding to requests at %s.' % ( self.instance_id, self.instance_ip) server_url = 'http://%s' % self.instance_ip if port: server_url += ':%s' % str(port) # initiate waiting loop self.ec2.iam.printer(waiting_msg, flush=True) t0 = timer() while True: t1 = timer() self.ec2.iam.printer('.', flush=True) try: response = requests.get(server_url, timeout=2) response_code = response.status_code if response_code >= 200 and response_code < 300: self.ec2.iam.printer(' done.') return response_code except: pass t2 = timer() if t2 - t0 > timeout: timeout_msg = 'Timeout [%ss]: %s' % (timeout, nonres_msg) raise TimeoutError(timeout_msg) response_time = t2 - t1 if 3 - response_time > 0: delay = 3 - response_time else: delay = 0 sleep(delay)
python
def responsive(self, port=80, timeout=600): ''' a method for waiting until web server on AWS instance has restarted :param port: integer with port number to check :param timeout: integer with number of seconds to continue to check :return: string with response code ''' title = '%s.wait' % self.__class__.__name__ from time import sleep # validate inputs input_fields = { 'port': port, 'timeout': timeout } for key, value in input_fields.items(): object_title = '%s(%s=%s)' % (title, key, str(value)) self.fields.validate(value, '.%s' % key, object_title) # construct parameters for request loop import requests waiting_msg = 'Waiting for http 200 response from %s' % self.instance_ip nonres_msg = 'Instance %s is not responding to requests at %s.' % ( self.instance_id, self.instance_ip) server_url = 'http://%s' % self.instance_ip if port: server_url += ':%s' % str(port) # initiate waiting loop self.ec2.iam.printer(waiting_msg, flush=True) t0 = timer() while True: t1 = timer() self.ec2.iam.printer('.', flush=True) try: response = requests.get(server_url, timeout=2) response_code = response.status_code if response_code >= 200 and response_code < 300: self.ec2.iam.printer(' done.') return response_code except: pass t2 = timer() if t2 - t0 > timeout: timeout_msg = 'Timeout [%ss]: %s' % (timeout, nonres_msg) raise TimeoutError(timeout_msg) response_time = t2 - t1 if 3 - response_time > 0: delay = 3 - response_time else: delay = 0 sleep(delay)
[ "def", "responsive", "(", "self", ",", "port", "=", "80", ",", "timeout", "=", "600", ")", ":", "title", "=", "'%s.wait'", "%", "self", ".", "__class__", ".", "__name__", "from", "time", "import", "sleep", "# validate inputs", "input_fields", "=", "{", "'port'", ":", "port", ",", "'timeout'", ":", "timeout", "}", "for", "key", ",", "value", "in", "input_fields", ".", "items", "(", ")", ":", "object_title", "=", "'%s(%s=%s)'", "%", "(", "title", ",", "key", ",", "str", "(", "value", ")", ")", "self", ".", "fields", ".", "validate", "(", "value", ",", "'.%s'", "%", "key", ",", "object_title", ")", "# construct parameters for request loop", "import", "requests", "waiting_msg", "=", "'Waiting for http 200 response from %s'", "%", "self", ".", "instance_ip", "nonres_msg", "=", "'Instance %s is not responding to requests at %s.'", "%", "(", "self", ".", "instance_id", ",", "self", ".", "instance_ip", ")", "server_url", "=", "'http://%s'", "%", "self", ".", "instance_ip", "if", "port", ":", "server_url", "+=", "':%s'", "%", "str", "(", "port", ")", "# initiate waiting loop", "self", ".", "ec2", ".", "iam", ".", "printer", "(", "waiting_msg", ",", "flush", "=", "True", ")", "t0", "=", "timer", "(", ")", "while", "True", ":", "t1", "=", "timer", "(", ")", "self", ".", "ec2", ".", "iam", ".", "printer", "(", "'.'", ",", "flush", "=", "True", ")", "try", ":", "response", "=", "requests", ".", "get", "(", "server_url", ",", "timeout", "=", "2", ")", "response_code", "=", "response", ".", "status_code", "if", "response_code", ">=", "200", "and", "response_code", "<", "300", ":", "self", ".", "ec2", ".", "iam", ".", "printer", "(", "' done.'", ")", "return", "response_code", "except", ":", "pass", "t2", "=", "timer", "(", ")", "if", "t2", "-", "t0", ">", "timeout", ":", "timeout_msg", "=", "'Timeout [%ss]: %s'", "%", "(", "timeout", ",", "nonres_msg", ")", "raise", "TimeoutError", "(", "timeout_msg", ")", "response_time", "=", "t2", "-", "t1", "if", "3", "-", "response_time", ">", "0", ":", "delay", "=", "3", "-", "response_time", "else", ":", "delay", "=", "0", "sleep", "(", "delay", ")" ]
a method for waiting until web server on AWS instance has restarted :param port: integer with port number to check :param timeout: integer with number of seconds to continue to check :return: string with response code
[ "a", "method", "for", "waiting", "until", "web", "server", "on", "AWS", "instance", "has", "restarted" ]
52949ece35e72e3cc308f54d9ffa6bfbd96805b8
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/aws/ssh.py#L667-L721
244,859
nefarioustim/parker
parker/mediafile.py
get_instance
def get_instance(uri): """Return an instance of MediaFile.""" global _instances try: instance = _instances[uri] except KeyError: instance = MediaFile( uri, client.get_instance() ) _instances[uri] = instance return instance
python
def get_instance(uri): """Return an instance of MediaFile.""" global _instances try: instance = _instances[uri] except KeyError: instance = MediaFile( uri, client.get_instance() ) _instances[uri] = instance return instance
[ "def", "get_instance", "(", "uri", ")", ":", "global", "_instances", "try", ":", "instance", "=", "_instances", "[", "uri", "]", "except", "KeyError", ":", "instance", "=", "MediaFile", "(", "uri", ",", "client", ".", "get_instance", "(", ")", ")", "_instances", "[", "uri", "]", "=", "instance", "return", "instance" ]
Return an instance of MediaFile.
[ "Return", "an", "instance", "of", "MediaFile", "." ]
ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6
https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/mediafile.py#L14-L26
244,860
nefarioustim/parker
parker/mediafile.py
MediaFile.fetch_to_file
def fetch_to_file(self, filename): """Stream the MediaFile to the filesystem.""" self.filename = filename stream = self.client.get_iter_content(self.uri) content_type = self.client.response_headers['content-type'] if content_type in _content_type_map: self.fileext = _content_type_map[content_type] self.filename = "%s.%s" % (self.filename, self.fileext) with open(self.filename, 'wb') as file_handle: for chunk in stream: file_handle.write(chunk)
python
def fetch_to_file(self, filename): """Stream the MediaFile to the filesystem.""" self.filename = filename stream = self.client.get_iter_content(self.uri) content_type = self.client.response_headers['content-type'] if content_type in _content_type_map: self.fileext = _content_type_map[content_type] self.filename = "%s.%s" % (self.filename, self.fileext) with open(self.filename, 'wb') as file_handle: for chunk in stream: file_handle.write(chunk)
[ "def", "fetch_to_file", "(", "self", ",", "filename", ")", ":", "self", ".", "filename", "=", "filename", "stream", "=", "self", ".", "client", ".", "get_iter_content", "(", "self", ".", "uri", ")", "content_type", "=", "self", ".", "client", ".", "response_headers", "[", "'content-type'", "]", "if", "content_type", "in", "_content_type_map", ":", "self", ".", "fileext", "=", "_content_type_map", "[", "content_type", "]", "self", ".", "filename", "=", "\"%s.%s\"", "%", "(", "self", ".", "filename", ",", "self", ".", "fileext", ")", "with", "open", "(", "self", ".", "filename", ",", "'wb'", ")", "as", "file_handle", ":", "for", "chunk", "in", "stream", ":", "file_handle", ".", "write", "(", "chunk", ")" ]
Stream the MediaFile to the filesystem.
[ "Stream", "the", "MediaFile", "to", "the", "filesystem", "." ]
ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6
https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/mediafile.py#L44-L56
244,861
mbodenhamer/syn
syn/base_utils/list.py
is_unique
def is_unique(seq): '''Returns True if every item in the seq is unique, False otherwise.''' try: s = set(seq) return len(s) == len(seq) except TypeError: buf = [] for item in seq: if item in buf: return False buf.append(item) return True
python
def is_unique(seq): '''Returns True if every item in the seq is unique, False otherwise.''' try: s = set(seq) return len(s) == len(seq) except TypeError: buf = [] for item in seq: if item in buf: return False buf.append(item) return True
[ "def", "is_unique", "(", "seq", ")", ":", "try", ":", "s", "=", "set", "(", "seq", ")", "return", "len", "(", "s", ")", "==", "len", "(", "seq", ")", "except", "TypeError", ":", "buf", "=", "[", "]", "for", "item", "in", "seq", ":", "if", "item", "in", "buf", ":", "return", "False", "buf", ".", "append", "(", "item", ")", "return", "True" ]
Returns True if every item in the seq is unique, False otherwise.
[ "Returns", "True", "if", "every", "item", "in", "the", "seq", "is", "unique", "False", "otherwise", "." ]
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/list.py#L211-L222
244,862
mbodenhamer/syn
syn/base_utils/list.py
indices_removed
def indices_removed(lst, idxs): '''Returns a copy of lst with each index in idxs removed.''' ret = [item for k,item in enumerate(lst) if k not in idxs] return type(lst)(ret)
python
def indices_removed(lst, idxs): '''Returns a copy of lst with each index in idxs removed.''' ret = [item for k,item in enumerate(lst) if k not in idxs] return type(lst)(ret)
[ "def", "indices_removed", "(", "lst", ",", "idxs", ")", ":", "ret", "=", "[", "item", "for", "k", ",", "item", "in", "enumerate", "(", "lst", ")", "if", "k", "not", "in", "idxs", "]", "return", "type", "(", "lst", ")", "(", "ret", ")" ]
Returns a copy of lst with each index in idxs removed.
[ "Returns", "a", "copy", "of", "lst", "with", "each", "index", "in", "idxs", "removed", "." ]
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/list.py#L227-L230
244,863
CS207-Final-Project-Group-10/cs207-FinalProject
fluxions/elementary_functions.py
_deriv_hypot
def _deriv_hypot(x, y): """Derivative of numpy hypot function""" r = np.hypot(x, y) df_dx = x / r df_dy = y / r return np.hstack([df_dx, df_dy])
python
def _deriv_hypot(x, y): """Derivative of numpy hypot function""" r = np.hypot(x, y) df_dx = x / r df_dy = y / r return np.hstack([df_dx, df_dy])
[ "def", "_deriv_hypot", "(", "x", ",", "y", ")", ":", "r", "=", "np", ".", "hypot", "(", "x", ",", "y", ")", "df_dx", "=", "x", "/", "r", "df_dy", "=", "y", "/", "r", "return", "np", ".", "hstack", "(", "[", "df_dx", ",", "df_dy", "]", ")" ]
Derivative of numpy hypot function
[ "Derivative", "of", "numpy", "hypot", "function" ]
842e9c2d3ca1490cef18c086dfde81856d8d3a82
https://github.com/CS207-Final-Project-Group-10/cs207-FinalProject/blob/842e9c2d3ca1490cef18c086dfde81856d8d3a82/fluxions/elementary_functions.py#L200-L205
244,864
CS207-Final-Project-Group-10/cs207-FinalProject
fluxions/elementary_functions.py
_deriv_arctan2
def _deriv_arctan2(y, x): """Derivative of the arctan2 function""" r2 = x*x + y*y df_dy = x / r2 df_dx = -y / r2 return np.hstack([df_dy, df_dx])
python
def _deriv_arctan2(y, x): """Derivative of the arctan2 function""" r2 = x*x + y*y df_dy = x / r2 df_dx = -y / r2 return np.hstack([df_dy, df_dx])
[ "def", "_deriv_arctan2", "(", "y", ",", "x", ")", ":", "r2", "=", "x", "*", "x", "+", "y", "*", "y", "df_dy", "=", "x", "/", "r2", "df_dx", "=", "-", "y", "/", "r2", "return", "np", ".", "hstack", "(", "[", "df_dy", ",", "df_dx", "]", ")" ]
Derivative of the arctan2 function
[ "Derivative", "of", "the", "arctan2", "function" ]
842e9c2d3ca1490cef18c086dfde81856d8d3a82
https://github.com/CS207-Final-Project-Group-10/cs207-FinalProject/blob/842e9c2d3ca1490cef18c086dfde81856d8d3a82/fluxions/elementary_functions.py#L211-L216
244,865
lambdalisue/maidenhair
src/maidenhair/classification/classify.py
default_classify_function
def default_classify_function(data): """ A default classify_function which recieve `data` and return filename without characters just after the last underscore >>> # [<filename>] is mimicking `data` >>> default_classify_function(['./foo/foo_bar_hoge.piyo']) './foo/foo_bar.piyo' >>> default_classify_function(['./foo/foo_bar.piyo']) './foo/foo.piyo' >>> default_classify_function(['./foo/foo.piyo']) './foo/foo.piyo' >>> default_classify_function(['./foo/foo']) './foo/foo' """ # data[0] indicate the filename of the data rootname, basename = os.path.split(data[0]) filename, ext = os.path.splitext(basename) if '_' in filename: filename = filename.rsplit('_', 1)[0] filename = os.path.join(rootname, filename + ext) return filename
python
def default_classify_function(data): """ A default classify_function which recieve `data` and return filename without characters just after the last underscore >>> # [<filename>] is mimicking `data` >>> default_classify_function(['./foo/foo_bar_hoge.piyo']) './foo/foo_bar.piyo' >>> default_classify_function(['./foo/foo_bar.piyo']) './foo/foo.piyo' >>> default_classify_function(['./foo/foo.piyo']) './foo/foo.piyo' >>> default_classify_function(['./foo/foo']) './foo/foo' """ # data[0] indicate the filename of the data rootname, basename = os.path.split(data[0]) filename, ext = os.path.splitext(basename) if '_' in filename: filename = filename.rsplit('_', 1)[0] filename = os.path.join(rootname, filename + ext) return filename
[ "def", "default_classify_function", "(", "data", ")", ":", "# data[0] indicate the filename of the data", "rootname", ",", "basename", "=", "os", ".", "path", ".", "split", "(", "data", "[", "0", "]", ")", "filename", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "basename", ")", "if", "'_'", "in", "filename", ":", "filename", "=", "filename", ".", "rsplit", "(", "'_'", ",", "1", ")", "[", "0", "]", "filename", "=", "os", ".", "path", ".", "join", "(", "rootname", ",", "filename", "+", "ext", ")", "return", "filename" ]
A default classify_function which recieve `data` and return filename without characters just after the last underscore >>> # [<filename>] is mimicking `data` >>> default_classify_function(['./foo/foo_bar_hoge.piyo']) './foo/foo_bar.piyo' >>> default_classify_function(['./foo/foo_bar.piyo']) './foo/foo.piyo' >>> default_classify_function(['./foo/foo.piyo']) './foo/foo.piyo' >>> default_classify_function(['./foo/foo']) './foo/foo'
[ "A", "default", "classify_function", "which", "recieve", "data", "and", "return", "filename", "without", "characters", "just", "after", "the", "last", "underscore" ]
d5095c1087d1f4d71cc57410492151d2803a9f0d
https://github.com/lambdalisue/maidenhair/blob/d5095c1087d1f4d71cc57410492151d2803a9f0d/src/maidenhair/classification/classify.py#L10-L31
244,866
lambdalisue/maidenhair
src/maidenhair/classification/classify.py
classify_dataset
def classify_dataset(dataset, fn): """ Classify dataset via fn Parameters ---------- dataset : list A list of data fn : function A function which recieve :attr:`data` and return classification string. It if is None, a function which return the first item of the :attr:`data` will be used (See ``with_filename`` parameter of :func:`maidenhair.load` function). Returns ------- dict A classified dataset """ if fn is None: fn = default_classify_function # classify dataset via classify_fn classified_dataset = OrderedDict() for data in dataset: classify_name = fn(data) if classify_name not in classified_dataset: classified_dataset[classify_name] = [] classified_dataset[classify_name].append(data) return classified_dataset
python
def classify_dataset(dataset, fn): """ Classify dataset via fn Parameters ---------- dataset : list A list of data fn : function A function which recieve :attr:`data` and return classification string. It if is None, a function which return the first item of the :attr:`data` will be used (See ``with_filename`` parameter of :func:`maidenhair.load` function). Returns ------- dict A classified dataset """ if fn is None: fn = default_classify_function # classify dataset via classify_fn classified_dataset = OrderedDict() for data in dataset: classify_name = fn(data) if classify_name not in classified_dataset: classified_dataset[classify_name] = [] classified_dataset[classify_name].append(data) return classified_dataset
[ "def", "classify_dataset", "(", "dataset", ",", "fn", ")", ":", "if", "fn", "is", "None", ":", "fn", "=", "default_classify_function", "# classify dataset via classify_fn", "classified_dataset", "=", "OrderedDict", "(", ")", "for", "data", "in", "dataset", ":", "classify_name", "=", "fn", "(", "data", ")", "if", "classify_name", "not", "in", "classified_dataset", ":", "classified_dataset", "[", "classify_name", "]", "=", "[", "]", "classified_dataset", "[", "classify_name", "]", ".", "append", "(", "data", ")", "return", "classified_dataset" ]
Classify dataset via fn Parameters ---------- dataset : list A list of data fn : function A function which recieve :attr:`data` and return classification string. It if is None, a function which return the first item of the :attr:`data` will be used (See ``with_filename`` parameter of :func:`maidenhair.load` function). Returns ------- dict A classified dataset
[ "Classify", "dataset", "via", "fn" ]
d5095c1087d1f4d71cc57410492151d2803a9f0d
https://github.com/lambdalisue/maidenhair/blob/d5095c1087d1f4d71cc57410492151d2803a9f0d/src/maidenhair/classification/classify.py#L34-L62
244,867
lockwooddev/python-nasapi
nasapi/api.py
Nasapi.get_apod
def get_apod(cls, date=None, hd=False): """ Returns Astronomy Picture of the Day Args: date: date instance (default = today) hd: bool if high resolution should be included Returns: json """ instance = cls('planetary/apod') filters = { 'date': date, 'hd': hd } return instance.get_resource(**filters)
python
def get_apod(cls, date=None, hd=False): """ Returns Astronomy Picture of the Day Args: date: date instance (default = today) hd: bool if high resolution should be included Returns: json """ instance = cls('planetary/apod') filters = { 'date': date, 'hd': hd } return instance.get_resource(**filters)
[ "def", "get_apod", "(", "cls", ",", "date", "=", "None", ",", "hd", "=", "False", ")", ":", "instance", "=", "cls", "(", "'planetary/apod'", ")", "filters", "=", "{", "'date'", ":", "date", ",", "'hd'", ":", "hd", "}", "return", "instance", ".", "get_resource", "(", "*", "*", "filters", ")" ]
Returns Astronomy Picture of the Day Args: date: date instance (default = today) hd: bool if high resolution should be included Returns: json
[ "Returns", "Astronomy", "Picture", "of", "the", "Day" ]
b487dd834c91b8a125a10c9b4b996ed2380da498
https://github.com/lockwooddev/python-nasapi/blob/b487dd834c91b8a125a10c9b4b996ed2380da498/nasapi/api.py#L72-L90
244,868
lockwooddev/python-nasapi
nasapi/api.py
Nasapi.get_assets
def get_assets(cls, lat, lon, begin=None, end=None): """ Returns date and ids of flyovers Args: lat: latitude float lon: longitude float begin: date instance end: date instance Returns: json """ instance = cls('planetary/earth/assets') filters = { 'lat': lat, 'lon': lon, 'begin': begin, 'end': end, } return instance.get_resource(**filters)
python
def get_assets(cls, lat, lon, begin=None, end=None): """ Returns date and ids of flyovers Args: lat: latitude float lon: longitude float begin: date instance end: date instance Returns: json """ instance = cls('planetary/earth/assets') filters = { 'lat': lat, 'lon': lon, 'begin': begin, 'end': end, } return instance.get_resource(**filters)
[ "def", "get_assets", "(", "cls", ",", "lat", ",", "lon", ",", "begin", "=", "None", ",", "end", "=", "None", ")", ":", "instance", "=", "cls", "(", "'planetary/earth/assets'", ")", "filters", "=", "{", "'lat'", ":", "lat", ",", "'lon'", ":", "lon", ",", "'begin'", ":", "begin", ",", "'end'", ":", "end", ",", "}", "return", "instance", ".", "get_resource", "(", "*", "*", "filters", ")" ]
Returns date and ids of flyovers Args: lat: latitude float lon: longitude float begin: date instance end: date instance Returns: json
[ "Returns", "date", "and", "ids", "of", "flyovers" ]
b487dd834c91b8a125a10c9b4b996ed2380da498
https://github.com/lockwooddev/python-nasapi/blob/b487dd834c91b8a125a10c9b4b996ed2380da498/nasapi/api.py#L93-L115
244,869
lockwooddev/python-nasapi
nasapi/api.py
Nasapi.get_imagery
def get_imagery(cls, lat, lon, date=None, dim=None, cloud_score=False): """ Returns satellite image Args: lat: latitude float lon: longitude float date: date instance of available date from `get_assets` dim: width and height of image in degrees as float cloud_score: boolean to calculate the percentage of the image covered by clouds Returns: json """ instance = cls('planetary/earth/imagery') filters = { 'lat': lat, 'lon': lon, 'date': date, 'dim': dim, 'cloud_score': cloud_score } return instance.get_resource(**filters)
python
def get_imagery(cls, lat, lon, date=None, dim=None, cloud_score=False): """ Returns satellite image Args: lat: latitude float lon: longitude float date: date instance of available date from `get_assets` dim: width and height of image in degrees as float cloud_score: boolean to calculate the percentage of the image covered by clouds Returns: json """ instance = cls('planetary/earth/imagery') filters = { 'lat': lat, 'lon': lon, 'date': date, 'dim': dim, 'cloud_score': cloud_score } return instance.get_resource(**filters)
[ "def", "get_imagery", "(", "cls", ",", "lat", ",", "lon", ",", "date", "=", "None", ",", "dim", "=", "None", ",", "cloud_score", "=", "False", ")", ":", "instance", "=", "cls", "(", "'planetary/earth/imagery'", ")", "filters", "=", "{", "'lat'", ":", "lat", ",", "'lon'", ":", "lon", ",", "'date'", ":", "date", ",", "'dim'", ":", "dim", ",", "'cloud_score'", ":", "cloud_score", "}", "return", "instance", ".", "get_resource", "(", "*", "*", "filters", ")" ]
Returns satellite image Args: lat: latitude float lon: longitude float date: date instance of available date from `get_assets` dim: width and height of image in degrees as float cloud_score: boolean to calculate the percentage of the image covered by clouds Returns: json
[ "Returns", "satellite", "image" ]
b487dd834c91b8a125a10c9b4b996ed2380da498
https://github.com/lockwooddev/python-nasapi/blob/b487dd834c91b8a125a10c9b4b996ed2380da498/nasapi/api.py#L118-L142
244,870
etcher-be/emiz
emiz/avwx/core.py
valid_station
def valid_station(station: str): """ Checks the validity of a station ident This function doesn't return anything. It merely raises a BadStation error if needed """ station = station.strip() if len(station) != 4: raise BadStation('ICAO station idents must be four characters long') uses_na_format(station)
python
def valid_station(station: str): """ Checks the validity of a station ident This function doesn't return anything. It merely raises a BadStation error if needed """ station = station.strip() if len(station) != 4: raise BadStation('ICAO station idents must be four characters long') uses_na_format(station)
[ "def", "valid_station", "(", "station", ":", "str", ")", ":", "station", "=", "station", ".", "strip", "(", ")", "if", "len", "(", "station", ")", "!=", "4", ":", "raise", "BadStation", "(", "'ICAO station idents must be four characters long'", ")", "uses_na_format", "(", "station", ")" ]
Checks the validity of a station ident This function doesn't return anything. It merely raises a BadStation error if needed
[ "Checks", "the", "validity", "of", "a", "station", "ident" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L23-L32
244,871
etcher-be/emiz
emiz/avwx/core.py
uses_na_format
def uses_na_format(station: str) -> bool: """ Returns True if the station uses the North American format, False if the International format """ if station[0] in NA_REGIONS: return True if station[0] in IN_REGIONS: return False if station[:2] in M_NA_REGIONS: return True if station[:2] in M_IN_REGIONS: return False raise BadStation("Station doesn't start with a recognized character set")
python
def uses_na_format(station: str) -> bool: """ Returns True if the station uses the North American format, False if the International format """ if station[0] in NA_REGIONS: return True if station[0] in IN_REGIONS: return False if station[:2] in M_NA_REGIONS: return True if station[:2] in M_IN_REGIONS: return False raise BadStation("Station doesn't start with a recognized character set")
[ "def", "uses_na_format", "(", "station", ":", "str", ")", "->", "bool", ":", "if", "station", "[", "0", "]", "in", "NA_REGIONS", ":", "return", "True", "if", "station", "[", "0", "]", "in", "IN_REGIONS", ":", "return", "False", "if", "station", "[", ":", "2", "]", "in", "M_NA_REGIONS", ":", "return", "True", "if", "station", "[", ":", "2", "]", "in", "M_IN_REGIONS", ":", "return", "False", "raise", "BadStation", "(", "\"Station doesn't start with a recognized character set\"", ")" ]
Returns True if the station uses the North American format, False if the International format
[ "Returns", "True", "if", "the", "station", "uses", "the", "North", "American", "format", "False", "if", "the", "International", "format" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L35-L48
244,872
etcher-be/emiz
emiz/avwx/core.py
remove_leading_zeros
def remove_leading_zeros(num: str) -> str: """ Strips zeros while handling -, M, and empty strings """ if not num: return num if num.startswith('M'): ret = 'M' + num[1:].lstrip('0') elif num.startswith('-'): ret = '-' + num[1:].lstrip('0') else: ret = num.lstrip('0') return '0' if ret in ('', 'M', '-') else ret
python
def remove_leading_zeros(num: str) -> str: """ Strips zeros while handling -, M, and empty strings """ if not num: return num if num.startswith('M'): ret = 'M' + num[1:].lstrip('0') elif num.startswith('-'): ret = '-' + num[1:].lstrip('0') else: ret = num.lstrip('0') return '0' if ret in ('', 'M', '-') else ret
[ "def", "remove_leading_zeros", "(", "num", ":", "str", ")", "->", "str", ":", "if", "not", "num", ":", "return", "num", "if", "num", ".", "startswith", "(", "'M'", ")", ":", "ret", "=", "'M'", "+", "num", "[", "1", ":", "]", ".", "lstrip", "(", "'0'", ")", "elif", "num", ".", "startswith", "(", "'-'", ")", ":", "ret", "=", "'-'", "+", "num", "[", "1", ":", "]", ".", "lstrip", "(", "'0'", ")", "else", ":", "ret", "=", "num", ".", "lstrip", "(", "'0'", ")", "return", "'0'", "if", "ret", "in", "(", "''", ",", "'M'", ",", "'-'", ")", "else", "ret" ]
Strips zeros while handling -, M, and empty strings
[ "Strips", "zeros", "while", "handling", "-", "M", "and", "empty", "strings" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L73-L85
244,873
etcher-be/emiz
emiz/avwx/core.py
spoken_number
def spoken_number(num: str) -> str: """ Returns the spoken version of a number Ex: 1.2 -> one point two 1 1/2 -> one and one half """ ret = [] for part in num.split(' '): if part in FRACTIONS: ret.append(FRACTIONS[part]) else: ret.append(' '.join([NUMBER_REPL[char] for char in part if char in NUMBER_REPL])) return ' and '.join(ret)
python
def spoken_number(num: str) -> str: """ Returns the spoken version of a number Ex: 1.2 -> one point two 1 1/2 -> one and one half """ ret = [] for part in num.split(' '): if part in FRACTIONS: ret.append(FRACTIONS[part]) else: ret.append(' '.join([NUMBER_REPL[char] for char in part if char in NUMBER_REPL])) return ' and '.join(ret)
[ "def", "spoken_number", "(", "num", ":", "str", ")", "->", "str", ":", "ret", "=", "[", "]", "for", "part", "in", "num", ".", "split", "(", "' '", ")", ":", "if", "part", "in", "FRACTIONS", ":", "ret", ".", "append", "(", "FRACTIONS", "[", "part", "]", ")", "else", ":", "ret", ".", "append", "(", "' '", ".", "join", "(", "[", "NUMBER_REPL", "[", "char", "]", "for", "char", "in", "part", "if", "char", "in", "NUMBER_REPL", "]", ")", ")", "return", "' and '", ".", "join", "(", "ret", ")" ]
Returns the spoken version of a number Ex: 1.2 -> one point two 1 1/2 -> one and one half
[ "Returns", "the", "spoken", "version", "of", "a", "number" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L88-L101
244,874
etcher-be/emiz
emiz/avwx/core.py
make_number
def make_number(num: str, repr_: str = None, speak: str = None): """ Returns a Number or Fraction dataclass for a number string """ if not num or is_unknown(num): return # Check CAVOK if num == 'CAVOK': return Number('CAVOK', 9999, 'ceiling and visibility ok') # type: ignore # Check special if num in SPECIAL_NUMBERS: return Number(repr_ or num, None, SPECIAL_NUMBERS[num]) # type: ignore # Create Fraction if '/' in num: nmr, dnm = [int(i) for i in num.split('/')] unpacked = unpack_fraction(num) spoken = spoken_number(unpacked) return Fraction(repr_ or num, nmr / dnm, spoken, nmr, dnm, unpacked) # type: ignore # Create Number val = num.replace('M', '-') val = float(val) if '.' in num else int(val) # type: ignore return Number(repr_ or num, val, spoken_number(speak or str(val)))
python
def make_number(num: str, repr_: str = None, speak: str = None): """ Returns a Number or Fraction dataclass for a number string """ if not num or is_unknown(num): return # Check CAVOK if num == 'CAVOK': return Number('CAVOK', 9999, 'ceiling and visibility ok') # type: ignore # Check special if num in SPECIAL_NUMBERS: return Number(repr_ or num, None, SPECIAL_NUMBERS[num]) # type: ignore # Create Fraction if '/' in num: nmr, dnm = [int(i) for i in num.split('/')] unpacked = unpack_fraction(num) spoken = spoken_number(unpacked) return Fraction(repr_ or num, nmr / dnm, spoken, nmr, dnm, unpacked) # type: ignore # Create Number val = num.replace('M', '-') val = float(val) if '.' in num else int(val) # type: ignore return Number(repr_ or num, val, spoken_number(speak or str(val)))
[ "def", "make_number", "(", "num", ":", "str", ",", "repr_", ":", "str", "=", "None", ",", "speak", ":", "str", "=", "None", ")", ":", "if", "not", "num", "or", "is_unknown", "(", "num", ")", ":", "return", "# Check CAVOK", "if", "num", "==", "'CAVOK'", ":", "return", "Number", "(", "'CAVOK'", ",", "9999", ",", "'ceiling and visibility ok'", ")", "# type: ignore", "# Check special", "if", "num", "in", "SPECIAL_NUMBERS", ":", "return", "Number", "(", "repr_", "or", "num", ",", "None", ",", "SPECIAL_NUMBERS", "[", "num", "]", ")", "# type: ignore", "# Create Fraction", "if", "'/'", "in", "num", ":", "nmr", ",", "dnm", "=", "[", "int", "(", "i", ")", "for", "i", "in", "num", ".", "split", "(", "'/'", ")", "]", "unpacked", "=", "unpack_fraction", "(", "num", ")", "spoken", "=", "spoken_number", "(", "unpacked", ")", "return", "Fraction", "(", "repr_", "or", "num", ",", "nmr", "/", "dnm", ",", "spoken", ",", "nmr", ",", "dnm", ",", "unpacked", ")", "# type: ignore", "# Create Number", "val", "=", "num", ".", "replace", "(", "'M'", ",", "'-'", ")", "val", "=", "float", "(", "val", ")", "if", "'.'", "in", "num", "else", "int", "(", "val", ")", "# type: ignore", "return", "Number", "(", "repr_", "or", "num", ",", "val", ",", "spoken_number", "(", "speak", "or", "str", "(", "val", ")", ")", ")" ]
Returns a Number or Fraction dataclass for a number string
[ "Returns", "a", "Number", "or", "Fraction", "dataclass", "for", "a", "number", "string" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L104-L125
244,875
etcher-be/emiz
emiz/avwx/core.py
find_first_in_list
def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore """ Returns the index of the earliest occurence of an item from a list in a string Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3 """ start = len(txt) + 1 for item in str_list: if start > txt.find(item) > -1: start = txt.find(item) return start if len(txt) + 1 > start > -1 else -1
python
def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore """ Returns the index of the earliest occurence of an item from a list in a string Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3 """ start = len(txt) + 1 for item in str_list: if start > txt.find(item) > -1: start = txt.find(item) return start if len(txt) + 1 > start > -1 else -1
[ "def", "find_first_in_list", "(", "txt", ":", "str", ",", "str_list", ":", "[", "str", "]", ")", "->", "int", ":", "# type: ignore", "start", "=", "len", "(", "txt", ")", "+", "1", "for", "item", "in", "str_list", ":", "if", "start", ">", "txt", ".", "find", "(", "item", ")", ">", "-", "1", ":", "start", "=", "txt", ".", "find", "(", "item", ")", "return", "start", "if", "len", "(", "txt", ")", "+", "1", ">", "start", ">", "-", "1", "else", "-", "1" ]
Returns the index of the earliest occurence of an item from a list in a string Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3
[ "Returns", "the", "index", "of", "the", "earliest", "occurence", "of", "an", "item", "from", "a", "list", "in", "a", "string" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L128-L138
244,876
etcher-be/emiz
emiz/avwx/core.py
get_remarks
def get_remarks(txt: str) -> ([str], str): # type: ignore """ Returns the report split into components and the remarks string Remarks can include items like RMK and on, NOSIG and on, and BECMG and on """ txt = txt.replace('?', '').strip() # First look for Altimeter in txt alt_index = len(txt) + 1 for item in [' A2', ' A3', ' Q1', ' Q0', ' Q9']: index = txt.find(item) if len(txt) - 6 > index > -1 and txt[index + 2:index + 6].isdigit(): alt_index = index # Then look for earliest remarks 'signifier' sig_index = find_first_in_list(txt, METAR_RMK) if sig_index == -1: sig_index = len(txt) + 1 if sig_index > alt_index > -1: return txt[:alt_index + 6].strip().split(' '), txt[alt_index + 7:] if alt_index > sig_index > -1: return txt[:sig_index].strip().split(' '), txt[sig_index + 1:] return txt.strip().split(' '), ''
python
def get_remarks(txt: str) -> ([str], str): # type: ignore """ Returns the report split into components and the remarks string Remarks can include items like RMK and on, NOSIG and on, and BECMG and on """ txt = txt.replace('?', '').strip() # First look for Altimeter in txt alt_index = len(txt) + 1 for item in [' A2', ' A3', ' Q1', ' Q0', ' Q9']: index = txt.find(item) if len(txt) - 6 > index > -1 and txt[index + 2:index + 6].isdigit(): alt_index = index # Then look for earliest remarks 'signifier' sig_index = find_first_in_list(txt, METAR_RMK) if sig_index == -1: sig_index = len(txt) + 1 if sig_index > alt_index > -1: return txt[:alt_index + 6].strip().split(' '), txt[alt_index + 7:] if alt_index > sig_index > -1: return txt[:sig_index].strip().split(' '), txt[sig_index + 1:] return txt.strip().split(' '), ''
[ "def", "get_remarks", "(", "txt", ":", "str", ")", "->", "(", "[", "str", "]", ",", "str", ")", ":", "# type: ignore", "txt", "=", "txt", ".", "replace", "(", "'?'", ",", "''", ")", ".", "strip", "(", ")", "# First look for Altimeter in txt", "alt_index", "=", "len", "(", "txt", ")", "+", "1", "for", "item", "in", "[", "' A2'", ",", "' A3'", ",", "' Q1'", ",", "' Q0'", ",", "' Q9'", "]", ":", "index", "=", "txt", ".", "find", "(", "item", ")", "if", "len", "(", "txt", ")", "-", "6", ">", "index", ">", "-", "1", "and", "txt", "[", "index", "+", "2", ":", "index", "+", "6", "]", ".", "isdigit", "(", ")", ":", "alt_index", "=", "index", "# Then look for earliest remarks 'signifier'", "sig_index", "=", "find_first_in_list", "(", "txt", ",", "METAR_RMK", ")", "if", "sig_index", "==", "-", "1", ":", "sig_index", "=", "len", "(", "txt", ")", "+", "1", "if", "sig_index", ">", "alt_index", ">", "-", "1", ":", "return", "txt", "[", ":", "alt_index", "+", "6", "]", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", ",", "txt", "[", "alt_index", "+", "7", ":", "]", "if", "alt_index", ">", "sig_index", ">", "-", "1", ":", "return", "txt", "[", ":", "sig_index", "]", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", ",", "txt", "[", "sig_index", "+", "1", ":", "]", "return", "txt", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", ",", "''" ]
Returns the report split into components and the remarks string Remarks can include items like RMK and on, NOSIG and on, and BECMG and on
[ "Returns", "the", "report", "split", "into", "components", "and", "the", "remarks", "string" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L141-L162
244,877
etcher-be/emiz
emiz/avwx/core.py
get_taf_remarks
def get_taf_remarks(txt: str) -> (str, str): # type: ignore """ Returns report and remarks separated if found """ remarks_start = find_first_in_list(txt, TAF_RMK) if remarks_start == -1: return txt, '' remarks = txt[remarks_start:] txt = txt[:remarks_start].strip() return txt, remarks
python
def get_taf_remarks(txt: str) -> (str, str): # type: ignore """ Returns report and remarks separated if found """ remarks_start = find_first_in_list(txt, TAF_RMK) if remarks_start == -1: return txt, '' remarks = txt[remarks_start:] txt = txt[:remarks_start].strip() return txt, remarks
[ "def", "get_taf_remarks", "(", "txt", ":", "str", ")", "->", "(", "str", ",", "str", ")", ":", "# type: ignore", "remarks_start", "=", "find_first_in_list", "(", "txt", ",", "TAF_RMK", ")", "if", "remarks_start", "==", "-", "1", ":", "return", "txt", ",", "''", "remarks", "=", "txt", "[", "remarks_start", ":", "]", "txt", "=", "txt", "[", ":", "remarks_start", "]", ".", "strip", "(", ")", "return", "txt", ",", "remarks" ]
Returns report and remarks separated if found
[ "Returns", "report", "and", "remarks", "separated", "if", "found" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L165-L174
244,878
etcher-be/emiz
emiz/avwx/core.py
sanitize_report_string
def sanitize_report_string(txt: str) -> str: """ Provides sanitization for operations that work better when the report is a string Returns the first pass sanitized report string """ if len(txt) < 4: return txt # Standardize whitespace txt = ' '.join(txt.split()) # Prevent changes to station ID stid, txt = txt[:4], txt[4:] # Replace invalid key-value pairs for key, rep in STR_REPL.items(): txt = txt.replace(key, rep) # Check for missing spaces in front of cloud layers # Ex: TSFEW004SCT012FEW///CBBKN080 for cloud in CLOUD_LIST: if cloud in txt and ' ' + cloud not in txt: start, counter = 0, 0 while txt.count(cloud) != txt.count(' ' + cloud): cloud_index = start + txt[start:].find(cloud) if len(txt[cloud_index:]) >= 3: target = txt[cloud_index + len(cloud):cloud_index + len(cloud) + 3] if target.isdigit() or not target.strip('/'): txt = txt[:cloud_index] + ' ' + txt[cloud_index:] start = cloud_index + len(cloud) + 1 # Prevent infinite loops if counter > txt.count(cloud): break counter += 1 return stid + txt
python
def sanitize_report_string(txt: str) -> str: """ Provides sanitization for operations that work better when the report is a string Returns the first pass sanitized report string """ if len(txt) < 4: return txt # Standardize whitespace txt = ' '.join(txt.split()) # Prevent changes to station ID stid, txt = txt[:4], txt[4:] # Replace invalid key-value pairs for key, rep in STR_REPL.items(): txt = txt.replace(key, rep) # Check for missing spaces in front of cloud layers # Ex: TSFEW004SCT012FEW///CBBKN080 for cloud in CLOUD_LIST: if cloud in txt and ' ' + cloud not in txt: start, counter = 0, 0 while txt.count(cloud) != txt.count(' ' + cloud): cloud_index = start + txt[start:].find(cloud) if len(txt[cloud_index:]) >= 3: target = txt[cloud_index + len(cloud):cloud_index + len(cloud) + 3] if target.isdigit() or not target.strip('/'): txt = txt[:cloud_index] + ' ' + txt[cloud_index:] start = cloud_index + len(cloud) + 1 # Prevent infinite loops if counter > txt.count(cloud): break counter += 1 return stid + txt
[ "def", "sanitize_report_string", "(", "txt", ":", "str", ")", "->", "str", ":", "if", "len", "(", "txt", ")", "<", "4", ":", "return", "txt", "# Standardize whitespace", "txt", "=", "' '", ".", "join", "(", "txt", ".", "split", "(", ")", ")", "# Prevent changes to station ID", "stid", ",", "txt", "=", "txt", "[", ":", "4", "]", ",", "txt", "[", "4", ":", "]", "# Replace invalid key-value pairs", "for", "key", ",", "rep", "in", "STR_REPL", ".", "items", "(", ")", ":", "txt", "=", "txt", ".", "replace", "(", "key", ",", "rep", ")", "# Check for missing spaces in front of cloud layers", "# Ex: TSFEW004SCT012FEW///CBBKN080", "for", "cloud", "in", "CLOUD_LIST", ":", "if", "cloud", "in", "txt", "and", "' '", "+", "cloud", "not", "in", "txt", ":", "start", ",", "counter", "=", "0", ",", "0", "while", "txt", ".", "count", "(", "cloud", ")", "!=", "txt", ".", "count", "(", "' '", "+", "cloud", ")", ":", "cloud_index", "=", "start", "+", "txt", "[", "start", ":", "]", ".", "find", "(", "cloud", ")", "if", "len", "(", "txt", "[", "cloud_index", ":", "]", ")", ">=", "3", ":", "target", "=", "txt", "[", "cloud_index", "+", "len", "(", "cloud", ")", ":", "cloud_index", "+", "len", "(", "cloud", ")", "+", "3", "]", "if", "target", ".", "isdigit", "(", ")", "or", "not", "target", ".", "strip", "(", "'/'", ")", ":", "txt", "=", "txt", "[", ":", "cloud_index", "]", "+", "' '", "+", "txt", "[", "cloud_index", ":", "]", "start", "=", "cloud_index", "+", "len", "(", "cloud", ")", "+", "1", "# Prevent infinite loops", "if", "counter", ">", "txt", ".", "count", "(", "cloud", ")", ":", "break", "counter", "+=", "1", "return", "stid", "+", "txt" ]
Provides sanitization for operations that work better when the report is a string Returns the first pass sanitized report string
[ "Provides", "sanitization", "for", "operations", "that", "work", "better", "when", "the", "report", "is", "a", "string" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L180-L211
244,879
etcher-be/emiz
emiz/avwx/core.py
sanitize_line
def sanitize_line(txt: str) -> str: """ Fixes common mistakes with 'new line' signifiers so that they can be recognized """ for key in LINE_FIXES: index = txt.find(key) if index > -1: txt = txt[:index] + LINE_FIXES[key] + txt[index + len(key):] # Fix when space is missing following new line signifiers for item in ['BECMG', 'TEMPO']: if item in txt and item + ' ' not in txt: index = txt.find(item) + len(item) txt = txt[:index] + ' ' + txt[index:] return txt
python
def sanitize_line(txt: str) -> str: """ Fixes common mistakes with 'new line' signifiers so that they can be recognized """ for key in LINE_FIXES: index = txt.find(key) if index > -1: txt = txt[:index] + LINE_FIXES[key] + txt[index + len(key):] # Fix when space is missing following new line signifiers for item in ['BECMG', 'TEMPO']: if item in txt and item + ' ' not in txt: index = txt.find(item) + len(item) txt = txt[:index] + ' ' + txt[index:] return txt
[ "def", "sanitize_line", "(", "txt", ":", "str", ")", "->", "str", ":", "for", "key", "in", "LINE_FIXES", ":", "index", "=", "txt", ".", "find", "(", "key", ")", "if", "index", ">", "-", "1", ":", "txt", "=", "txt", "[", ":", "index", "]", "+", "LINE_FIXES", "[", "key", "]", "+", "txt", "[", "index", "+", "len", "(", "key", ")", ":", "]", "# Fix when space is missing following new line signifiers", "for", "item", "in", "[", "'BECMG'", ",", "'TEMPO'", "]", ":", "if", "item", "in", "txt", "and", "item", "+", "' '", "not", "in", "txt", ":", "index", "=", "txt", ".", "find", "(", "item", ")", "+", "len", "(", "item", ")", "txt", "=", "txt", "[", ":", "index", "]", "+", "' '", "+", "txt", "[", "index", ":", "]", "return", "txt" ]
Fixes common mistakes with 'new line' signifiers so that they can be recognized
[ "Fixes", "common", "mistakes", "with", "new", "line", "signifiers", "so", "that", "they", "can", "be", "recognized" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L222-L235
244,880
etcher-be/emiz
emiz/avwx/core.py
extra_space_exists
def extra_space_exists(str1: str, str2: str) -> bool: # noqa """ Return True if a space shouldn't exist between two items """ ls1, ls2 = len(str1), len(str2) if str1.isdigit(): # 10 SM if str2 in ['SM', '0SM']: return True # 12 /10 if ls2 > 2 and str2[0] == '/' and str2[1:].isdigit(): return True if str2.isdigit(): # OVC 040 if str1 in CLOUD_LIST: return True # 12/ 10 if ls1 > 2 and str1.endswith('/') and str1[:-1].isdigit(): return True # 12/1 0 if ls2 == 1 and ls1 > 3 and str1[:2].isdigit() and '/' in str1 and str1[3:].isdigit(): return True # Q 1001 if str1 in ['Q', 'A']: return True # 36010G20 KT if str2 == 'KT' and str1[-1].isdigit() \ and (str1[:5].isdigit() or (str1.startswith('VRB') and str1[3:5].isdigit())): return True # 36010K T if str2 == 'T' and ls1 >= 6 \ and (str1[:5].isdigit() or (str1.startswith('VRB') and str1[3:5].isdigit())) and str1[-1] == 'K': return True # OVC022 CB if str2 in CLOUD_TRANSLATIONS and str2 not in CLOUD_LIST and ls1 >= 3 and str1[:3] in CLOUD_LIST: return True # FM 122400 if str1 in ['FM', 'TL'] and (str2.isdigit() or (str2.endswith('Z') and str2[:-1].isdigit())): return True # TX 20/10 if str1 in ['TX', 'TN'] and str2.find('/') != -1: return True return False
python
def extra_space_exists(str1: str, str2: str) -> bool: # noqa """ Return True if a space shouldn't exist between two items """ ls1, ls2 = len(str1), len(str2) if str1.isdigit(): # 10 SM if str2 in ['SM', '0SM']: return True # 12 /10 if ls2 > 2 and str2[0] == '/' and str2[1:].isdigit(): return True if str2.isdigit(): # OVC 040 if str1 in CLOUD_LIST: return True # 12/ 10 if ls1 > 2 and str1.endswith('/') and str1[:-1].isdigit(): return True # 12/1 0 if ls2 == 1 and ls1 > 3 and str1[:2].isdigit() and '/' in str1 and str1[3:].isdigit(): return True # Q 1001 if str1 in ['Q', 'A']: return True # 36010G20 KT if str2 == 'KT' and str1[-1].isdigit() \ and (str1[:5].isdigit() or (str1.startswith('VRB') and str1[3:5].isdigit())): return True # 36010K T if str2 == 'T' and ls1 >= 6 \ and (str1[:5].isdigit() or (str1.startswith('VRB') and str1[3:5].isdigit())) and str1[-1] == 'K': return True # OVC022 CB if str2 in CLOUD_TRANSLATIONS and str2 not in CLOUD_LIST and ls1 >= 3 and str1[:3] in CLOUD_LIST: return True # FM 122400 if str1 in ['FM', 'TL'] and (str2.isdigit() or (str2.endswith('Z') and str2[:-1].isdigit())): return True # TX 20/10 if str1 in ['TX', 'TN'] and str2.find('/') != -1: return True return False
[ "def", "extra_space_exists", "(", "str1", ":", "str", ",", "str2", ":", "str", ")", "->", "bool", ":", "# noqa", "ls1", ",", "ls2", "=", "len", "(", "str1", ")", ",", "len", "(", "str2", ")", "if", "str1", ".", "isdigit", "(", ")", ":", "# 10 SM", "if", "str2", "in", "[", "'SM'", ",", "'0SM'", "]", ":", "return", "True", "# 12 /10", "if", "ls2", ">", "2", "and", "str2", "[", "0", "]", "==", "'/'", "and", "str2", "[", "1", ":", "]", ".", "isdigit", "(", ")", ":", "return", "True", "if", "str2", ".", "isdigit", "(", ")", ":", "# OVC 040", "if", "str1", "in", "CLOUD_LIST", ":", "return", "True", "# 12/ 10", "if", "ls1", ">", "2", "and", "str1", ".", "endswith", "(", "'/'", ")", "and", "str1", "[", ":", "-", "1", "]", ".", "isdigit", "(", ")", ":", "return", "True", "# 12/1 0", "if", "ls2", "==", "1", "and", "ls1", ">", "3", "and", "str1", "[", ":", "2", "]", ".", "isdigit", "(", ")", "and", "'/'", "in", "str1", "and", "str1", "[", "3", ":", "]", ".", "isdigit", "(", ")", ":", "return", "True", "# Q 1001", "if", "str1", "in", "[", "'Q'", ",", "'A'", "]", ":", "return", "True", "# 36010G20 KT", "if", "str2", "==", "'KT'", "and", "str1", "[", "-", "1", "]", ".", "isdigit", "(", ")", "and", "(", "str1", "[", ":", "5", "]", ".", "isdigit", "(", ")", "or", "(", "str1", ".", "startswith", "(", "'VRB'", ")", "and", "str1", "[", "3", ":", "5", "]", ".", "isdigit", "(", ")", ")", ")", ":", "return", "True", "# 36010K T", "if", "str2", "==", "'T'", "and", "ls1", ">=", "6", "and", "(", "str1", "[", ":", "5", "]", ".", "isdigit", "(", ")", "or", "(", "str1", ".", "startswith", "(", "'VRB'", ")", "and", "str1", "[", "3", ":", "5", "]", ".", "isdigit", "(", ")", ")", ")", "and", "str1", "[", "-", "1", "]", "==", "'K'", ":", "return", "True", "# OVC022 CB", "if", "str2", "in", "CLOUD_TRANSLATIONS", "and", "str2", "not", "in", "CLOUD_LIST", "and", "ls1", ">=", "3", "and", "str1", "[", ":", "3", "]", "in", "CLOUD_LIST", ":", "return", "True", "# FM 122400", "if", "str1", "in", "[", "'FM'", ",", "'TL'", "]", "and", "(", "str2", ".", "isdigit", "(", ")", "or", "(", "str2", ".", "endswith", "(", "'Z'", ")", "and", "str2", "[", ":", "-", "1", "]", ".", "isdigit", "(", ")", ")", ")", ":", "return", "True", "# TX 20/10", "if", "str1", "in", "[", "'TX'", ",", "'TN'", "]", "and", "str2", ".", "find", "(", "'/'", ")", "!=", "-", "1", ":", "return", "True", "return", "False" ]
Return True if a space shouldn't exist between two items
[ "Return", "True", "if", "a", "space", "shouldn", "t", "exist", "between", "two", "items" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L238-L280
244,881
etcher-be/emiz
emiz/avwx/core.py
get_altimeter
def get_altimeter(wxdata: [str], units: Units, version: str = 'NA') -> ([str], Number): # type: ignore # noqa """ Returns the report list and the removed altimeter item Version is 'NA' (North American / default) or 'IN' (International) """ if not wxdata: return wxdata, None altimeter = '' target = wxdata[-1] if version == 'NA': # Version target if target[0] == 'A': altimeter = wxdata.pop()[1:] # Other version but prefer normal if available elif target[0] == 'Q': if wxdata[-2][0] == 'A': wxdata.pop() altimeter = wxdata.pop()[1:] else: units.altimeter = 'hPa' altimeter = wxdata.pop()[1:].lstrip('.') # Else grab the digits elif len(target) == 4 and target.isdigit(): altimeter = wxdata.pop() elif version == 'IN': # Version target if target[0] == 'Q': altimeter = wxdata.pop()[1:].lstrip('.') if '/' in altimeter: altimeter = altimeter[:altimeter.find('/')] # Other version but prefer normal if available elif target[0] == 'A': if wxdata[-2][0] == 'Q': wxdata.pop() altimeter = wxdata.pop()[1:] else: units.altimeter = 'inHg' altimeter = wxdata.pop()[1:] # Some stations report both, but we only need one if wxdata and (wxdata[-1][0] == 'A' or wxdata[-1][0] == 'Q'): wxdata.pop() # convert to Number if not altimeter: return wxdata, None if units.altimeter == 'inHg': value = altimeter[:2] + '.' + altimeter[2:] else: value = altimeter return wxdata, make_number(value, altimeter)
python
def get_altimeter(wxdata: [str], units: Units, version: str = 'NA') -> ([str], Number): # type: ignore # noqa """ Returns the report list and the removed altimeter item Version is 'NA' (North American / default) or 'IN' (International) """ if not wxdata: return wxdata, None altimeter = '' target = wxdata[-1] if version == 'NA': # Version target if target[0] == 'A': altimeter = wxdata.pop()[1:] # Other version but prefer normal if available elif target[0] == 'Q': if wxdata[-2][0] == 'A': wxdata.pop() altimeter = wxdata.pop()[1:] else: units.altimeter = 'hPa' altimeter = wxdata.pop()[1:].lstrip('.') # Else grab the digits elif len(target) == 4 and target.isdigit(): altimeter = wxdata.pop() elif version == 'IN': # Version target if target[0] == 'Q': altimeter = wxdata.pop()[1:].lstrip('.') if '/' in altimeter: altimeter = altimeter[:altimeter.find('/')] # Other version but prefer normal if available elif target[0] == 'A': if wxdata[-2][0] == 'Q': wxdata.pop() altimeter = wxdata.pop()[1:] else: units.altimeter = 'inHg' altimeter = wxdata.pop()[1:] # Some stations report both, but we only need one if wxdata and (wxdata[-1][0] == 'A' or wxdata[-1][0] == 'Q'): wxdata.pop() # convert to Number if not altimeter: return wxdata, None if units.altimeter == 'inHg': value = altimeter[:2] + '.' + altimeter[2:] else: value = altimeter return wxdata, make_number(value, altimeter)
[ "def", "get_altimeter", "(", "wxdata", ":", "[", "str", "]", ",", "units", ":", "Units", ",", "version", ":", "str", "=", "'NA'", ")", "->", "(", "[", "str", "]", ",", "Number", ")", ":", "# type: ignore # noqa", "if", "not", "wxdata", ":", "return", "wxdata", ",", "None", "altimeter", "=", "''", "target", "=", "wxdata", "[", "-", "1", "]", "if", "version", "==", "'NA'", ":", "# Version target", "if", "target", "[", "0", "]", "==", "'A'", ":", "altimeter", "=", "wxdata", ".", "pop", "(", ")", "[", "1", ":", "]", "# Other version but prefer normal if available", "elif", "target", "[", "0", "]", "==", "'Q'", ":", "if", "wxdata", "[", "-", "2", "]", "[", "0", "]", "==", "'A'", ":", "wxdata", ".", "pop", "(", ")", "altimeter", "=", "wxdata", ".", "pop", "(", ")", "[", "1", ":", "]", "else", ":", "units", ".", "altimeter", "=", "'hPa'", "altimeter", "=", "wxdata", ".", "pop", "(", ")", "[", "1", ":", "]", ".", "lstrip", "(", "'.'", ")", "# Else grab the digits", "elif", "len", "(", "target", ")", "==", "4", "and", "target", ".", "isdigit", "(", ")", ":", "altimeter", "=", "wxdata", ".", "pop", "(", ")", "elif", "version", "==", "'IN'", ":", "# Version target", "if", "target", "[", "0", "]", "==", "'Q'", ":", "altimeter", "=", "wxdata", ".", "pop", "(", ")", "[", "1", ":", "]", ".", "lstrip", "(", "'.'", ")", "if", "'/'", "in", "altimeter", ":", "altimeter", "=", "altimeter", "[", ":", "altimeter", ".", "find", "(", "'/'", ")", "]", "# Other version but prefer normal if available", "elif", "target", "[", "0", "]", "==", "'A'", ":", "if", "wxdata", "[", "-", "2", "]", "[", "0", "]", "==", "'Q'", ":", "wxdata", ".", "pop", "(", ")", "altimeter", "=", "wxdata", ".", "pop", "(", ")", "[", "1", ":", "]", "else", ":", "units", ".", "altimeter", "=", "'inHg'", "altimeter", "=", "wxdata", ".", "pop", "(", ")", "[", "1", ":", "]", "# Some stations report both, but we only need one", "if", "wxdata", "and", "(", "wxdata", "[", "-", "1", "]", "[", "0", "]", "==", "'A'", "or", "wxdata", "[", "-", "1", "]", "[", "0", "]", "==", "'Q'", ")", ":", "wxdata", ".", "pop", "(", ")", "# convert to Number", "if", "not", "altimeter", ":", "return", "wxdata", ",", "None", "if", "units", ".", "altimeter", "==", "'inHg'", ":", "value", "=", "altimeter", "[", ":", "2", "]", "+", "'.'", "+", "altimeter", "[", "2", ":", "]", "else", ":", "value", "=", "altimeter", "return", "wxdata", ",", "make_number", "(", "value", ",", "altimeter", ")" ]
Returns the report list and the removed altimeter item Version is 'NA' (North American / default) or 'IN' (International)
[ "Returns", "the", "report", "list", "and", "the", "removed", "altimeter", "item" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L354-L403
244,882
etcher-be/emiz
emiz/avwx/core.py
get_station_and_time
def get_station_and_time(wxdata: [str]) -> ([str], str, str): # type: ignore """ Returns the report list and removed station ident and time strings """ station = wxdata.pop(0) qtime = wxdata[0] if wxdata and qtime.endswith('Z') and qtime[:-1].isdigit(): rtime = wxdata.pop(0) elif wxdata and len(qtime) == 6 and qtime.isdigit(): rtime = wxdata.pop(0) + 'Z' else: rtime = '' return wxdata, station, rtime
python
def get_station_and_time(wxdata: [str]) -> ([str], str, str): # type: ignore """ Returns the report list and removed station ident and time strings """ station = wxdata.pop(0) qtime = wxdata[0] if wxdata and qtime.endswith('Z') and qtime[:-1].isdigit(): rtime = wxdata.pop(0) elif wxdata and len(qtime) == 6 and qtime.isdigit(): rtime = wxdata.pop(0) + 'Z' else: rtime = '' return wxdata, station, rtime
[ "def", "get_station_and_time", "(", "wxdata", ":", "[", "str", "]", ")", "->", "(", "[", "str", "]", ",", "str", ",", "str", ")", ":", "# type: ignore", "station", "=", "wxdata", ".", "pop", "(", "0", ")", "qtime", "=", "wxdata", "[", "0", "]", "if", "wxdata", "and", "qtime", ".", "endswith", "(", "'Z'", ")", "and", "qtime", "[", ":", "-", "1", "]", ".", "isdigit", "(", ")", ":", "rtime", "=", "wxdata", ".", "pop", "(", "0", ")", "elif", "wxdata", "and", "len", "(", "qtime", ")", "==", "6", "and", "qtime", ".", "isdigit", "(", ")", ":", "rtime", "=", "wxdata", ".", "pop", "(", "0", ")", "+", "'Z'", "else", ":", "rtime", "=", "''", "return", "wxdata", ",", "station", ",", "rtime" ]
Returns the report list and removed station ident and time strings
[ "Returns", "the", "report", "list", "and", "removed", "station", "ident", "and", "time", "strings" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L461-L473
244,883
etcher-be/emiz
emiz/avwx/core.py
get_visibility
def get_visibility(wxdata: [str], units: Units) -> ([str], Number): # type: ignore """ Returns the report list and removed visibility string """ visibility = '' # type: ignore if wxdata: item = copy(wxdata[0]) # Vis reported in statue miles if item.endswith('SM'): # 10SM if item in ('P6SM', 'M1/4SM'): visibility = item[:-2] elif '/' not in item: visibility = str(int(item[:item.find('SM')])) else: visibility = item[:item.find('SM')] # 1/2SM wxdata.pop(0) units.visibility = 'sm' # Vis reported in meters elif len(item) == 4 and item.isdigit(): visibility = wxdata.pop(0) units.visibility = 'm' elif 7 >= len(item) >= 5 and item[:4].isdigit() \ and (item[4] in ['M', 'N', 'S', 'E', 'W'] or item[4:] == 'NDV'): visibility = wxdata.pop(0)[:4] units.visibility = 'm' elif len(item) == 5 and item[1:].isdigit() and item[0] in ['M', 'P', 'B']: visibility = wxdata.pop(0)[1:] units.visibility = 'm' elif item.endswith('KM') and item[:item.find('KM')].isdigit(): visibility = item[:item.find('KM')] + '000' wxdata.pop(0) units.visibility = 'm' # Vis statute miles but split Ex: 2 1/2SM elif len(wxdata) > 1 and wxdata[1].endswith('SM') and '/' in wxdata[1] and item.isdigit(): vis1 = wxdata.pop(0) # 2 vis2 = wxdata.pop(0).replace('SM', '') # 1/2 visibility = str(int(vis1) * int(vis2[2]) + int(vis2[0])) + vis2[1:] # 5/2 units.visibility = 'sm' return wxdata, make_number(visibility)
python
def get_visibility(wxdata: [str], units: Units) -> ([str], Number): # type: ignore """ Returns the report list and removed visibility string """ visibility = '' # type: ignore if wxdata: item = copy(wxdata[0]) # Vis reported in statue miles if item.endswith('SM'): # 10SM if item in ('P6SM', 'M1/4SM'): visibility = item[:-2] elif '/' not in item: visibility = str(int(item[:item.find('SM')])) else: visibility = item[:item.find('SM')] # 1/2SM wxdata.pop(0) units.visibility = 'sm' # Vis reported in meters elif len(item) == 4 and item.isdigit(): visibility = wxdata.pop(0) units.visibility = 'm' elif 7 >= len(item) >= 5 and item[:4].isdigit() \ and (item[4] in ['M', 'N', 'S', 'E', 'W'] or item[4:] == 'NDV'): visibility = wxdata.pop(0)[:4] units.visibility = 'm' elif len(item) == 5 and item[1:].isdigit() and item[0] in ['M', 'P', 'B']: visibility = wxdata.pop(0)[1:] units.visibility = 'm' elif item.endswith('KM') and item[:item.find('KM')].isdigit(): visibility = item[:item.find('KM')] + '000' wxdata.pop(0) units.visibility = 'm' # Vis statute miles but split Ex: 2 1/2SM elif len(wxdata) > 1 and wxdata[1].endswith('SM') and '/' in wxdata[1] and item.isdigit(): vis1 = wxdata.pop(0) # 2 vis2 = wxdata.pop(0).replace('SM', '') # 1/2 visibility = str(int(vis1) * int(vis2[2]) + int(vis2[0])) + vis2[1:] # 5/2 units.visibility = 'sm' return wxdata, make_number(visibility)
[ "def", "get_visibility", "(", "wxdata", ":", "[", "str", "]", ",", "units", ":", "Units", ")", "->", "(", "[", "str", "]", ",", "Number", ")", ":", "# type: ignore", "visibility", "=", "''", "# type: ignore", "if", "wxdata", ":", "item", "=", "copy", "(", "wxdata", "[", "0", "]", ")", "# Vis reported in statue miles", "if", "item", ".", "endswith", "(", "'SM'", ")", ":", "# 10SM", "if", "item", "in", "(", "'P6SM'", ",", "'M1/4SM'", ")", ":", "visibility", "=", "item", "[", ":", "-", "2", "]", "elif", "'/'", "not", "in", "item", ":", "visibility", "=", "str", "(", "int", "(", "item", "[", ":", "item", ".", "find", "(", "'SM'", ")", "]", ")", ")", "else", ":", "visibility", "=", "item", "[", ":", "item", ".", "find", "(", "'SM'", ")", "]", "# 1/2SM", "wxdata", ".", "pop", "(", "0", ")", "units", ".", "visibility", "=", "'sm'", "# Vis reported in meters", "elif", "len", "(", "item", ")", "==", "4", "and", "item", ".", "isdigit", "(", ")", ":", "visibility", "=", "wxdata", ".", "pop", "(", "0", ")", "units", ".", "visibility", "=", "'m'", "elif", "7", ">=", "len", "(", "item", ")", ">=", "5", "and", "item", "[", ":", "4", "]", ".", "isdigit", "(", ")", "and", "(", "item", "[", "4", "]", "in", "[", "'M'", ",", "'N'", ",", "'S'", ",", "'E'", ",", "'W'", "]", "or", "item", "[", "4", ":", "]", "==", "'NDV'", ")", ":", "visibility", "=", "wxdata", ".", "pop", "(", "0", ")", "[", ":", "4", "]", "units", ".", "visibility", "=", "'m'", "elif", "len", "(", "item", ")", "==", "5", "and", "item", "[", "1", ":", "]", ".", "isdigit", "(", ")", "and", "item", "[", "0", "]", "in", "[", "'M'", ",", "'P'", ",", "'B'", "]", ":", "visibility", "=", "wxdata", ".", "pop", "(", "0", ")", "[", "1", ":", "]", "units", ".", "visibility", "=", "'m'", "elif", "item", ".", "endswith", "(", "'KM'", ")", "and", "item", "[", ":", "item", ".", "find", "(", "'KM'", ")", "]", ".", "isdigit", "(", ")", ":", "visibility", "=", "item", "[", ":", "item", ".", "find", "(", "'KM'", ")", "]", "+", "'000'", "wxdata", ".", "pop", "(", "0", ")", "units", ".", "visibility", "=", "'m'", "# Vis statute miles but split Ex: 2 1/2SM", "elif", "len", "(", "wxdata", ")", ">", "1", "and", "wxdata", "[", "1", "]", ".", "endswith", "(", "'SM'", ")", "and", "'/'", "in", "wxdata", "[", "1", "]", "and", "item", ".", "isdigit", "(", ")", ":", "vis1", "=", "wxdata", ".", "pop", "(", "0", ")", "# 2", "vis2", "=", "wxdata", ".", "pop", "(", "0", ")", ".", "replace", "(", "'SM'", ",", "''", ")", "# 1/2", "visibility", "=", "str", "(", "int", "(", "vis1", ")", "*", "int", "(", "vis2", "[", "2", "]", ")", "+", "int", "(", "vis2", "[", "0", "]", ")", ")", "+", "vis2", "[", "1", ":", "]", "# 5/2", "units", ".", "visibility", "=", "'sm'", "return", "wxdata", ",", "make_number", "(", "visibility", ")" ]
Returns the report list and removed visibility string
[ "Returns", "the", "report", "list", "and", "removed", "visibility", "string" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L529-L567
244,884
etcher-be/emiz
emiz/avwx/core.py
starts_new_line
def starts_new_line(item: str) -> bool: """ Returns True if the given element should start a new report line """ if item in TAF_NEWLINE: return True for start in TAF_NEWLINE_STARTSWITH: if item.startswith(start): return True return False
python
def starts_new_line(item: str) -> bool: """ Returns True if the given element should start a new report line """ if item in TAF_NEWLINE: return True for start in TAF_NEWLINE_STARTSWITH: if item.startswith(start): return True return False
[ "def", "starts_new_line", "(", "item", ":", "str", ")", "->", "bool", ":", "if", "item", "in", "TAF_NEWLINE", ":", "return", "True", "for", "start", "in", "TAF_NEWLINE_STARTSWITH", ":", "if", "item", ".", "startswith", "(", "start", ")", ":", "return", "True", "return", "False" ]
Returns True if the given element should start a new report line
[ "Returns", "True", "if", "the", "given", "element", "should", "start", "a", "new", "report", "line" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L570-L581
244,885
etcher-be/emiz
emiz/avwx/core.py
split_taf
def split_taf(txt: str) -> [str]: # type: ignore """ Splits a TAF report into each distinct time period """ lines = [] split = txt.split() last_index = 0 for i, item in enumerate(split): if starts_new_line(item) and i != 0 and not split[i - 1].startswith('PROB'): lines.append(' '.join(split[last_index:i])) last_index = i lines.append(' '.join(split[last_index:])) return lines
python
def split_taf(txt: str) -> [str]: # type: ignore """ Splits a TAF report into each distinct time period """ lines = [] split = txt.split() last_index = 0 for i, item in enumerate(split): if starts_new_line(item) and i != 0 and not split[i - 1].startswith('PROB'): lines.append(' '.join(split[last_index:i])) last_index = i lines.append(' '.join(split[last_index:])) return lines
[ "def", "split_taf", "(", "txt", ":", "str", ")", "->", "[", "str", "]", ":", "# type: ignore", "lines", "=", "[", "]", "split", "=", "txt", ".", "split", "(", ")", "last_index", "=", "0", "for", "i", ",", "item", "in", "enumerate", "(", "split", ")", ":", "if", "starts_new_line", "(", "item", ")", "and", "i", "!=", "0", "and", "not", "split", "[", "i", "-", "1", "]", ".", "startswith", "(", "'PROB'", ")", ":", "lines", ".", "append", "(", "' '", ".", "join", "(", "split", "[", "last_index", ":", "i", "]", ")", ")", "last_index", "=", "i", "lines", ".", "append", "(", "' '", ".", "join", "(", "split", "[", "last_index", ":", "]", ")", ")", "return", "lines" ]
Splits a TAF report into each distinct time period
[ "Splits", "a", "TAF", "report", "into", "each", "distinct", "time", "period" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L584-L596
244,886
etcher-be/emiz
emiz/avwx/core.py
_get_next_time
def _get_next_time(lines: [dict], target: str) -> str: # type: ignore """ Returns the next FROM target value or empty """ for line in lines: if line[target] and not _is_tempo_or_prob(line['type']): return line[target] return ''
python
def _get_next_time(lines: [dict], target: str) -> str: # type: ignore """ Returns the next FROM target value or empty """ for line in lines: if line[target] and not _is_tempo_or_prob(line['type']): return line[target] return ''
[ "def", "_get_next_time", "(", "lines", ":", "[", "dict", "]", ",", "target", ":", "str", ")", "->", "str", ":", "# type: ignore", "for", "line", "in", "lines", ":", "if", "line", "[", "target", "]", "and", "not", "_is_tempo_or_prob", "(", "line", "[", "'type'", "]", ")", ":", "return", "line", "[", "target", "]", "return", "''" ]
Returns the next FROM target value or empty
[ "Returns", "the", "next", "FROM", "target", "value", "or", "empty" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L644-L651
244,887
etcher-be/emiz
emiz/avwx/core.py
get_temp_min_and_max
def get_temp_min_and_max(wxlist: [str]) -> ([str], str, str): # type: ignore """ Pull out Max temp at time and Min temp at time items from wx list """ temp_max, temp_min = '', '' for i, item in reversed(list(enumerate(wxlist))): if len(item) > 6 and item[0] == 'T' and '/' in item: # TX12/1316Z if item[1] == 'X': temp_max = wxlist.pop(i) # TNM03/1404Z elif item[1] == 'N': temp_min = wxlist.pop(i) # TM03/1404Z T12/1316Z -> Will fix TN/TX elif item[1] == 'M' or item[1].isdigit(): if temp_min: if int(temp_min[2:temp_min.find('/')].replace('M', '-')) \ > int(item[1:item.find('/')].replace('M', '-')): temp_max = 'TX' + temp_min[2:] temp_min = 'TN' + item[1:] else: temp_max = 'TX' + item[1:] else: temp_min = 'TN' + item[1:] wxlist.pop(i) return wxlist, temp_max, temp_min
python
def get_temp_min_and_max(wxlist: [str]) -> ([str], str, str): # type: ignore """ Pull out Max temp at time and Min temp at time items from wx list """ temp_max, temp_min = '', '' for i, item in reversed(list(enumerate(wxlist))): if len(item) > 6 and item[0] == 'T' and '/' in item: # TX12/1316Z if item[1] == 'X': temp_max = wxlist.pop(i) # TNM03/1404Z elif item[1] == 'N': temp_min = wxlist.pop(i) # TM03/1404Z T12/1316Z -> Will fix TN/TX elif item[1] == 'M' or item[1].isdigit(): if temp_min: if int(temp_min[2:temp_min.find('/')].replace('M', '-')) \ > int(item[1:item.find('/')].replace('M', '-')): temp_max = 'TX' + temp_min[2:] temp_min = 'TN' + item[1:] else: temp_max = 'TX' + item[1:] else: temp_min = 'TN' + item[1:] wxlist.pop(i) return wxlist, temp_max, temp_min
[ "def", "get_temp_min_and_max", "(", "wxlist", ":", "[", "str", "]", ")", "->", "(", "[", "str", "]", ",", "str", ",", "str", ")", ":", "# type: ignore", "temp_max", ",", "temp_min", "=", "''", ",", "''", "for", "i", ",", "item", "in", "reversed", "(", "list", "(", "enumerate", "(", "wxlist", ")", ")", ")", ":", "if", "len", "(", "item", ")", ">", "6", "and", "item", "[", "0", "]", "==", "'T'", "and", "'/'", "in", "item", ":", "# TX12/1316Z", "if", "item", "[", "1", "]", "==", "'X'", ":", "temp_max", "=", "wxlist", ".", "pop", "(", "i", ")", "# TNM03/1404Z", "elif", "item", "[", "1", "]", "==", "'N'", ":", "temp_min", "=", "wxlist", ".", "pop", "(", "i", ")", "# TM03/1404Z T12/1316Z -> Will fix TN/TX", "elif", "item", "[", "1", "]", "==", "'M'", "or", "item", "[", "1", "]", ".", "isdigit", "(", ")", ":", "if", "temp_min", ":", "if", "int", "(", "temp_min", "[", "2", ":", "temp_min", ".", "find", "(", "'/'", ")", "]", ".", "replace", "(", "'M'", ",", "'-'", ")", ")", ">", "int", "(", "item", "[", "1", ":", "item", ".", "find", "(", "'/'", ")", "]", ".", "replace", "(", "'M'", ",", "'-'", ")", ")", ":", "temp_max", "=", "'TX'", "+", "temp_min", "[", "2", ":", "]", "temp_min", "=", "'TN'", "+", "item", "[", "1", ":", "]", "else", ":", "temp_max", "=", "'TX'", "+", "item", "[", "1", ":", "]", "else", ":", "temp_min", "=", "'TN'", "+", "item", "[", "1", ":", "]", "wxlist", ".", "pop", "(", "i", ")", "return", "wxlist", ",", "temp_max", ",", "temp_min" ]
Pull out Max temp at time and Min temp at time items from wx list
[ "Pull", "out", "Max", "temp", "at", "time", "and", "Min", "temp", "at", "time", "items", "from", "wx", "list" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L682-L707
244,888
etcher-be/emiz
emiz/avwx/core.py
_get_digit_list
def _get_digit_list(alist: [str], from_index: int) -> ([str], [str]): # type: ignore """ Returns a list of items removed from a given list of strings that are all digits from 'from_index' until hitting a non-digit item """ ret = [] alist.pop(from_index) while len(alist) > from_index and alist[from_index].isdigit(): ret.append(alist.pop(from_index)) return alist, ret
python
def _get_digit_list(alist: [str], from_index: int) -> ([str], [str]): # type: ignore """ Returns a list of items removed from a given list of strings that are all digits from 'from_index' until hitting a non-digit item """ ret = [] alist.pop(from_index) while len(alist) > from_index and alist[from_index].isdigit(): ret.append(alist.pop(from_index)) return alist, ret
[ "def", "_get_digit_list", "(", "alist", ":", "[", "str", "]", ",", "from_index", ":", "int", ")", "->", "(", "[", "str", "]", ",", "[", "str", "]", ")", ":", "# type: ignore", "ret", "=", "[", "]", "alist", ".", "pop", "(", "from_index", ")", "while", "len", "(", "alist", ")", ">", "from_index", "and", "alist", "[", "from_index", "]", ".", "isdigit", "(", ")", ":", "ret", ".", "append", "(", "alist", ".", "pop", "(", "from_index", ")", ")", "return", "alist", ",", "ret" ]
Returns a list of items removed from a given list of strings that are all digits from 'from_index' until hitting a non-digit item
[ "Returns", "a", "list", "of", "items", "removed", "from", "a", "given", "list", "of", "strings", "that", "are", "all", "digits", "from", "from_index", "until", "hitting", "a", "non", "-", "digit", "item" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L710-L719
244,889
etcher-be/emiz
emiz/avwx/core.py
get_oceania_temp_and_alt
def get_oceania_temp_and_alt(wxlist: [str]) -> ([str], [str], [str]): # type: ignore """ Get Temperature and Altimeter lists for Oceania TAFs """ tlist, qlist = [], [] # type: ignore if 'T' in wxlist: wxlist, tlist = _get_digit_list(wxlist, wxlist.index('T')) if 'Q' in wxlist: wxlist, qlist = _get_digit_list(wxlist, wxlist.index('Q')) return wxlist, tlist, qlist
python
def get_oceania_temp_and_alt(wxlist: [str]) -> ([str], [str], [str]): # type: ignore """ Get Temperature and Altimeter lists for Oceania TAFs """ tlist, qlist = [], [] # type: ignore if 'T' in wxlist: wxlist, tlist = _get_digit_list(wxlist, wxlist.index('T')) if 'Q' in wxlist: wxlist, qlist = _get_digit_list(wxlist, wxlist.index('Q')) return wxlist, tlist, qlist
[ "def", "get_oceania_temp_and_alt", "(", "wxlist", ":", "[", "str", "]", ")", "->", "(", "[", "str", "]", ",", "[", "str", "]", ",", "[", "str", "]", ")", ":", "# type: ignore", "tlist", ",", "qlist", "=", "[", "]", ",", "[", "]", "# type: ignore", "if", "'T'", "in", "wxlist", ":", "wxlist", ",", "tlist", "=", "_get_digit_list", "(", "wxlist", ",", "wxlist", ".", "index", "(", "'T'", ")", ")", "if", "'Q'", "in", "wxlist", ":", "wxlist", ",", "qlist", "=", "_get_digit_list", "(", "wxlist", ",", "wxlist", ".", "index", "(", "'Q'", ")", ")", "return", "wxlist", ",", "tlist", ",", "qlist" ]
Get Temperature and Altimeter lists for Oceania TAFs
[ "Get", "Temperature", "and", "Altimeter", "lists", "for", "Oceania", "TAFs" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L722-L731
244,890
etcher-be/emiz
emiz/avwx/core.py
sanitize_cloud
def sanitize_cloud(cloud: str) -> str: """ Fix rare cloud layer issues """ if len(cloud) < 4: return cloud if not cloud[3].isdigit() and cloud[3] != '/': if cloud[3] == 'O': cloud = cloud[:3] + '0' + cloud[4:] # Bad "O": FEWO03 -> FEW003 else: # Move modifiers to end: BKNC015 -> BKN015C cloud = cloud[:3] + cloud[4:] + cloud[3] return cloud
python
def sanitize_cloud(cloud: str) -> str: """ Fix rare cloud layer issues """ if len(cloud) < 4: return cloud if not cloud[3].isdigit() and cloud[3] != '/': if cloud[3] == 'O': cloud = cloud[:3] + '0' + cloud[4:] # Bad "O": FEWO03 -> FEW003 else: # Move modifiers to end: BKNC015 -> BKN015C cloud = cloud[:3] + cloud[4:] + cloud[3] return cloud
[ "def", "sanitize_cloud", "(", "cloud", ":", "str", ")", "->", "str", ":", "if", "len", "(", "cloud", ")", "<", "4", ":", "return", "cloud", "if", "not", "cloud", "[", "3", "]", ".", "isdigit", "(", ")", "and", "cloud", "[", "3", "]", "!=", "'/'", ":", "if", "cloud", "[", "3", "]", "==", "'O'", ":", "cloud", "=", "cloud", "[", ":", "3", "]", "+", "'0'", "+", "cloud", "[", "4", ":", "]", "# Bad \"O\": FEWO03 -> FEW003", "else", ":", "# Move modifiers to end: BKNC015 -> BKN015C", "cloud", "=", "cloud", "[", ":", "3", "]", "+", "cloud", "[", "4", ":", "]", "+", "cloud", "[", "3", "]", "return", "cloud" ]
Fix rare cloud layer issues
[ "Fix", "rare", "cloud", "layer", "issues" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L734-L745
244,891
etcher-be/emiz
emiz/avwx/core.py
get_clouds
def get_clouds(wxdata: [str]) -> ([str], list): # type: ignore """ Returns the report list and removed list of split cloud layers """ clouds = [] for i, item in reversed(list(enumerate(wxdata))): if item[:3] in CLOUD_LIST or item[:2] == 'VV': cloud = wxdata.pop(i) clouds.append(make_cloud(cloud)) return wxdata, sorted(clouds, key=lambda cloud: (cloud.altitude, cloud.type))
python
def get_clouds(wxdata: [str]) -> ([str], list): # type: ignore """ Returns the report list and removed list of split cloud layers """ clouds = [] for i, item in reversed(list(enumerate(wxdata))): if item[:3] in CLOUD_LIST or item[:2] == 'VV': cloud = wxdata.pop(i) clouds.append(make_cloud(cloud)) return wxdata, sorted(clouds, key=lambda cloud: (cloud.altitude, cloud.type))
[ "def", "get_clouds", "(", "wxdata", ":", "[", "str", "]", ")", "->", "(", "[", "str", "]", ",", "list", ")", ":", "# type: ignore", "clouds", "=", "[", "]", "for", "i", ",", "item", "in", "reversed", "(", "list", "(", "enumerate", "(", "wxdata", ")", ")", ")", ":", "if", "item", "[", ":", "3", "]", "in", "CLOUD_LIST", "or", "item", "[", ":", "2", "]", "==", "'VV'", ":", "cloud", "=", "wxdata", ".", "pop", "(", "i", ")", "clouds", ".", "append", "(", "make_cloud", "(", "cloud", ")", ")", "return", "wxdata", ",", "sorted", "(", "clouds", ",", "key", "=", "lambda", "cloud", ":", "(", "cloud", ".", "altitude", ",", "cloud", ".", "type", ")", ")" ]
Returns the report list and removed list of split cloud layers
[ "Returns", "the", "report", "list", "and", "removed", "list", "of", "split", "cloud", "layers" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L783-L792
244,892
etcher-be/emiz
emiz/avwx/core.py
get_flight_rules
def get_flight_rules(vis: Number, ceiling: Cloud) -> int: """ Returns int based on current flight rules from parsed METAR data 0=VFR, 1=MVFR, 2=IFR, 3=LIFR Note: Common practice is to report IFR if visibility unavailable """ # Parse visibility if not vis: return 2 if vis.repr == 'CAVOK' or vis.repr.startswith('P6'): vis = 10 # type: ignore elif vis.repr.startswith('M'): vis = 0 # type: ignore # Convert meters to miles elif len(vis.repr) == 4: vis = vis.value * 0.000621371 # type: ignore else: vis = vis.value # type: ignore # Parse ceiling cld = ceiling.altitude if ceiling else 99 # Determine flight rules if (vis <= 5) or (cld <= 30): # type: ignore if (vis < 3) or (cld < 10): # type: ignore if (vis < 1) or (cld < 5): # type: ignore return 3 # LIFR return 2 # IFR return 1 # MVFR return 0
python
def get_flight_rules(vis: Number, ceiling: Cloud) -> int: """ Returns int based on current flight rules from parsed METAR data 0=VFR, 1=MVFR, 2=IFR, 3=LIFR Note: Common practice is to report IFR if visibility unavailable """ # Parse visibility if not vis: return 2 if vis.repr == 'CAVOK' or vis.repr.startswith('P6'): vis = 10 # type: ignore elif vis.repr.startswith('M'): vis = 0 # type: ignore # Convert meters to miles elif len(vis.repr) == 4: vis = vis.value * 0.000621371 # type: ignore else: vis = vis.value # type: ignore # Parse ceiling cld = ceiling.altitude if ceiling else 99 # Determine flight rules if (vis <= 5) or (cld <= 30): # type: ignore if (vis < 3) or (cld < 10): # type: ignore if (vis < 1) or (cld < 5): # type: ignore return 3 # LIFR return 2 # IFR return 1 # MVFR return 0
[ "def", "get_flight_rules", "(", "vis", ":", "Number", ",", "ceiling", ":", "Cloud", ")", "->", "int", ":", "# Parse visibility", "if", "not", "vis", ":", "return", "2", "if", "vis", ".", "repr", "==", "'CAVOK'", "or", "vis", ".", "repr", ".", "startswith", "(", "'P6'", ")", ":", "vis", "=", "10", "# type: ignore", "elif", "vis", ".", "repr", ".", "startswith", "(", "'M'", ")", ":", "vis", "=", "0", "# type: ignore", "# Convert meters to miles", "elif", "len", "(", "vis", ".", "repr", ")", "==", "4", ":", "vis", "=", "vis", ".", "value", "*", "0.000621371", "# type: ignore", "else", ":", "vis", "=", "vis", ".", "value", "# type: ignore", "# Parse ceiling", "cld", "=", "ceiling", ".", "altitude", "if", "ceiling", "else", "99", "# Determine flight rules", "if", "(", "vis", "<=", "5", ")", "or", "(", "cld", "<=", "30", ")", ":", "# type: ignore", "if", "(", "vis", "<", "3", ")", "or", "(", "cld", "<", "10", ")", ":", "# type: ignore", "if", "(", "vis", "<", "1", ")", "or", "(", "cld", "<", "5", ")", ":", "# type: ignore", "return", "3", "# LIFR", "return", "2", "# IFR", "return", "1", "# MVFR", "return", "0" ]
Returns int based on current flight rules from parsed METAR data 0=VFR, 1=MVFR, 2=IFR, 3=LIFR Note: Common practice is to report IFR if visibility unavailable
[ "Returns", "int", "based", "on", "current", "flight", "rules", "from", "parsed", "METAR", "data" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L795-L824
244,893
etcher-be/emiz
emiz/avwx/core.py
get_taf_flight_rules
def get_taf_flight_rules(lines: [dict]) -> [dict]: # type: ignore """ Get flight rules by looking for missing data in prior reports """ for i, line in enumerate(lines): temp_vis, temp_cloud = line['visibility'], line['clouds'] for report in reversed(lines[:i]): if not _is_tempo_or_prob(report['type']): if temp_vis == '': temp_vis = report['visibility'] if 'SKC' in report['other'] or 'CLR' in report['other']: temp_cloud = 'temp-clear' elif temp_cloud == []: temp_cloud = report['clouds'] if temp_vis != '' and temp_cloud != []: break if temp_cloud == 'temp-clear': temp_cloud = [] line['flight_rules'] = FLIGHT_RULES[get_flight_rules(temp_vis, get_ceiling(temp_cloud))] return lines
python
def get_taf_flight_rules(lines: [dict]) -> [dict]: # type: ignore """ Get flight rules by looking for missing data in prior reports """ for i, line in enumerate(lines): temp_vis, temp_cloud = line['visibility'], line['clouds'] for report in reversed(lines[:i]): if not _is_tempo_or_prob(report['type']): if temp_vis == '': temp_vis = report['visibility'] if 'SKC' in report['other'] or 'CLR' in report['other']: temp_cloud = 'temp-clear' elif temp_cloud == []: temp_cloud = report['clouds'] if temp_vis != '' and temp_cloud != []: break if temp_cloud == 'temp-clear': temp_cloud = [] line['flight_rules'] = FLIGHT_RULES[get_flight_rules(temp_vis, get_ceiling(temp_cloud))] return lines
[ "def", "get_taf_flight_rules", "(", "lines", ":", "[", "dict", "]", ")", "->", "[", "dict", "]", ":", "# type: ignore", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "temp_vis", ",", "temp_cloud", "=", "line", "[", "'visibility'", "]", ",", "line", "[", "'clouds'", "]", "for", "report", "in", "reversed", "(", "lines", "[", ":", "i", "]", ")", ":", "if", "not", "_is_tempo_or_prob", "(", "report", "[", "'type'", "]", ")", ":", "if", "temp_vis", "==", "''", ":", "temp_vis", "=", "report", "[", "'visibility'", "]", "if", "'SKC'", "in", "report", "[", "'other'", "]", "or", "'CLR'", "in", "report", "[", "'other'", "]", ":", "temp_cloud", "=", "'temp-clear'", "elif", "temp_cloud", "==", "[", "]", ":", "temp_cloud", "=", "report", "[", "'clouds'", "]", "if", "temp_vis", "!=", "''", "and", "temp_cloud", "!=", "[", "]", ":", "break", "if", "temp_cloud", "==", "'temp-clear'", ":", "temp_cloud", "=", "[", "]", "line", "[", "'flight_rules'", "]", "=", "FLIGHT_RULES", "[", "get_flight_rules", "(", "temp_vis", ",", "get_ceiling", "(", "temp_cloud", ")", ")", "]", "return", "lines" ]
Get flight rules by looking for missing data in prior reports
[ "Get", "flight", "rules", "by", "looking", "for", "missing", "data", "in", "prior", "reports" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L827-L846
244,894
etcher-be/emiz
emiz/avwx/core.py
get_ceiling
def get_ceiling(clouds: [Cloud]) -> Cloud: # type: ignore """ Returns ceiling layer from Cloud-List or None if none found Assumes that the clouds are already sorted lowest to highest Only 'Broken', 'Overcast', and 'Vertical Visibility' are considdered ceilings Prevents errors due to lack of cloud information (eg. '' or 'FEW///') """ for cloud in clouds: if cloud.altitude and cloud.type in ('OVC', 'BKN', 'VV'): return cloud return None
python
def get_ceiling(clouds: [Cloud]) -> Cloud: # type: ignore """ Returns ceiling layer from Cloud-List or None if none found Assumes that the clouds are already sorted lowest to highest Only 'Broken', 'Overcast', and 'Vertical Visibility' are considdered ceilings Prevents errors due to lack of cloud information (eg. '' or 'FEW///') """ for cloud in clouds: if cloud.altitude and cloud.type in ('OVC', 'BKN', 'VV'): return cloud return None
[ "def", "get_ceiling", "(", "clouds", ":", "[", "Cloud", "]", ")", "->", "Cloud", ":", "# type: ignore", "for", "cloud", "in", "clouds", ":", "if", "cloud", ".", "altitude", "and", "cloud", ".", "type", "in", "(", "'OVC'", ",", "'BKN'", ",", "'VV'", ")", ":", "return", "cloud", "return", "None" ]
Returns ceiling layer from Cloud-List or None if none found Assumes that the clouds are already sorted lowest to highest Only 'Broken', 'Overcast', and 'Vertical Visibility' are considdered ceilings Prevents errors due to lack of cloud information (eg. '' or 'FEW///')
[ "Returns", "ceiling", "layer", "from", "Cloud", "-", "List", "or", "None", "if", "none", "found" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L849-L862
244,895
etcher-be/emiz
emiz/avwx/core.py
parse_date
def parse_date(date: str, hour_threshold: int = 200): """ Parses a report timestamp in ddhhZ or ddhhmmZ format This function assumes the given timestamp is within the hour threshold from current date """ # Format date string date = date.strip('Z') if len(date) == 4: date += '00' if not (len(date) == 6 and date.isdigit()): return # Create initial guess now = datetime.utcnow() guess = now.replace(day=int(date[0:2]), hour=int(date[2:4]) % 24, minute=int(date[4:6]) % 60, second=0, microsecond=0) hourdiff = (guess - now) / timedelta(minutes=1) / 60 # Handle changing months if hourdiff > hour_threshold: guess += relativedelta(months=-1) elif hourdiff < -hour_threshold: guess += relativedelta(months=+1) return guess
python
def parse_date(date: str, hour_threshold: int = 200): """ Parses a report timestamp in ddhhZ or ddhhmmZ format This function assumes the given timestamp is within the hour threshold from current date """ # Format date string date = date.strip('Z') if len(date) == 4: date += '00' if not (len(date) == 6 and date.isdigit()): return # Create initial guess now = datetime.utcnow() guess = now.replace(day=int(date[0:2]), hour=int(date[2:4]) % 24, minute=int(date[4:6]) % 60, second=0, microsecond=0) hourdiff = (guess - now) / timedelta(minutes=1) / 60 # Handle changing months if hourdiff > hour_threshold: guess += relativedelta(months=-1) elif hourdiff < -hour_threshold: guess += relativedelta(months=+1) return guess
[ "def", "parse_date", "(", "date", ":", "str", ",", "hour_threshold", ":", "int", "=", "200", ")", ":", "# Format date string", "date", "=", "date", ".", "strip", "(", "'Z'", ")", "if", "len", "(", "date", ")", "==", "4", ":", "date", "+=", "'00'", "if", "not", "(", "len", "(", "date", ")", "==", "6", "and", "date", ".", "isdigit", "(", ")", ")", ":", "return", "# Create initial guess", "now", "=", "datetime", ".", "utcnow", "(", ")", "guess", "=", "now", ".", "replace", "(", "day", "=", "int", "(", "date", "[", "0", ":", "2", "]", ")", ",", "hour", "=", "int", "(", "date", "[", "2", ":", "4", "]", ")", "%", "24", ",", "minute", "=", "int", "(", "date", "[", "4", ":", "6", "]", ")", "%", "60", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "hourdiff", "=", "(", "guess", "-", "now", ")", "/", "timedelta", "(", "minutes", "=", "1", ")", "/", "60", "# Handle changing months", "if", "hourdiff", ">", "hour_threshold", ":", "guess", "+=", "relativedelta", "(", "months", "=", "-", "1", ")", "elif", "hourdiff", "<", "-", "hour_threshold", ":", "guess", "+=", "relativedelta", "(", "months", "=", "+", "1", ")", "return", "guess" ]
Parses a report timestamp in ddhhZ or ddhhmmZ format This function assumes the given timestamp is within the hour threshold from current date
[ "Parses", "a", "report", "timestamp", "in", "ddhhZ", "or", "ddhhmmZ", "format" ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L865-L889
244,896
delfick/aws_syncr
aws_syncr/option_spec/buckets.py
Buckets.sync_one
def sync_one(self, aws_syncr, amazon, bucket): """Make sure this bucket exists and has only attributes we want it to have""" if bucket.permission.statements: permission_document = bucket.permission.document else: permission_document = "" bucket_info = amazon.s3.bucket_info(bucket.name) if not bucket_info.creation_date: amazon.s3.create_bucket(bucket.name, permission_document, bucket) else: amazon.s3.modify_bucket(bucket_info, bucket.name, permission_document, bucket)
python
def sync_one(self, aws_syncr, amazon, bucket): """Make sure this bucket exists and has only attributes we want it to have""" if bucket.permission.statements: permission_document = bucket.permission.document else: permission_document = "" bucket_info = amazon.s3.bucket_info(bucket.name) if not bucket_info.creation_date: amazon.s3.create_bucket(bucket.name, permission_document, bucket) else: amazon.s3.modify_bucket(bucket_info, bucket.name, permission_document, bucket)
[ "def", "sync_one", "(", "self", ",", "aws_syncr", ",", "amazon", ",", "bucket", ")", ":", "if", "bucket", ".", "permission", ".", "statements", ":", "permission_document", "=", "bucket", ".", "permission", ".", "document", "else", ":", "permission_document", "=", "\"\"", "bucket_info", "=", "amazon", ".", "s3", ".", "bucket_info", "(", "bucket", ".", "name", ")", "if", "not", "bucket_info", ".", "creation_date", ":", "amazon", ".", "s3", ".", "create_bucket", "(", "bucket", ".", "name", ",", "permission_document", ",", "bucket", ")", "else", ":", "amazon", ".", "s3", ".", "modify_bucket", "(", "bucket_info", ",", "bucket", ".", "name", ",", "permission_document", ",", "bucket", ")" ]
Make sure this bucket exists and has only attributes we want it to have
[ "Make", "sure", "this", "bucket", "exists", "and", "has", "only", "attributes", "we", "want", "it", "to", "have" ]
8cd214b27c1eee98dfba4632cbb8bc0ae36356bd
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/option_spec/buckets.py#L312-L323
244,897
matthewdeanmartin/jiggle_version
jiggle_version/file_opener.py
FileOpener.is_python_inside
def is_python_inside(self, file_path): # type: (str) -> bool """ If .py, yes. If extensionless, open file and check shebang TODO: support variations on this: #!/usr/bin/env python :param file_path: :return: """ if file_path.endswith(".py"): return True # duh. # not supporting surprising extensions, ege. .py2, .python, .corn_chowder # extensionless if "." not in file_path: try: firstline = self.open_this(file_path, "r").readline() if firstline.startswith("#") and "python" in firstline: return True except: pass return False
python
def is_python_inside(self, file_path): # type: (str) -> bool """ If .py, yes. If extensionless, open file and check shebang TODO: support variations on this: #!/usr/bin/env python :param file_path: :return: """ if file_path.endswith(".py"): return True # duh. # not supporting surprising extensions, ege. .py2, .python, .corn_chowder # extensionless if "." not in file_path: try: firstline = self.open_this(file_path, "r").readline() if firstline.startswith("#") and "python" in firstline: return True except: pass return False
[ "def", "is_python_inside", "(", "self", ",", "file_path", ")", ":", "# type: (str) -> bool", "if", "file_path", ".", "endswith", "(", "\".py\"", ")", ":", "return", "True", "# duh.", "# not supporting surprising extensions, ege. .py2, .python, .corn_chowder", "# extensionless", "if", "\".\"", "not", "in", "file_path", ":", "try", ":", "firstline", "=", "self", ".", "open_this", "(", "file_path", ",", "\"r\"", ")", ".", "readline", "(", ")", "if", "firstline", ".", "startswith", "(", "\"#\"", ")", "and", "\"python\"", "in", "firstline", ":", "return", "True", "except", ":", "pass", "return", "False" ]
If .py, yes. If extensionless, open file and check shebang TODO: support variations on this: #!/usr/bin/env python :param file_path: :return:
[ "If", ".", "py", "yes", ".", "If", "extensionless", "open", "file", "and", "check", "shebang" ]
963656a0a47b7162780a5f6c8f4b8bbbebc148f5
https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/file_opener.py#L38-L61
244,898
rameshg87/pyremotevbox
pyremotevbox/ZSI/wstools/XMLname.py
toXMLname
def toXMLname(string): """Convert string to a XML name.""" if string.find(':') != -1 : (prefix, localname) = string.split(':',1) else: prefix = None localname = string T = unicode(localname) N = len(localname) X = []; for i in range(N) : if i< N-1 and T[i]==u'_' and T[i+1]==u'x': X.append(u'_x005F_') elif i==0 and N >= 3 and \ ( T[0]==u'x' or T[0]==u'X' ) and \ ( T[1]==u'm' or T[1]==u'M' ) and \ ( T[2]==u'l' or T[2]==u'L' ): X.append(u'_xFFFF_' + T[0]) elif (not _NCNameChar(T[i])) or (i==0 and not _NCNameStartChar(T[i])): X.append(_toUnicodeHex(T[i])) else: X.append(T[i]) if prefix: return "%s:%s" % (prefix, u''.join(X)) return u''.join(X)
python
def toXMLname(string): """Convert string to a XML name.""" if string.find(':') != -1 : (prefix, localname) = string.split(':',1) else: prefix = None localname = string T = unicode(localname) N = len(localname) X = []; for i in range(N) : if i< N-1 and T[i]==u'_' and T[i+1]==u'x': X.append(u'_x005F_') elif i==0 and N >= 3 and \ ( T[0]==u'x' or T[0]==u'X' ) and \ ( T[1]==u'm' or T[1]==u'M' ) and \ ( T[2]==u'l' or T[2]==u'L' ): X.append(u'_xFFFF_' + T[0]) elif (not _NCNameChar(T[i])) or (i==0 and not _NCNameStartChar(T[i])): X.append(_toUnicodeHex(T[i])) else: X.append(T[i]) if prefix: return "%s:%s" % (prefix, u''.join(X)) return u''.join(X)
[ "def", "toXMLname", "(", "string", ")", ":", "if", "string", ".", "find", "(", "':'", ")", "!=", "-", "1", ":", "(", "prefix", ",", "localname", ")", "=", "string", ".", "split", "(", "':'", ",", "1", ")", "else", ":", "prefix", "=", "None", "localname", "=", "string", "T", "=", "unicode", "(", "localname", ")", "N", "=", "len", "(", "localname", ")", "X", "=", "[", "]", "for", "i", "in", "range", "(", "N", ")", ":", "if", "i", "<", "N", "-", "1", "and", "T", "[", "i", "]", "==", "u'_'", "and", "T", "[", "i", "+", "1", "]", "==", "u'x'", ":", "X", ".", "append", "(", "u'_x005F_'", ")", "elif", "i", "==", "0", "and", "N", ">=", "3", "and", "(", "T", "[", "0", "]", "==", "u'x'", "or", "T", "[", "0", "]", "==", "u'X'", ")", "and", "(", "T", "[", "1", "]", "==", "u'm'", "or", "T", "[", "1", "]", "==", "u'M'", ")", "and", "(", "T", "[", "2", "]", "==", "u'l'", "or", "T", "[", "2", "]", "==", "u'L'", ")", ":", "X", ".", "append", "(", "u'_xFFFF_'", "+", "T", "[", "0", "]", ")", "elif", "(", "not", "_NCNameChar", "(", "T", "[", "i", "]", ")", ")", "or", "(", "i", "==", "0", "and", "not", "_NCNameStartChar", "(", "T", "[", "i", "]", ")", ")", ":", "X", ".", "append", "(", "_toUnicodeHex", "(", "T", "[", "i", "]", ")", ")", "else", ":", "X", ".", "append", "(", "T", "[", "i", "]", ")", "if", "prefix", ":", "return", "\"%s:%s\"", "%", "(", "prefix", ",", "u''", ".", "join", "(", "X", ")", ")", "return", "u''", ".", "join", "(", "X", ")" ]
Convert string to a XML name.
[ "Convert", "string", "to", "a", "XML", "name", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/XMLname.py#L50-L77
244,899
rameshg87/pyremotevbox
pyremotevbox/ZSI/wstools/XMLname.py
fromXMLname
def fromXMLname(string): """Convert XML name to unicode string.""" retval = sub(r'_xFFFF_','', string ) def fun( matchobj ): return _fromUnicodeHex( matchobj.group(0) ) retval = sub(r'_x[0-9A-Za-z]+_', fun, retval ) return retval
python
def fromXMLname(string): """Convert XML name to unicode string.""" retval = sub(r'_xFFFF_','', string ) def fun( matchobj ): return _fromUnicodeHex( matchobj.group(0) ) retval = sub(r'_x[0-9A-Za-z]+_', fun, retval ) return retval
[ "def", "fromXMLname", "(", "string", ")", ":", "retval", "=", "sub", "(", "r'_xFFFF_'", ",", "''", ",", "string", ")", "def", "fun", "(", "matchobj", ")", ":", "return", "_fromUnicodeHex", "(", "matchobj", ".", "group", "(", "0", ")", ")", "retval", "=", "sub", "(", "r'_x[0-9A-Za-z]+_'", ",", "fun", ",", "retval", ")", "return", "retval" ]
Convert XML name to unicode string.
[ "Convert", "XML", "name", "to", "unicode", "string", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/XMLname.py#L80-L90