repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
abw333/dominoes
dominoes/game.py
_remaining_points
def _remaining_points(hands): ''' :param list hands: hands for which to compute the remaining points :return: a list indicating the amount of points remaining in each of the input hands ''' points = [] for hand in hands: points.append(sum(d.first + d.second for d in hand)) ...
python
def _remaining_points(hands): ''' :param list hands: hands for which to compute the remaining points :return: a list indicating the amount of points remaining in each of the input hands ''' points = [] for hand in hands: points.append(sum(d.first + d.second for d in hand)) ...
[ "def", "_remaining_points", "(", "hands", ")", ":", "points", "=", "[", "]", "for", "hand", "in", "hands", ":", "points", ".", "append", "(", "sum", "(", "d", ".", "first", "+", "d", ".", "second", "for", "d", "in", "hand", ")", ")", "return", "p...
:param list hands: hands for which to compute the remaining points :return: a list indicating the amount of points remaining in each of the input hands
[ ":", "param", "list", "hands", ":", "hands", "for", "which", "to", "compute", "the", "remaining", "points", ":", "return", ":", "a", "list", "indicating", "the", "amount", "of", "points", "remaining", "in", "each", "of", "the", "input", "hands" ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/game.py#L43-L53
abw333/dominoes
dominoes/game.py
_validate_hands
def _validate_hands(hands, missing): ''' Validates hands, based on values that are supposed to be missing from them. :param list hands: list of Hand objects to validate :param list missing: list of sets that indicate the values that are supposed to be missing from ...
python
def _validate_hands(hands, missing): ''' Validates hands, based on values that are supposed to be missing from them. :param list hands: list of Hand objects to validate :param list missing: list of sets that indicate the values that are supposed to be missing from ...
[ "def", "_validate_hands", "(", "hands", ",", "missing", ")", ":", "for", "h", ",", "m", "in", "zip", "(", "hands", ",", "missing", ")", ":", "for", "value", "in", "m", ":", "if", "dominoes", ".", "hand", ".", "contains_value", "(", "h", ",", "value...
Validates hands, based on values that are supposed to be missing from them. :param list hands: list of Hand objects to validate :param list missing: list of sets that indicate the values that are supposed to be missing from the respective Hand objects :...
[ "Validates", "hands", "based", "on", "values", "that", "are", "supposed", "to", "be", "missing", "from", "them", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/game.py#L55-L72
abw333/dominoes
dominoes/game.py
_all_possible_partitionings
def _all_possible_partitionings(elements, sizes): ''' Helper function for Game.all_possible_hands(). Given a set of elements and the sizes of partitions, yields all possible partitionings of the elements into partitions of the provided sizes. :param set elements: a set of elements to partition. ...
python
def _all_possible_partitionings(elements, sizes): ''' Helper function for Game.all_possible_hands(). Given a set of elements and the sizes of partitions, yields all possible partitionings of the elements into partitions of the provided sizes. :param set elements: a set of elements to partition. ...
[ "def", "_all_possible_partitionings", "(", "elements", ",", "sizes", ")", ":", "try", ":", "# get the size of the current partition", "size", "=", "sizes", "[", "0", "]", "except", "IndexError", ":", "# base case: no more sizes left", "yield", "(", ")", "return", "#...
Helper function for Game.all_possible_hands(). Given a set of elements and the sizes of partitions, yields all possible partitionings of the elements into partitions of the provided sizes. :param set elements: a set of elements to partition. :param list sizes: a list of sizes for the partitions. The su...
[ "Helper", "function", "for", "Game", ".", "all_possible_hands", "()", ".", "Given", "a", "set", "of", "elements", "and", "the", "sizes", "of", "partitions", "yields", "all", "possible", "partitionings", "of", "the", "elements", "into", "partitions", "of", "the...
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/game.py#L74-L101
abw333/dominoes
dominoes/game.py
Game.new
def new(cls, starting_domino=None, starting_player=0): ''' :param Domino starting_domino: the domino that should be played to start the game. The player with this domino in their hand wil...
python
def new(cls, starting_domino=None, starting_player=0): ''' :param Domino starting_domino: the domino that should be played to start the game. The player with this domino in their hand wil...
[ "def", "new", "(", "cls", ",", "starting_domino", "=", "None", ",", "starting_player", "=", "0", ")", ":", "board", "=", "dominoes", ".", "Board", "(", ")", "hands", "=", "_randomized_hands", "(", ")", "moves", "=", "[", "]", "result", "=", "None", "...
:param Domino starting_domino: the domino that should be played to start the game. The player with this domino in their hand will play first. :param int starting_player: the player that should pl...
[ ":", "param", "Domino", "starting_domino", ":", "the", "domino", "that", "should", "be", "played", "to", "start", "the", "game", ".", "The", "player", "with", "this", "domino", "in", "their", "hand", "will", "play", "first", ".", ":", "param", "int", "st...
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/game.py#L236-L273
abw333/dominoes
dominoes/game.py
Game._update_valid_moves
def _update_valid_moves(self): ''' Updates self.valid_moves according to the latest game state. Assumes that the board and all hands are non-empty. ''' left_end = self.board.left_end() right_end = self.board.right_end() moves = [] for d in self.hands[self...
python
def _update_valid_moves(self): ''' Updates self.valid_moves according to the latest game state. Assumes that the board and all hands are non-empty. ''' left_end = self.board.left_end() right_end = self.board.right_end() moves = [] for d in self.hands[self...
[ "def", "_update_valid_moves", "(", "self", ")", ":", "left_end", "=", "self", ".", "board", ".", "left_end", "(", ")", "right_end", "=", "self", ".", "board", ".", "right_end", "(", ")", "moves", "=", "[", "]", "for", "d", "in", "self", ".", "hands",...
Updates self.valid_moves according to the latest game state. Assumes that the board and all hands are non-empty.
[ "Updates", "self", ".", "valid_moves", "according", "to", "the", "latest", "game", "state", ".", "Assumes", "that", "the", "board", "and", "all", "hands", "are", "non", "-", "empty", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/game.py#L284-L301
abw333/dominoes
dominoes/game.py
Game.make_move
def make_move(self, d, left): ''' Plays a domino from the hand of the player whose turn it is onto one end of the game board. If the game does not end, the turn is advanced to the next player who has a valid move. Making a move is transactional - if the operation fails at any po...
python
def make_move(self, d, left): ''' Plays a domino from the hand of the player whose turn it is onto one end of the game board. If the game does not end, the turn is advanced to the next player who has a valid move. Making a move is transactional - if the operation fails at any po...
[ "def", "make_move", "(", "self", ",", "d", ",", "left", ")", ":", "if", "self", ".", "result", "is", "not", "None", ":", "raise", "dominoes", ".", "GameOverException", "(", "'Cannot make a move - the game is over!'", ")", "i", "=", "self", ".", "hands", "[...
Plays a domino from the hand of the player whose turn it is onto one end of the game board. If the game does not end, the turn is advanced to the next player who has a valid move. Making a move is transactional - if the operation fails at any point, the game will return to its state bef...
[ "Plays", "a", "domino", "from", "the", "hand", "of", "the", "player", "whose", "turn", "it", "is", "onto", "one", "end", "of", "the", "game", "board", ".", "If", "the", "game", "does", "not", "end", "the", "turn", "is", "advanced", "to", "the", "next...
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/game.py#L303-L373
abw333/dominoes
dominoes/game.py
Game.missing_values
def missing_values(self): ''' Computes the values that must be missing from each player's hand, based on when they have passed. :return: a list of sets, each one containing the values that must be missing from the corresponding player's hand '''...
python
def missing_values(self): ''' Computes the values that must be missing from each player's hand, based on when they have passed. :return: a list of sets, each one containing the values that must be missing from the corresponding player's hand '''...
[ "def", "missing_values", "(", "self", ")", ":", "missing", "=", "[", "set", "(", ")", "for", "_", "in", "self", ".", "hands", "]", "# replay the game from the beginning", "board", "=", "dominoes", ".", "SkinnyBoard", "(", ")", "player", "=", "self", ".", ...
Computes the values that must be missing from each player's hand, based on when they have passed. :return: a list of sets, each one containing the values that must be missing from the corresponding player's hand
[ "Computes", "the", "values", "that", "must", "be", "missing", "from", "each", "player", "s", "hand", "based", "on", "when", "they", "have", "passed", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/game.py#L375-L400
abw333/dominoes
dominoes/game.py
Game.random_possible_hands
def random_possible_hands(self): ''' Returns random possible hands for all players, given the information known by the player whose turn it is. This information includes the current player's hand, the sizes of the other players' hands, and the moves played by every player, includ...
python
def random_possible_hands(self): ''' Returns random possible hands for all players, given the information known by the player whose turn it is. This information includes the current player's hand, the sizes of the other players' hands, and the moves played by every player, includ...
[ "def", "random_possible_hands", "(", "self", ")", ":", "# compute values that must be missing from", "# each hand, to rule out impossible hands", "missing", "=", "self", ".", "missing_values", "(", ")", "# get the dominoes that are in all of the other hands. note that, even", "# thou...
Returns random possible hands for all players, given the information known by the player whose turn it is. This information includes the current player's hand, the sizes of the other players' hands, and the moves played by every player, including the passes. :return: a list of possible ...
[ "Returns", "random", "possible", "hands", "for", "all", "players", "given", "the", "information", "known", "by", "the", "player", "whose", "turn", "it", "is", ".", "This", "information", "includes", "the", "current", "player", "s", "hand", "the", "sizes", "o...
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/game.py#L402-L440
abw333/dominoes
dominoes/game.py
Game.all_possible_hands
def all_possible_hands(self): ''' Yields all possible hands for all players, given the information known by the player whose turn it is. This information includes the current player's hand, the sizes of the other players' hands, and the moves played by every player, including the...
python
def all_possible_hands(self): ''' Yields all possible hands for all players, given the information known by the player whose turn it is. This information includes the current player's hand, the sizes of the other players' hands, and the moves played by every player, including the...
[ "def", "all_possible_hands", "(", "self", ")", ":", "# compute values that must be missing from", "# each hand, to rule out impossible hands", "missing", "=", "self", ".", "missing_values", "(", ")", "# get the dominoes that are in all of the other hands. note that, even", "# though ...
Yields all possible hands for all players, given the information known by the player whose turn it is. This information includes the current player's hand, the sizes of the other players' hands, and the moves played by every player, including the passes. :yields: a list of possible Hand...
[ "Yields", "all", "possible", "hands", "for", "all", "players", "given", "the", "information", "known", "by", "the", "player", "whose", "turn", "it", "is", ".", "This", "information", "includes", "the", "current", "player", "s", "hand", "the", "sizes", "of", ...
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/game.py#L442-L484
abw333/dominoes
dominoes/players.py
random
def random(game): ''' Prefers moves randomly. :param Game game: game to play :return: None ''' game.valid_moves = tuple(sorted(game.valid_moves, key=lambda _: rand.random()))
python
def random(game): ''' Prefers moves randomly. :param Game game: game to play :return: None ''' game.valid_moves = tuple(sorted(game.valid_moves, key=lambda _: rand.random()))
[ "def", "random", "(", "game", ")", ":", "game", ".", "valid_moves", "=", "tuple", "(", "sorted", "(", "game", ".", "valid_moves", ",", "key", "=", "lambda", "_", ":", "rand", ".", "random", "(", ")", ")", ")" ]
Prefers moves randomly. :param Game game: game to play :return: None
[ "Prefers", "moves", "randomly", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/players.py#L71-L78
abw333/dominoes
dominoes/players.py
bota_gorda
def bota_gorda(game): ''' Prefers to play dominoes with higher point values. :param Game game: game to play :return: None ''' game.valid_moves = tuple(sorted(game.valid_moves, key=lambda m: -(m[0].first + m[0].second)))
python
def bota_gorda(game): ''' Prefers to play dominoes with higher point values. :param Game game: game to play :return: None ''' game.valid_moves = tuple(sorted(game.valid_moves, key=lambda m: -(m[0].first + m[0].second)))
[ "def", "bota_gorda", "(", "game", ")", ":", "game", ".", "valid_moves", "=", "tuple", "(", "sorted", "(", "game", ".", "valid_moves", ",", "key", "=", "lambda", "m", ":", "-", "(", "m", "[", "0", "]", ".", "first", "+", "m", "[", "0", "]", ".",...
Prefers to play dominoes with higher point values. :param Game game: game to play :return: None
[ "Prefers", "to", "play", "dominoes", "with", "higher", "point", "values", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/players.py#L89-L96
abw333/dominoes
dominoes/search.py
make_moves
def make_moves(game, player=dominoes.players.identity): ''' For each of a Game object's valid moves, yields a tuple containing the move and the Game object obtained by playing the move on the original Game object. The original Game object will be modified. :param Game game: the game to make mov...
python
def make_moves(game, player=dominoes.players.identity): ''' For each of a Game object's valid moves, yields a tuple containing the move and the Game object obtained by playing the move on the original Game object. The original Game object will be modified. :param Game game: the game to make mov...
[ "def", "make_moves", "(", "game", ",", "player", "=", "dominoes", ".", "players", ".", "identity", ")", ":", "# game is over - do not yield anything", "if", "game", ".", "result", "is", "not", "None", ":", "return", "# determine the order in which to make moves", "p...
For each of a Game object's valid moves, yields a tuple containing the move and the Game object obtained by playing the move on the original Game object. The original Game object will be modified. :param Game game: the game to make moves on :param callable player: a player to call on the ...
[ "For", "each", "of", "a", "Game", "object", "s", "valid", "moves", "yields", "a", "tuple", "containing", "the", "move", "and", "the", "Game", "object", "obtained", "by", "playing", "the", "move", "on", "the", "original", "Game", "object", ".", "The", "or...
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/search.py#L5-L38
abw333/dominoes
dominoes/search.py
alphabeta
def alphabeta(game, alpha_beta=(-float('inf'), float('inf')), player=dominoes.players.identity): ''' Runs minimax search with alpha-beta pruning on the provided game. :param Game game: game to search :param tuple alpha_beta: a tuple of two floats that indicate ...
python
def alphabeta(game, alpha_beta=(-float('inf'), float('inf')), player=dominoes.players.identity): ''' Runs minimax search with alpha-beta pruning on the provided game. :param Game game: game to search :param tuple alpha_beta: a tuple of two floats that indicate ...
[ "def", "alphabeta", "(", "game", ",", "alpha_beta", "=", "(", "-", "float", "(", "'inf'", ")", ",", "float", "(", "'inf'", ")", ")", ",", "player", "=", "dominoes", ".", "players", ".", "identity", ")", ":", "# base case - game is over", "if", "game", ...
Runs minimax search with alpha-beta pruning on the provided game. :param Game game: game to search :param tuple alpha_beta: a tuple of two floats that indicate the initial values of alpha and beta, respectively. The default is (-inf, inf). :param ca...
[ "Runs", "minimax", "search", "with", "alpha", "-", "beta", "pruning", "on", "the", "provided", "game", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/search.py#L40-L81
abw333/dominoes
dominoes/series.py
Series.next_game
def next_game(self): ''' Advances the series to the next game, if possible. Also updates each team's score with points from the most recently completed game. :return: the next game, if the previous game did not end the series; None otherwise :raises SeriesOverEx...
python
def next_game(self): ''' Advances the series to the next game, if possible. Also updates each team's score with points from the most recently completed game. :return: the next game, if the previous game did not end the series; None otherwise :raises SeriesOverEx...
[ "def", "next_game", "(", "self", ")", ":", "if", "self", ".", "is_over", "(", ")", ":", "raise", "dominoes", ".", "SeriesOverException", "(", "'Cannot start a new game - series ended with a score of {} to {}'", ".", "format", "(", "*", "self", ".", "scores", ")", ...
Advances the series to the next game, if possible. Also updates each team's score with points from the most recently completed game. :return: the next game, if the previous game did not end the series; None otherwise :raises SeriesOverException: if the series has already ended ...
[ "Advances", "the", "series", "to", "the", "next", "game", "if", "possible", ".", "Also", "updates", "each", "team", "s", "score", "with", "points", "from", "the", "most", "recently", "completed", "game", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/series.py#L92-L134
abw333/dominoes
dominoes/skinny_board.py
SkinnyBoard.from_board
def from_board(cls, board): ''' :param Board board: board to represent :return: SkinnyBoard to represent the given Board ''' if len(board): left = board.left_end() right = board.right_end() else: left = None right = None ...
python
def from_board(cls, board): ''' :param Board board: board to represent :return: SkinnyBoard to represent the given Board ''' if len(board): left = board.left_end() right = board.right_end() else: left = None right = None ...
[ "def", "from_board", "(", "cls", ",", "board", ")", ":", "if", "len", "(", "board", ")", ":", "left", "=", "board", ".", "left_end", "(", ")", "right", "=", "board", ".", "right_end", "(", ")", "else", ":", "left", "=", "None", "right", "=", "Non...
:param Board board: board to represent :return: SkinnyBoard to represent the given Board
[ ":", "param", "Board", "board", ":", "board", "to", "represent", ":", "return", ":", "SkinnyBoard", "to", "represent", "the", "given", "Board" ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/skinny_board.py#L44-L56
abw333/dominoes
dominoes/skinny_board.py
SkinnyBoard._add_left
def _add_left(self, d): ''' Adds the provided domino to the left end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match ''' if not self: self._left = d.first self._right = d...
python
def _add_left(self, d): ''' Adds the provided domino to the left end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match ''' if not self: self._left = d.first self._right = d...
[ "def", "_add_left", "(", "self", ",", "d", ")", ":", "if", "not", "self", ":", "self", ".", "_left", "=", "d", ".", "first", "self", ".", "_right", "=", "d", ".", "second", "elif", "d", ".", "second", "==", "self", ".", "left_end", "(", ")", ":...
Adds the provided domino to the left end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match
[ "Adds", "the", "provided", "domino", "to", "the", "left", "end", "of", "the", "board", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/skinny_board.py#L80-L101
abw333/dominoes
dominoes/skinny_board.py
SkinnyBoard._add_right
def _add_right(self, d): ''' Adds the provided domino to the right end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match ''' if not self: self._left = d.first self._right =...
python
def _add_right(self, d): ''' Adds the provided domino to the right end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match ''' if not self: self._left = d.first self._right =...
[ "def", "_add_right", "(", "self", ",", "d", ")", ":", "if", "not", "self", ":", "self", ".", "_left", "=", "d", ".", "first", "self", ".", "_right", "=", "d", ".", "second", "elif", "d", ".", "first", "==", "self", ".", "right_end", "(", ")", "...
Adds the provided domino to the right end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match
[ "Adds", "the", "provided", "domino", "to", "the", "right", "end", "of", "the", "board", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/skinny_board.py#L103-L124
abw333/dominoes
dominoes/skinny_board.py
SkinnyBoard.add
def add(self, d, left): ''' Adds the provided domino to the specifed end of the board. :param Domino d: domino to add :param bool left: end of the board to which to add the domino (True for left, False for right) :return: None :raises EndsMismat...
python
def add(self, d, left): ''' Adds the provided domino to the specifed end of the board. :param Domino d: domino to add :param bool left: end of the board to which to add the domino (True for left, False for right) :return: None :raises EndsMismat...
[ "def", "add", "(", "self", ",", "d", ",", "left", ")", ":", "if", "left", ":", "self", ".", "_add_left", "(", "d", ")", "else", ":", "self", ".", "_add_right", "(", "d", ")" ]
Adds the provided domino to the specifed end of the board. :param Domino d: domino to add :param bool left: end of the board to which to add the domino (True for left, False for right) :return: None :raises EndsMismatchException: if the values do not match
[ "Adds", "the", "provided", "domino", "to", "the", "specifed", "end", "of", "the", "board", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/skinny_board.py#L126-L139
abw333/dominoes
dominoes/board.py
Board._add_left
def _add_left(self, d): ''' Adds the provided domino to the left end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match ''' if not self: self.board.append(d) elif d.first == sel...
python
def _add_left(self, d): ''' Adds the provided domino to the left end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match ''' if not self: self.board.append(d) elif d.first == sel...
[ "def", "_add_left", "(", "self", ",", "d", ")", ":", "if", "not", "self", ":", "self", ".", "board", ".", "append", "(", "d", ")", "elif", "d", ".", "first", "==", "self", ".", "left_end", "(", ")", ":", "self", ".", "board", ".", "appendleft", ...
Adds the provided domino to the left end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match
[ "Adds", "the", "provided", "domino", "to", "the", "left", "end", "of", "the", "board", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/board.py#L60-L78
abw333/dominoes
dominoes/board.py
Board._add_right
def _add_right(self, d): ''' Adds the provided domino to the right end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match ''' if not self: self.board.append(d) elif d.first == s...
python
def _add_right(self, d): ''' Adds the provided domino to the right end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match ''' if not self: self.board.append(d) elif d.first == s...
[ "def", "_add_right", "(", "self", ",", "d", ")", ":", "if", "not", "self", ":", "self", ".", "board", ".", "append", "(", "d", ")", "elif", "d", ".", "first", "==", "self", ".", "right_end", "(", ")", ":", "self", ".", "board", ".", "append", "...
Adds the provided domino to the right end of the board. :param Domino d: domino to add :return: None :raises EndsMismatchException: if the values do not match
[ "Adds", "the", "provided", "domino", "to", "the", "right", "end", "of", "the", "board", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/board.py#L80-L98
abw333/dominoes
dominoes/hand.py
Hand.play
def play(self, d): ''' Removes a domino from the hand. :param Domino d: domino to remove from the hand :return: the index within the hand of the played domino :raises NoSuchDominoException: if the domino is not in the hand ''' try: i = self._dominoes....
python
def play(self, d): ''' Removes a domino from the hand. :param Domino d: domino to remove from the hand :return: the index within the hand of the played domino :raises NoSuchDominoException: if the domino is not in the hand ''' try: i = self._dominoes....
[ "def", "play", "(", "self", ",", "d", ")", ":", "try", ":", "i", "=", "self", ".", "_dominoes", ".", "index", "(", "d", ")", "except", "ValueError", ":", "raise", "dominoes", ".", "NoSuchDominoException", "(", "'Cannot make move -'", "' {} is not in hand!'",...
Removes a domino from the hand. :param Domino d: domino to remove from the hand :return: the index within the hand of the played domino :raises NoSuchDominoException: if the domino is not in the hand
[ "Removes", "a", "domino", "from", "the", "hand", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/hand.py#L46-L61
abw333/dominoes
dominoes/hand.py
Hand.draw
def draw(self, d, i=None): ''' Adds a domino to the hand. :param Domino d: domino to add to the hand :param int i: index at which to add the domino; by default adds to the end of the hand :return: None ''' if i is None: self._dom...
python
def draw(self, d, i=None): ''' Adds a domino to the hand. :param Domino d: domino to add to the hand :param int i: index at which to add the domino; by default adds to the end of the hand :return: None ''' if i is None: self._dom...
[ "def", "draw", "(", "self", ",", "d", ",", "i", "=", "None", ")", ":", "if", "i", "is", "None", ":", "self", ".", "_dominoes", ".", "append", "(", "d", ")", "else", ":", "self", ".", "_dominoes", ".", "insert", "(", "i", ",", "d", ")" ]
Adds a domino to the hand. :param Domino d: domino to add to the hand :param int i: index at which to add the domino; by default adds to the end of the hand :return: None
[ "Adds", "a", "domino", "to", "the", "hand", "." ]
train
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/hand.py#L63-L75
albertz/music-player-core
compile_utils.py
find_exec_in_path
def find_exec_in_path(exec_name): """ :param str exec_name: :return: yields full paths :rtype: list[str] """ if "PATH" not in os.environ: return for p in os.environ["PATH"].split(":"): pp = "%s/%s" % (p, exec_name) if os.path.exists(pp): yield pp
python
def find_exec_in_path(exec_name): """ :param str exec_name: :return: yields full paths :rtype: list[str] """ if "PATH" not in os.environ: return for p in os.environ["PATH"].split(":"): pp = "%s/%s" % (p, exec_name) if os.path.exists(pp): yield pp
[ "def", "find_exec_in_path", "(", "exec_name", ")", ":", "if", "\"PATH\"", "not", "in", "os", ".", "environ", ":", "return", "for", "p", "in", "os", ".", "environ", "[", "\"PATH\"", "]", ".", "split", "(", "\":\"", ")", ":", "pp", "=", "\"%s/%s\"", "%...
:param str exec_name: :return: yields full paths :rtype: list[str]
[ ":", "param", "str", "exec_name", ":", ":", "return", ":", "yields", "full", "paths", ":", "rtype", ":", "list", "[", "str", "]" ]
train
https://github.com/albertz/music-player-core/blob/d124f8b43362648501d157a67d203d5f4ef008ad/compile_utils.py#L165-L176
albertz/music-player-core
compile_utils.py
get_pkg_config
def get_pkg_config(pkg_config_args, *packages): """ :param str|list[str] pkg_config_args: e.g. "--cflags" :param str packages: e.g. "python3" :rtype: list[str]|None """ if not isinstance(pkg_config_args, (tuple, list)): pkg_config_args = [pkg_config_args] # Maybe we have multiple pkg...
python
def get_pkg_config(pkg_config_args, *packages): """ :param str|list[str] pkg_config_args: e.g. "--cflags" :param str packages: e.g. "python3" :rtype: list[str]|None """ if not isinstance(pkg_config_args, (tuple, list)): pkg_config_args = [pkg_config_args] # Maybe we have multiple pkg...
[ "def", "get_pkg_config", "(", "pkg_config_args", ",", "*", "packages", ")", ":", "if", "not", "isinstance", "(", "pkg_config_args", ",", "(", "tuple", ",", "list", ")", ")", ":", "pkg_config_args", "=", "[", "pkg_config_args", "]", "# Maybe we have multiple pkg-...
:param str|list[str] pkg_config_args: e.g. "--cflags" :param str packages: e.g. "python3" :rtype: list[str]|None
[ ":", "param", "str|list", "[", "str", "]", "pkg_config_args", ":", "e", ".", "g", ".", "--", "cflags", ":", "param", "str", "packages", ":", "e", ".", "g", ".", "python3", ":", "rtype", ":", "list", "[", "str", "]", "|None" ]
train
https://github.com/albertz/music-player-core/blob/d124f8b43362648501d157a67d203d5f4ef008ad/compile_utils.py#L179-L196
albertz/music-player-core
setup.py
pkgconfig
def pkgconfig(*packages, **kw): """ :param str packages: list like 'libavutil', 'libavformat', ... :rtype: dict[str] """ kw = kw.copy() flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} # kwargs of :class:`Extension` for token in check_output(["pkg-config", "--libs", "--cflags"] + list(...
python
def pkgconfig(*packages, **kw): """ :param str packages: list like 'libavutil', 'libavformat', ... :rtype: dict[str] """ kw = kw.copy() flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} # kwargs of :class:`Extension` for token in check_output(["pkg-config", "--libs", "--cflags"] + list(...
[ "def", "pkgconfig", "(", "*", "packages", ",", "*", "*", "kw", ")", ":", "kw", "=", "kw", ".", "copy", "(", ")", "flag_map", "=", "{", "'-I'", ":", "'include_dirs'", ",", "'-L'", ":", "'library_dirs'", ",", "'-l'", ":", "'libraries'", "}", "# kwargs ...
:param str packages: list like 'libavutil', 'libavformat', ... :rtype: dict[str]
[ ":", "param", "str", "packages", ":", "list", "like", "libavutil", "libavformat", "...", ":", "rtype", ":", "dict", "[", "str", "]" ]
train
https://github.com/albertz/music-player-core/blob/d124f8b43362648501d157a67d203d5f4ef008ad/setup.py#L11-L23
fitodic/centerline
centerline/io.py
create_centerlines
def create_centerlines(src, dst, density=0.5): """ Create centerlines and save the to an ESRI Shapefile. Reads polygons from the `src` ESRI Shapefile, creates Centerline objects with the specified `density` parameter and writes them to the `dst` ESRI Shapefile. Only Polygon features are conver...
python
def create_centerlines(src, dst, density=0.5): """ Create centerlines and save the to an ESRI Shapefile. Reads polygons from the `src` ESRI Shapefile, creates Centerline objects with the specified `density` parameter and writes them to the `dst` ESRI Shapefile. Only Polygon features are conver...
[ "def", "create_centerlines", "(", "src", ",", "dst", ",", "density", "=", "0.5", ")", ":", "try", ":", "DST_DRIVER", "=", "get_ogr_driver", "(", "filepath", "=", "dst", ")", "except", "ValueError", ":", "raise", "with", "fiona", ".", "Env", "(", ")", "...
Create centerlines and save the to an ESRI Shapefile. Reads polygons from the `src` ESRI Shapefile, creates Centerline objects with the specified `density` parameter and writes them to the `dst` ESRI Shapefile. Only Polygon features are converted to centerlines. Features of different types are ski...
[ "Create", "centerlines", "and", "save", "the", "to", "an", "ESRI", "Shapefile", "." ]
train
https://github.com/fitodic/centerline/blob/f27e7b1ecb77bd4da40093ab44754cbd3ec9f58b/centerline/io.py#L14-L83
fitodic/centerline
centerline/main.py
Centerline._create_centerline
def _create_centerline(self): """ Calculate the centerline of a polygon. Densifies the border of a polygon which is then represented by a Numpy array of points necessary for creating the Voronoi diagram. Once the diagram is created, the ridges located within the polygon are ...
python
def _create_centerline(self): """ Calculate the centerline of a polygon. Densifies the border of a polygon which is then represented by a Numpy array of points necessary for creating the Voronoi diagram. Once the diagram is created, the ridges located within the polygon are ...
[ "def", "_create_centerline", "(", "self", ")", ":", "border", "=", "array", "(", "self", ".", "__densify_border", "(", ")", ")", "vor", "=", "Voronoi", "(", "border", ")", "vertex", "=", "vor", ".", "vertices", "lst_lines", "=", "[", "]", "for", "j", ...
Calculate the centerline of a polygon. Densifies the border of a polygon which is then represented by a Numpy array of points necessary for creating the Voronoi diagram. Once the diagram is created, the ridges located within the polygon are joined and returned. Returns: ...
[ "Calculate", "the", "centerline", "of", "a", "polygon", "." ]
train
https://github.com/fitodic/centerline/blob/f27e7b1ecb77bd4da40093ab44754cbd3ec9f58b/centerline/main.py#L62-L99
fitodic/centerline
centerline/main.py
Centerline.__densify_border
def __densify_border(self): """ Densify the border of a polygon. The border is densified by a given factor (by default: 0.5). The complexity of the polygon's geometry is evaluated in order to densify the borders of its interior rings as well. Returns: list:...
python
def __densify_border(self): """ Densify the border of a polygon. The border is densified by a given factor (by default: 0.5). The complexity of the polygon's geometry is evaluated in order to densify the borders of its interior rings as well. Returns: list:...
[ "def", "__densify_border", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_input_geom", ",", "MultiPolygon", ")", ":", "polygons", "=", "[", "polygon", "for", "polygon", "in", "self", ".", "_input_geom", "]", "else", ":", "polygons", "=", ...
Densify the border of a polygon. The border is densified by a given factor (by default: 0.5). The complexity of the polygon's geometry is evaluated in order to densify the borders of its interior rings as well. Returns: list: a list of points where each point is represente...
[ "Densify", "the", "border", "of", "a", "polygon", "." ]
train
https://github.com/fitodic/centerline/blob/f27e7b1ecb77bd4da40093ab44754cbd3ec9f58b/centerline/main.py#L101-L137
fitodic/centerline
centerline/main.py
Centerline.__fixed_interpolation
def __fixed_interpolation(self, line): """ Place additional points on the border at the specified distance. By default the distance is 0.5 (meters) which means that the first point will be placed 0.5 m from the starting point, the second point will be placed at the distance of 1...
python
def __fixed_interpolation(self, line): """ Place additional points on the border at the specified distance. By default the distance is 0.5 (meters) which means that the first point will be placed 0.5 m from the starting point, the second point will be placed at the distance of 1...
[ "def", "__fixed_interpolation", "(", "self", ",", "line", ")", ":", "STARTPOINT", "=", "[", "line", ".", "xy", "[", "0", "]", "[", "0", "]", "-", "self", ".", "_minx", ",", "line", ".", "xy", "[", "1", "]", "[", "0", "]", "-", "self", ".", "_...
Place additional points on the border at the specified distance. By default the distance is 0.5 (meters) which means that the first point will be placed 0.5 m from the starting point, the second point will be placed at the distance of 1.0 m from the first point, etc. The loop breaks whe...
[ "Place", "additional", "points", "on", "the", "border", "at", "the", "specified", "distance", "." ]
train
https://github.com/fitodic/centerline/blob/f27e7b1ecb77bd4da40093ab44754cbd3ec9f58b/centerline/main.py#L139-L173
fitodic/centerline
centerline/utils.py
is_valid_geometry
def is_valid_geometry(geometry): """ Confirm that the geometry type is of type Polygon or MultiPolygon. Args: geometry (BaseGeometry): BaseGeometry instance (e.g. Polygon) Returns: bool """ if isinstance(geometry, Polygon) or isinstance(geometry, MultiPolygon): return ...
python
def is_valid_geometry(geometry): """ Confirm that the geometry type is of type Polygon or MultiPolygon. Args: geometry (BaseGeometry): BaseGeometry instance (e.g. Polygon) Returns: bool """ if isinstance(geometry, Polygon) or isinstance(geometry, MultiPolygon): return ...
[ "def", "is_valid_geometry", "(", "geometry", ")", ":", "if", "isinstance", "(", "geometry", ",", "Polygon", ")", "or", "isinstance", "(", "geometry", ",", "MultiPolygon", ")", ":", "return", "True", "else", ":", "return", "False" ]
Confirm that the geometry type is of type Polygon or MultiPolygon. Args: geometry (BaseGeometry): BaseGeometry instance (e.g. Polygon) Returns: bool
[ "Confirm", "that", "the", "geometry", "type", "is", "of", "type", "Polygon", "or", "MultiPolygon", "." ]
train
https://github.com/fitodic/centerline/blob/f27e7b1ecb77bd4da40093ab44754cbd3ec9f58b/centerline/utils.py#L17-L31
fitodic/centerline
centerline/utils.py
get_ogr_driver
def get_ogr_driver(filepath): """ Get the OGR driver from the provided file extension. Args: file_extension (str): file extension Returns: osgeo.ogr.Driver Raises: ValueError: no driver is found """ filename, file_extension = os.path.splitext(filepath) EXTENSI...
python
def get_ogr_driver(filepath): """ Get the OGR driver from the provided file extension. Args: file_extension (str): file extension Returns: osgeo.ogr.Driver Raises: ValueError: no driver is found """ filename, file_extension = os.path.splitext(filepath) EXTENSI...
[ "def", "get_ogr_driver", "(", "filepath", ")", ":", "filename", ",", "file_extension", "=", "os", ".", "path", ".", "splitext", "(", "filepath", ")", "EXTENSION", "=", "file_extension", "[", "1", ":", "]", "ogr_driver_count", "=", "ogr", ".", "GetDriverCount...
Get the OGR driver from the provided file extension. Args: file_extension (str): file extension Returns: osgeo.ogr.Driver Raises: ValueError: no driver is found
[ "Get", "the", "OGR", "driver", "from", "the", "provided", "file", "extension", "." ]
train
https://github.com/fitodic/centerline/blob/f27e7b1ecb77bd4da40093ab44754cbd3ec9f58b/centerline/utils.py#L34-L63
marcolagi/quantulum
quantulum/regex.py
get_numwords
def get_numwords(): """Convert number words to integers in a given text.""" numwords = {'and': (1, 0), 'a': (1, 1), 'an': (1, 1)} for idx, word in enumerate(UNITS): numwords[word] = (1, idx) for idx, word in enumerate(TENS): numwords[word] = (1, idx * 10) for idx, word in enumerate(...
python
def get_numwords(): """Convert number words to integers in a given text.""" numwords = {'and': (1, 0), 'a': (1, 1), 'an': (1, 1)} for idx, word in enumerate(UNITS): numwords[word] = (1, idx) for idx, word in enumerate(TENS): numwords[word] = (1, idx * 10) for idx, word in enumerate(...
[ "def", "get_numwords", "(", ")", ":", "numwords", "=", "{", "'and'", ":", "(", "1", ",", "0", ")", ",", "'a'", ":", "(", "1", ",", "1", ")", ",", "'an'", ":", "(", "1", ",", "1", ")", "}", "for", "idx", ",", "word", "in", "enumerate", "(", ...
Convert number words to integers in a given text.
[ "Convert", "number", "words", "to", "integers", "in", "a", "given", "text", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/regex.py#L23-L36
marcolagi/quantulum
quantulum/regex.py
get_units_regex
def get_units_regex(): """Build a compiled regex object.""" op_keys = sorted(OPERATORS.keys(), key=len, reverse=True) unit_keys = sorted(l.UNITS.keys(), key=len, reverse=True) symbol_keys = sorted(l.SYMBOLS.keys(), key=len, reverse=True) exponent = ur'(?:(?:\^?\-?[0-9%s]*)(?:\ cubed|\ squared)?)(?!...
python
def get_units_regex(): """Build a compiled regex object.""" op_keys = sorted(OPERATORS.keys(), key=len, reverse=True) unit_keys = sorted(l.UNITS.keys(), key=len, reverse=True) symbol_keys = sorted(l.SYMBOLS.keys(), key=len, reverse=True) exponent = ur'(?:(?:\^?\-?[0-9%s]*)(?:\ cubed|\ squared)?)(?!...
[ "def", "get_units_regex", "(", ")", ":", "op_keys", "=", "sorted", "(", "OPERATORS", ".", "keys", "(", ")", ",", "key", "=", "len", ",", "reverse", "=", "True", ")", "unit_keys", "=", "sorted", "(", "l", ".", "UNITS", ".", "keys", "(", ")", ",", ...
Build a compiled regex object.
[ "Build", "a", "compiled", "regex", "object", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/regex.py#L105-L132
marcolagi/quantulum
quantulum/load.py
get_dimension_permutations
def get_dimension_permutations(entities, dimensions): """Get all possible dimensional definitions for an entity.""" new_dimensions = defaultdict(int) for item in dimensions: new = entities[item['base']].dimensions if new: for new_item in new: new_dimensions[new_it...
python
def get_dimension_permutations(entities, dimensions): """Get all possible dimensional definitions for an entity.""" new_dimensions = defaultdict(int) for item in dimensions: new = entities[item['base']].dimensions if new: for new_item in new: new_dimensions[new_it...
[ "def", "get_dimension_permutations", "(", "entities", ",", "dimensions", ")", ":", "new_dimensions", "=", "defaultdict", "(", "int", ")", "for", "item", "in", "dimensions", ":", "new", "=", "entities", "[", "item", "[", "'base'", "]", "]", ".", "dimensions",...
Get all possible dimensional definitions for an entity.
[ "Get", "all", "possible", "dimensional", "definitions", "for", "an", "entity", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/load.py#L34-L55
marcolagi/quantulum
quantulum/load.py
load_entities
def load_entities(): """Load entities from JSON file.""" path = os.path.join(TOPDIR, 'entities.json') entities = json.load(open(path)) names = [i['name'] for i in entities] try: assert len(set(names)) == len(entities) except AssertionError: raise Exception('Entities with same na...
python
def load_entities(): """Load entities from JSON file.""" path = os.path.join(TOPDIR, 'entities.json') entities = json.load(open(path)) names = [i['name'] for i in entities] try: assert len(set(names)) == len(entities) except AssertionError: raise Exception('Entities with same na...
[ "def", "load_entities", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "TOPDIR", ",", "'entities.json'", ")", "entities", "=", "json", ".", "load", "(", "open", "(", "path", ")", ")", "names", "=", "[", "i", "[", "'name'", "]", ...
Load entities from JSON file.
[ "Load", "entities", "from", "JSON", "file", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/load.py#L59-L84
marcolagi/quantulum
quantulum/load.py
get_dimensions_units
def get_dimensions_units(names): """Create dictionary of unit dimensions.""" dimensions_uni = {} for name in names: key = get_key_from_dimensions(names[name].dimensions) dimensions_uni[key] = names[name] plain_dimensions = [{'base': name, 'power': 1}] key = get_key_from_dim...
python
def get_dimensions_units(names): """Create dictionary of unit dimensions.""" dimensions_uni = {} for name in names: key = get_key_from_dimensions(names[name].dimensions) dimensions_uni[key] = names[name] plain_dimensions = [{'base': name, 'power': 1}] key = get_key_from_dim...
[ "def", "get_dimensions_units", "(", "names", ")", ":", "dimensions_uni", "=", "{", "}", "for", "name", "in", "names", ":", "key", "=", "get_key_from_dimensions", "(", "names", "[", "name", "]", ".", "dimensions", ")", "dimensions_uni", "[", "key", "]", "="...
Create dictionary of unit dimensions.
[ "Create", "dictionary", "of", "unit", "dimensions", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/load.py#L90-L109
marcolagi/quantulum
quantulum/load.py
load_units
def load_units(): """Load units from JSON file.""" names = {} lowers = defaultdict(list) symbols = defaultdict(list) surfaces = defaultdict(list) for unit in json.load(open(os.path.join(TOPDIR, 'units.json'))): try: assert unit['name'] not in names except AssertionEr...
python
def load_units(): """Load units from JSON file.""" names = {} lowers = defaultdict(list) symbols = defaultdict(list) surfaces = defaultdict(list) for unit in json.load(open(os.path.join(TOPDIR, 'units.json'))): try: assert unit['name'] not in names except AssertionEr...
[ "def", "load_units", "(", ")", ":", "names", "=", "{", "}", "lowers", "=", "defaultdict", "(", "list", ")", "symbols", "=", "defaultdict", "(", "list", ")", "surfaces", "=", "defaultdict", "(", "list", ")", "for", "unit", "in", "json", ".", "load", "...
Load units from JSON file.
[ "Load", "units", "from", "JSON", "file", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/load.py#L113-L160
marcolagi/quantulum
quantulum/classifier.py
download_wiki
def download_wiki(): """Download WikiPedia pages of ambiguous units.""" ambiguous = [i for i in l.UNITS.items() if len(i[1]) > 1] ambiguous += [i for i in l.DERIVED_ENT.items() if len(i[1]) > 1] pages = set([(j.name, j.uri) for i in ambiguous for j in i[1]]) print objs = [] for num, page in...
python
def download_wiki(): """Download WikiPedia pages of ambiguous units.""" ambiguous = [i for i in l.UNITS.items() if len(i[1]) > 1] ambiguous += [i for i in l.DERIVED_ENT.items() if len(i[1]) > 1] pages = set([(j.name, j.uri) for i in ambiguous for j in i[1]]) print objs = [] for num, page in...
[ "def", "download_wiki", "(", ")", ":", "ambiguous", "=", "[", "i", "for", "i", "in", "l", ".", "UNITS", ".", "items", "(", ")", "if", "len", "(", "i", "[", "1", "]", ")", ">", "1", "]", "ambiguous", "+=", "[", "i", "for", "i", "in", "l", "....
Download WikiPedia pages of ambiguous units.
[ "Download", "WikiPedia", "pages", "of", "ambiguous", "units", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/classifier.py#L28-L53
marcolagi/quantulum
quantulum/classifier.py
clean_text
def clean_text(text): """Clean text for TFIDF.""" new_text = re.sub(ur'\p{P}+', ' ', text) new_text = [stem(i) for i in new_text.lower().split() if not re.findall(r'[0-9]', i)] new_text = ' '.join(new_text) return new_text
python
def clean_text(text): """Clean text for TFIDF.""" new_text = re.sub(ur'\p{P}+', ' ', text) new_text = [stem(i) for i in new_text.lower().split() if not re.findall(r'[0-9]', i)] new_text = ' '.join(new_text) return new_text
[ "def", "clean_text", "(", "text", ")", ":", "new_text", "=", "re", ".", "sub", "(", "ur'\\p{P}+'", ",", "' '", ",", "text", ")", "new_text", "=", "[", "stem", "(", "i", ")", "for", "i", "in", "new_text", ".", "lower", "(", ")", ".", "split", "(",...
Clean text for TFIDF.
[ "Clean", "text", "for", "TFIDF", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/classifier.py#L57-L66
marcolagi/quantulum
quantulum/classifier.py
train_classifier
def train_classifier(download=True, parameters=None, ngram_range=(1, 1)): """Train the intent classifier.""" if download: download_wiki() path = os.path.join(l.TOPDIR, 'train.json') training_set = json.load(open(path)) path = os.path.join(l.TOPDIR, 'wiki.json') wiki_set = json.load(open...
python
def train_classifier(download=True, parameters=None, ngram_range=(1, 1)): """Train the intent classifier.""" if download: download_wiki() path = os.path.join(l.TOPDIR, 'train.json') training_set = json.load(open(path)) path = os.path.join(l.TOPDIR, 'wiki.json') wiki_set = json.load(open...
[ "def", "train_classifier", "(", "download", "=", "True", ",", "parameters", "=", "None", ",", "ngram_range", "=", "(", "1", ",", "1", ")", ")", ":", "if", "download", ":", "download_wiki", "(", ")", "path", "=", "os", ".", "path", ".", "join", "(", ...
Train the intent classifier.
[ "Train", "the", "intent", "classifier", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/classifier.py#L70-L101
marcolagi/quantulum
quantulum/classifier.py
load_classifier
def load_classifier(): """Train the intent classifier.""" path = os.path.join(l.TOPDIR, 'clf.pickle') obj = pickle.load(open(path, 'r')) return obj['tfidf_model'], obj['clf'], obj['target_names']
python
def load_classifier(): """Train the intent classifier.""" path = os.path.join(l.TOPDIR, 'clf.pickle') obj = pickle.load(open(path, 'r')) return obj['tfidf_model'], obj['clf'], obj['target_names']
[ "def", "load_classifier", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "l", ".", "TOPDIR", ",", "'clf.pickle'", ")", "obj", "=", "pickle", ".", "load", "(", "open", "(", "path", ",", "'r'", ")", ")", "return", "obj", "[", "'tf...
Train the intent classifier.
[ "Train", "the", "intent", "classifier", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/classifier.py#L105-L110
marcolagi/quantulum
quantulum/classifier.py
disambiguate_entity
def disambiguate_entity(key, text): """Resolve ambiguity between entities with same dimensionality.""" new_ent = l.DERIVED_ENT[key][0] if len(l.DERIVED_ENT[key]) > 1: transformed = TFIDF_MODEL.transform([text]) scores = CLF.predict_proba(transformed).tolist()[0] scores = sorted(zip(...
python
def disambiguate_entity(key, text): """Resolve ambiguity between entities with same dimensionality.""" new_ent = l.DERIVED_ENT[key][0] if len(l.DERIVED_ENT[key]) > 1: transformed = TFIDF_MODEL.transform([text]) scores = CLF.predict_proba(transformed).tolist()[0] scores = sorted(zip(...
[ "def", "disambiguate_entity", "(", "key", ",", "text", ")", ":", "new_ent", "=", "l", ".", "DERIVED_ENT", "[", "key", "]", "[", "0", "]", "if", "len", "(", "l", ".", "DERIVED_ENT", "[", "key", "]", ")", ">", "1", ":", "transformed", "=", "TFIDF_MOD...
Resolve ambiguity between entities with same dimensionality.
[ "Resolve", "ambiguity", "between", "entities", "with", "same", "dimensionality", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/classifier.py#L119-L135
marcolagi/quantulum
quantulum/classifier.py
disambiguate_unit
def disambiguate_unit(unit, text): """ Resolve ambiguity. Distinguish between units that have same names, symbols or abbreviations. """ new_unit = l.UNITS[unit] if not new_unit: new_unit = l.LOWER_UNITS[unit.lower()] if not new_unit: raise KeyError('Could not find un...
python
def disambiguate_unit(unit, text): """ Resolve ambiguity. Distinguish between units that have same names, symbols or abbreviations. """ new_unit = l.UNITS[unit] if not new_unit: new_unit = l.LOWER_UNITS[unit.lower()] if not new_unit: raise KeyError('Could not find un...
[ "def", "disambiguate_unit", "(", "unit", ",", "text", ")", ":", "new_unit", "=", "l", ".", "UNITS", "[", "unit", "]", "if", "not", "new_unit", ":", "new_unit", "=", "l", ".", "LOWER_UNITS", "[", "unit", ".", "lower", "(", ")", "]", "if", "not", "ne...
Resolve ambiguity. Distinguish between units that have same names, symbols or abbreviations.
[ "Resolve", "ambiguity", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/classifier.py#L139-L167
marcolagi/quantulum
quantulum/parser.py
clean_surface
def clean_surface(surface, span): """Remove spurious characters from a quantity's surface.""" surface = surface.replace('-', ' ') no_start = ['and', ' '] no_end = [' and', ' '] found = True while found: found = False for word in no_start: if surface.lower().startswit...
python
def clean_surface(surface, span): """Remove spurious characters from a quantity's surface.""" surface = surface.replace('-', ' ') no_start = ['and', ' '] no_end = [' and', ' '] found = True while found: found = False for word in no_start: if surface.lower().startswit...
[ "def", "clean_surface", "(", "surface", ",", "span", ")", ":", "surface", "=", "surface", ".", "replace", "(", "'-'", ",", "' '", ")", "no_start", "=", "[", "'and'", ",", "' '", "]", "no_end", "=", "[", "' and'", ",", "' '", "]", "found", "=", "Tru...
Remove spurious characters from a quantity's surface.
[ "Remove", "spurious", "characters", "from", "a", "quantity", "s", "surface", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L20-L49
marcolagi/quantulum
quantulum/parser.py
extract_spellout_values
def extract_spellout_values(text): """Convert spelled out numbers in a given text to digits.""" values = [] for item in r.REG_TXT.finditer(text): surface, span = clean_surface(item.group(0), item.span()) if not surface or surface.lower() in r.SCALES: continue curr = resul...
python
def extract_spellout_values(text): """Convert spelled out numbers in a given text to digits.""" values = [] for item in r.REG_TXT.finditer(text): surface, span = clean_surface(item.group(0), item.span()) if not surface or surface.lower() in r.SCALES: continue curr = resul...
[ "def", "extract_spellout_values", "(", "text", ")", ":", "values", "=", "[", "]", "for", "item", "in", "r", ".", "REG_TXT", ".", "finditer", "(", "text", ")", ":", "surface", ",", "span", "=", "clean_surface", "(", "item", ".", "group", "(", "0", ")"...
Convert spelled out numbers in a given text to digits.
[ "Convert", "spelled", "out", "numbers", "in", "a", "given", "text", "to", "digits", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L53-L79
marcolagi/quantulum
quantulum/parser.py
substitute_values
def substitute_values(text, values): """Convert spelled out numbers in a given text to digits.""" shift, final_text, shifts = 0, text, defaultdict(int) for value in values: first = value['old_span'][0] + shift second = value['old_span'][1] + shift new_s = value['new_surface'] ...
python
def substitute_values(text, values): """Convert spelled out numbers in a given text to digits.""" shift, final_text, shifts = 0, text, defaultdict(int) for value in values: first = value['old_span'][0] + shift second = value['old_span'][1] + shift new_s = value['new_surface'] ...
[ "def", "substitute_values", "(", "text", ",", "values", ")", ":", "shift", ",", "final_text", ",", "shifts", "=", "0", ",", "text", ",", "defaultdict", "(", "int", ")", "for", "value", "in", "values", ":", "first", "=", "value", "[", "'old_span'", "]",...
Convert spelled out numbers in a given text to digits.
[ "Convert", "spelled", "out", "numbers", "in", "a", "given", "text", "to", "digits", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L83-L97
marcolagi/quantulum
quantulum/parser.py
get_values
def get_values(item): """Extract value from regex hit.""" fracs = r'|'.join(r.UNI_FRAC) value = item.group(2) value = re.sub(ur'(?<=\d)(%s)10' % r.MULTIPLIERS, 'e', value) value = re.sub(fracs, callback, value, re.IGNORECASE) value = re.sub(' +', ' ', value) range_separator = re.findall(ur...
python
def get_values(item): """Extract value from regex hit.""" fracs = r'|'.join(r.UNI_FRAC) value = item.group(2) value = re.sub(ur'(?<=\d)(%s)10' % r.MULTIPLIERS, 'e', value) value = re.sub(fracs, callback, value, re.IGNORECASE) value = re.sub(' +', ' ', value) range_separator = re.findall(ur...
[ "def", "get_values", "(", "item", ")", ":", "fracs", "=", "r'|'", ".", "join", "(", "r", ".", "UNI_FRAC", ")", "value", "=", "item", ".", "group", "(", "2", ")", "value", "=", "re", ".", "sub", "(", "ur'(?<=\\d)(%s)10'", "%", "r", ".", "MULTIPLIERS...
Extract value from regex hit.
[ "Extract", "value", "from", "regex", "hit", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L107-L140
marcolagi/quantulum
quantulum/parser.py
build_unit_name
def build_unit_name(dimensions): """Build the name of the unit from its dimensions.""" name = '' for unit in dimensions: if unit['power'] < 0: name += 'per ' power = abs(unit['power']) if power == 1: name += unit['base'] elif power == 2: n...
python
def build_unit_name(dimensions): """Build the name of the unit from its dimensions.""" name = '' for unit in dimensions: if unit['power'] < 0: name += 'per ' power = abs(unit['power']) if power == 1: name += unit['base'] elif power == 2: n...
[ "def", "build_unit_name", "(", "dimensions", ")", ":", "name", "=", "''", "for", "unit", "in", "dimensions", ":", "if", "unit", "[", "'power'", "]", "<", "0", ":", "name", "+=", "'per '", "power", "=", "abs", "(", "unit", "[", "'power'", "]", ")", ...
Build the name of the unit from its dimensions.
[ "Build", "the", "name", "of", "the", "unit", "from", "its", "dimensions", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L144-L166
marcolagi/quantulum
quantulum/parser.py
get_unit_from_dimensions
def get_unit_from_dimensions(dimensions, text): """Reconcile a unit based on its dimensionality.""" key = l.get_key_from_dimensions(dimensions) try: unit = l.DERIVED_UNI[key] except KeyError: logging.debug(u'\tCould not find unit for: %s', key) unit = c.Unit(name=build_unit_name...
python
def get_unit_from_dimensions(dimensions, text): """Reconcile a unit based on its dimensionality.""" key = l.get_key_from_dimensions(dimensions) try: unit = l.DERIVED_UNI[key] except KeyError: logging.debug(u'\tCould not find unit for: %s', key) unit = c.Unit(name=build_unit_name...
[ "def", "get_unit_from_dimensions", "(", "dimensions", ",", "text", ")", ":", "key", "=", "l", ".", "get_key_from_dimensions", "(", "dimensions", ")", "try", ":", "unit", "=", "l", ".", "DERIVED_UNI", "[", "key", "]", "except", "KeyError", ":", "logging", "...
Reconcile a unit based on its dimensionality.
[ "Reconcile", "a", "unit", "based", "on", "its", "dimensionality", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L170-L182
marcolagi/quantulum
quantulum/parser.py
get_entity_from_dimensions
def get_entity_from_dimensions(dimensions, text): """ Infer the underlying entity of a unit (e.g. "volume" for "m^3"). Just based on the unit's dimensionality if the classifier is disabled. """ new_dimensions = [{'base': l.NAMES[i['base']].entity.name, 'power': i['power']} fo...
python
def get_entity_from_dimensions(dimensions, text): """ Infer the underlying entity of a unit (e.g. "volume" for "m^3"). Just based on the unit's dimensionality if the classifier is disabled. """ new_dimensions = [{'base': l.NAMES[i['base']].entity.name, 'power': i['power']} fo...
[ "def", "get_entity_from_dimensions", "(", "dimensions", ",", "text", ")", ":", "new_dimensions", "=", "[", "{", "'base'", ":", "l", ".", "NAMES", "[", "i", "[", "'base'", "]", "]", ".", "entity", ".", "name", ",", "'power'", ":", "i", "[", "'power'", ...
Infer the underlying entity of a unit (e.g. "volume" for "m^3"). Just based on the unit's dimensionality if the classifier is disabled.
[ "Infer", "the", "underlying", "entity", "of", "a", "unit", "(", "e", ".", "g", ".", "volume", "for", "m^3", ")", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L186-L207
marcolagi/quantulum
quantulum/parser.py
parse_unit
def parse_unit(item, group, slash): """Parse surface and power from unit text.""" surface = item.group(group).replace('.', '') power = re.findall(r'\-?[0-9%s]+' % r.SUPERSCRIPTS, surface) if power: power = [r.UNI_SUPER[i] if i in r.UNI_SUPER else i for i in power] power...
python
def parse_unit(item, group, slash): """Parse surface and power from unit text.""" surface = item.group(group).replace('.', '') power = re.findall(r'\-?[0-9%s]+' % r.SUPERSCRIPTS, surface) if power: power = [r.UNI_SUPER[i] if i in r.UNI_SUPER else i for i in power] power...
[ "def", "parse_unit", "(", "item", ",", "group", ",", "slash", ")", ":", "surface", "=", "item", ".", "group", "(", "group", ")", ".", "replace", "(", "'.'", ",", "''", ")", "power", "=", "re", ".", "findall", "(", "r'\\-?[0-9%s]+'", "%", "r", ".", ...
Parse surface and power from unit text.
[ "Parse", "surface", "and", "power", "from", "unit", "text", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L211-L234
marcolagi/quantulum
quantulum/parser.py
get_unit
def get_unit(item, text): """Extract unit from regex hit.""" group_units = [1, 4, 6, 8, 10] group_operators = [3, 5, 7, 9] item_units = [item.group(i) for i in group_units if item.group(i)] if len(item_units) == 0: unit = l.NAMES['dimensionless'] else: dimensions, slash = [], F...
python
def get_unit(item, text): """Extract unit from regex hit.""" group_units = [1, 4, 6, 8, 10] group_operators = [3, 5, 7, 9] item_units = [item.group(i) for i in group_units if item.group(i)] if len(item_units) == 0: unit = l.NAMES['dimensionless'] else: dimensions, slash = [], F...
[ "def", "get_unit", "(", "item", ",", "text", ")", ":", "group_units", "=", "[", "1", ",", "4", ",", "6", ",", "8", ",", "10", "]", "group_operators", "=", "[", "3", ",", "5", ",", "7", ",", "9", "]", "item_units", "=", "[", "item", ".", "grou...
Extract unit from regex hit.
[ "Extract", "unit", "from", "regex", "hit", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L238-L267
marcolagi/quantulum
quantulum/parser.py
get_surface
def get_surface(shifts, orig_text, item, text): """Extract surface from regex hit.""" span = item.span() logging.debug(u'\tInitial span: %s ("%s")', span, text[span[0]:span[1]]) real_span = (span[0] - shifts[span[0]], span[1] - shifts[span[1] - 1]) surface = orig_text[real_span[0]:real_span[1]] ...
python
def get_surface(shifts, orig_text, item, text): """Extract surface from regex hit.""" span = item.span() logging.debug(u'\tInitial span: %s ("%s")', span, text[span[0]:span[1]]) real_span = (span[0] - shifts[span[0]], span[1] - shifts[span[1] - 1]) surface = orig_text[real_span[0]:real_span[1]] ...
[ "def", "get_surface", "(", "shifts", ",", "orig_text", ",", "item", ",", "text", ")", ":", "span", "=", "item", ".", "span", "(", ")", "logging", ".", "debug", "(", "u'\\tInitial span: %s (\"%s\")'", ",", "span", ",", "text", "[", "span", "[", "0", "]"...
Extract surface from regex hit.
[ "Extract", "surface", "from", "regex", "hit", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L271-L289
marcolagi/quantulum
quantulum/parser.py
is_quote_artifact
def is_quote_artifact(orig_text, span): """Distinguish between quotes and units.""" res = False cursor = re.finditer(r'("|\')[^ .,:;?!()*+-].*?("|\')', orig_text) for item in cursor: if item.span()[1] == span[1]: res = True return res
python
def is_quote_artifact(orig_text, span): """Distinguish between quotes and units.""" res = False cursor = re.finditer(r'("|\')[^ .,:;?!()*+-].*?("|\')', orig_text) for item in cursor: if item.span()[1] == span[1]: res = True return res
[ "def", "is_quote_artifact", "(", "orig_text", ",", "span", ")", ":", "res", "=", "False", "cursor", "=", "re", ".", "finditer", "(", "r'(\"|\\')[^ .,:;?!()*+-].*?(\"|\\')'", ",", "orig_text", ")", "for", "item", "in", "cursor", ":", "if", "item", ".", "span"...
Distinguish between quotes and units.
[ "Distinguish", "between", "quotes", "and", "units", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L293-L302
marcolagi/quantulum
quantulum/parser.py
build_quantity
def build_quantity(orig_text, text, item, values, unit, surface, span, uncert): """Build a Quantity object out of extracted information.""" # Discard irrelevant txt2float extractions, cardinal numbers, codes etc. if surface.lower() in ['a', 'an', 'one'] or \ re.search(r'1st|2nd|3rd|[04-9]th', su...
python
def build_quantity(orig_text, text, item, values, unit, surface, span, uncert): """Build a Quantity object out of extracted information.""" # Discard irrelevant txt2float extractions, cardinal numbers, codes etc. if surface.lower() in ['a', 'an', 'one'] or \ re.search(r'1st|2nd|3rd|[04-9]th', su...
[ "def", "build_quantity", "(", "orig_text", ",", "text", ",", "item", ",", "values", ",", "unit", ",", "surface", ",", "span", ",", "uncert", ")", ":", "# Discard irrelevant txt2float extractions, cardinal numbers, codes etc.", "if", "surface", ".", "lower", "(", "...
Build a Quantity object out of extracted information.
[ "Build", "a", "Quantity", "object", "out", "of", "extracted", "information", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L306-L384
marcolagi/quantulum
quantulum/parser.py
clean_text
def clean_text(text): """Clean text before parsing.""" # Replace a few nasty unicode characters with their ASCII equivalent maps = {u'×': u'x', u'–': u'-', u'−': '-'} for element in maps: text = text.replace(element, maps[element]) # Replace genitives text = re.sub(r'(?<=\w)\'s\b|(?<=\w...
python
def clean_text(text): """Clean text before parsing.""" # Replace a few nasty unicode characters with their ASCII equivalent maps = {u'×': u'x', u'–': u'-', u'−': '-'} for element in maps: text = text.replace(element, maps[element]) # Replace genitives text = re.sub(r'(?<=\w)\'s\b|(?<=\w...
[ "def", "clean_text", "(", "text", ")", ":", "# Replace a few nasty unicode characters with their ASCII equivalent", "maps", "=", "{", "u'×':", " ", "'x',", " ", "'–': u", "'", "', u", "'", "': '-'", "}", "", "", "for", "element", "in", "maps", ":", "text", "="...
Clean text before parsing.
[ "Clean", "text", "before", "parsing", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L388-L400
marcolagi/quantulum
quantulum/parser.py
parse
def parse(text, verbose=False): """Extract all quantities from unstructured text.""" log_format = ('%(asctime)s --- %(message)s') logging.basicConfig(format=log_format) root = logging.getLogger() if verbose: level = root.level root.setLevel(logging.DEBUG) logging.debug(u'Ver...
python
def parse(text, verbose=False): """Extract all quantities from unstructured text.""" log_format = ('%(asctime)s --- %(message)s') logging.basicConfig(format=log_format) root = logging.getLogger() if verbose: level = root.level root.setLevel(logging.DEBUG) logging.debug(u'Ver...
[ "def", "parse", "(", "text", ",", "verbose", "=", "False", ")", ":", "log_format", "=", "(", "'%(asctime)s --- %(message)s'", ")", "logging", ".", "basicConfig", "(", "format", "=", "log_format", ")", "root", "=", "logging", ".", "getLogger", "(", ")", "if...
Extract all quantities from unstructured text.
[ "Extract", "all", "quantities", "from", "unstructured", "text", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L404-L448
marcolagi/quantulum
quantulum/parser.py
inline_parse
def inline_parse(text, verbose=False): """Extract all quantities from unstructured text.""" if isinstance(text, str): text = text.decode('utf-8') parsed = parse(text, verbose=verbose) shift = 0 for quantity in parsed: index = quantity.span[1] + shift to_add = u' {' + unicod...
python
def inline_parse(text, verbose=False): """Extract all quantities from unstructured text.""" if isinstance(text, str): text = text.decode('utf-8') parsed = parse(text, verbose=verbose) shift = 0 for quantity in parsed: index = quantity.span[1] + shift to_add = u' {' + unicod...
[ "def", "inline_parse", "(", "text", ",", "verbose", "=", "False", ")", ":", "if", "isinstance", "(", "text", ",", "str", ")", ":", "text", "=", "text", ".", "decode", "(", "'utf-8'", ")", "parsed", "=", "parse", "(", "text", ",", "verbose", "=", "v...
Extract all quantities from unstructured text.
[ "Extract", "all", "quantities", "from", "unstructured", "text", "." ]
train
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L452-L466
hharnisc/python-meteor
MeteorClient.py
MeteorClient._reconnected
def _reconnected(self): """Reconnect Currently we get a new session every time so we have to clear all the data an resubscribe""" if self._login_data or self._login_token: def reconnect_login_callback(error, result): if error: if self._l...
python
def _reconnected(self): """Reconnect Currently we get a new session every time so we have to clear all the data an resubscribe""" if self._login_data or self._login_token: def reconnect_login_callback(error, result): if error: if self._l...
[ "def", "_reconnected", "(", "self", ")", ":", "if", "self", ".", "_login_data", "or", "self", ".", "_login_token", ":", "def", "reconnect_login_callback", "(", "error", ",", "result", ")", ":", "if", "error", ":", "if", "self", ".", "_login_token", ":", ...
Reconnect Currently we get a new session every time so we have to clear all the data an resubscribe
[ "Reconnect" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L61-L90
hharnisc/python-meteor
MeteorClient.py
MeteorClient.login
def login(self, user, password, token=None, callback=None): """Login with a username and password Arguments: user - username or email address password - the password for the account Keyword Arguments: token - meteor resume token callback - callback function cont...
python
def login(self, user, password, token=None, callback=None): """Login with a username and password Arguments: user - username or email address password - the password for the account Keyword Arguments: token - meteor resume token callback - callback function cont...
[ "def", "login", "(", "self", ",", "user", ",", "password", ",", "token", "=", "None", ",", "callback", "=", "None", ")", ":", "# TODO: keep the tokenExpires around so we know the next time", "# we need to authenticate", "# hash the password", "hashed", "=", "hashl...
Login with a username and password Arguments: user - username or email address password - the password for the account Keyword Arguments: token - meteor resume token callback - callback function containing error as first argument and login data
[ "Login", "with", "a", "username", "and", "password" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L103-L138
hharnisc/python-meteor
MeteorClient.py
MeteorClient.logout
def logout(self, callback=None): """Logout a user Keyword Arguments: callback - callback function called when the user has been logged out""" self.ddp_client.call('logout', [], callback=callback) self.emit('logged_out')
python
def logout(self, callback=None): """Logout a user Keyword Arguments: callback - callback function called when the user has been logged out""" self.ddp_client.call('logout', [], callback=callback) self.emit('logged_out')
[ "def", "logout", "(", "self", ",", "callback", "=", "None", ")", ":", "self", ".", "ddp_client", ".", "call", "(", "'logout'", ",", "[", "]", ",", "callback", "=", "callback", ")", "self", ".", "emit", "(", "'logged_out'", ")" ]
Logout a user Keyword Arguments: callback - callback function called when the user has been logged out
[ "Logout", "a", "user" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L165-L171
hharnisc/python-meteor
MeteorClient.py
MeteorClient.call
def call(self, method, params, callback=None): """Call a remote method Arguments: method - remote method name params - remote method parameters Keyword Arguments: callback - callback function containing return data""" self._wait_for_connect() self.ddp_cl...
python
def call(self, method, params, callback=None): """Call a remote method Arguments: method - remote method name params - remote method parameters Keyword Arguments: callback - callback function containing return data""" self._wait_for_connect() self.ddp_cl...
[ "def", "call", "(", "self", ",", "method", ",", "params", ",", "callback", "=", "None", ")", ":", "self", ".", "_wait_for_connect", "(", ")", "self", ".", "ddp_client", ".", "call", "(", "method", ",", "params", ",", "callback", "=", "callback", ")" ]
Call a remote method Arguments: method - remote method name params - remote method parameters Keyword Arguments: callback - callback function containing return data
[ "Call", "a", "remote", "method" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L177-L187
hharnisc/python-meteor
MeteorClient.py
MeteorClient.subscribe
def subscribe(self, name, params=[], callback=None): """Subscribe to a collection Arguments: name - the name of the publication params - the subscription parameters Keyword Arguments: callback - a function callback that returns an error (if exists)""" self._wait_...
python
def subscribe(self, name, params=[], callback=None): """Subscribe to a collection Arguments: name - the name of the publication params - the subscription parameters Keyword Arguments: callback - a function callback that returns an error (if exists)""" self._wait_...
[ "def", "subscribe", "(", "self", ",", "name", ",", "params", "=", "[", "]", ",", "callback", "=", "None", ")", ":", "self", ".", "_wait_for_connect", "(", ")", "def", "subscribed", "(", "error", ",", "sub_id", ")", ":", "if", "error", ":", "self", ...
Subscribe to a collection Arguments: name - the name of the publication params - the subscription parameters Keyword Arguments: callback - a function callback that returns an error (if exists)
[ "Subscribe", "to", "a", "collection", "Arguments", ":", "name", "-", "the", "name", "of", "the", "publication", "params", "-", "the", "subscription", "parameters" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L193-L220
hharnisc/python-meteor
MeteorClient.py
MeteorClient.unsubscribe
def unsubscribe(self, name): """Unsubscribe from a collection Arguments: name - the name of the publication""" self._wait_for_connect() if name not in self.subscriptions: raise MeteorClientException('No subscription for {}'.format(name)) self.ddp_client.unsub...
python
def unsubscribe(self, name): """Unsubscribe from a collection Arguments: name - the name of the publication""" self._wait_for_connect() if name not in self.subscriptions: raise MeteorClientException('No subscription for {}'.format(name)) self.ddp_client.unsub...
[ "def", "unsubscribe", "(", "self", ",", "name", ")", ":", "self", ".", "_wait_for_connect", "(", ")", "if", "name", "not", "in", "self", ".", "subscriptions", ":", "raise", "MeteorClientException", "(", "'No subscription for {}'", ".", "format", "(", "name", ...
Unsubscribe from a collection Arguments: name - the name of the publication
[ "Unsubscribe", "from", "a", "collection" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L222-L232
hharnisc/python-meteor
MeteorClient.py
MeteorClient.find
def find(self, collection, selector={}): """Find data in a collection Arguments: collection - collection to search Keyword Arguments: selector - the query (default returns all items in a collection)""" results = [] for _id, doc in self.collection_data.data.get(c...
python
def find(self, collection, selector={}): """Find data in a collection Arguments: collection - collection to search Keyword Arguments: selector - the query (default returns all items in a collection)""" results = [] for _id, doc in self.collection_data.data.get(c...
[ "def", "find", "(", "self", ",", "collection", ",", "selector", "=", "{", "}", ")", ":", "results", "=", "[", "]", "for", "_id", ",", "doc", "in", "self", ".", "collection_data", ".", "data", ".", "get", "(", "collection", ",", "{", "}", ")", "."...
Find data in a collection Arguments: collection - collection to search Keyword Arguments: selector - the query (default returns all items in a collection)
[ "Find", "data", "in", "a", "collection" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L238-L254
hharnisc/python-meteor
MeteorClient.py
MeteorClient.find_one
def find_one(self, collection, selector={}): """Return one item from a collection Arguments: collection - collection to search Keyword Arguments: selector - the query (default returns first item found)""" for _id, doc in self.collection_data.data.get(collection, {}).ite...
python
def find_one(self, collection, selector={}): """Return one item from a collection Arguments: collection - collection to search Keyword Arguments: selector - the query (default returns first item found)""" for _id, doc in self.collection_data.data.get(collection, {}).ite...
[ "def", "find_one", "(", "self", ",", "collection", ",", "selector", "=", "{", "}", ")", ":", "for", "_id", ",", "doc", "in", "self", ".", "collection_data", ".", "data", ".", "get", "(", "collection", ",", "{", "}", ")", ".", "items", "(", ")", "...
Return one item from a collection Arguments: collection - collection to search Keyword Arguments: selector - the query (default returns first item found)
[ "Return", "one", "item", "from", "a", "collection" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L256-L271
hharnisc/python-meteor
MeteorClient.py
MeteorClient.insert
def insert(self, collection, doc, callback=None): """Insert an item into a collection Arguments: collection - the collection to be modified doc - The document to insert. May not yet have an _id attribute, in which case Meteor will generate one for you. Keyword Arguments...
python
def insert(self, collection, doc, callback=None): """Insert an item into a collection Arguments: collection - the collection to be modified doc - The document to insert. May not yet have an _id attribute, in which case Meteor will generate one for you. Keyword Arguments...
[ "def", "insert", "(", "self", ",", "collection", ",", "doc", ",", "callback", "=", "None", ")", ":", "self", ".", "call", "(", "\"/\"", "+", "collection", "+", "\"/insert\"", ",", "[", "doc", "]", ",", "callback", "=", "callback", ")" ]
Insert an item into a collection Arguments: collection - the collection to be modified doc - The document to insert. May not yet have an _id attribute, in which case Meteor will generate one for you. Keyword Arguments: callback - Optional. If present, called with an err...
[ "Insert", "an", "item", "into", "a", "collection" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L273-L284
hharnisc/python-meteor
MeteorClient.py
MeteorClient.update
def update(self, collection, selector, modifier, callback=None): """Insert an item into a collection Arguments: collection - the collection to be modified selector - specifies which documents to modify modifier - Specifies how to modify the documents Keyword Arguments: ...
python
def update(self, collection, selector, modifier, callback=None): """Insert an item into a collection Arguments: collection - the collection to be modified selector - specifies which documents to modify modifier - Specifies how to modify the documents Keyword Arguments: ...
[ "def", "update", "(", "self", ",", "collection", ",", "selector", ",", "modifier", ",", "callback", "=", "None", ")", ":", "self", ".", "call", "(", "\"/\"", "+", "collection", "+", "\"/update\"", ",", "[", "selector", ",", "modifier", "]", ",", "callb...
Insert an item into a collection Arguments: collection - the collection to be modified selector - specifies which documents to modify modifier - Specifies how to modify the documents Keyword Arguments: callback - Optional. If present, called with an error object as the ...
[ "Insert", "an", "item", "into", "a", "collection" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L286-L297
hharnisc/python-meteor
MeteorClient.py
MeteorClient.remove
def remove(self, collection, selector, callback=None): """Remove an item from a collection Arguments: collection - the collection to be modified selector - Specifies which documents to remove Keyword Arguments: callback - Optional. If present, called with an error objec...
python
def remove(self, collection, selector, callback=None): """Remove an item from a collection Arguments: collection - the collection to be modified selector - Specifies which documents to remove Keyword Arguments: callback - Optional. If present, called with an error objec...
[ "def", "remove", "(", "self", ",", "collection", ",", "selector", ",", "callback", "=", "None", ")", ":", "self", ".", "call", "(", "\"/\"", "+", "collection", "+", "\"/remove\"", ",", "[", "selector", "]", ",", "callback", "=", "callback", ")" ]
Remove an item from a collection Arguments: collection - the collection to be modified selector - Specifies which documents to remove Keyword Arguments: callback - Optional. If present, called with an error object as its argument.
[ "Remove", "an", "item", "from", "a", "collection" ]
train
https://github.com/hharnisc/python-meteor/blob/b3ad728660785d5506bba6948436d061ee8ca5bc/MeteorClient.py#L299-L308
pikhovkin/simple-websocket-server
simple_websocket_server/__init__.py
WebSocket.close
def close(self, status=1000, reason=u''): """ Send Close frame to the client. The underlying socket is only closed when the client acknowledges the Close frame. status is the closing identifier. reason is the reason for the close. """ try: ...
python
def close(self, status=1000, reason=u''): """ Send Close frame to the client. The underlying socket is only closed when the client acknowledges the Close frame. status is the closing identifier. reason is the reason for the close. """ try: ...
[ "def", "close", "(", "self", ",", "status", "=", "1000", ",", "reason", "=", "u''", ")", ":", "try", ":", "if", "self", ".", "closed", "is", "False", ":", "close_msg", "=", "bytearray", "(", ")", "close_msg", ".", "extend", "(", "struct", ".", "pac...
Send Close frame to the client. The underlying socket is only closed when the client acknowledges the Close frame. status is the closing identifier. reason is the reason for the close.
[ "Send", "Close", "frame", "to", "the", "client", ".", "The", "underlying", "socket", "is", "only", "closed", "when", "the", "client", "acknowledges", "the", "Close", "frame", "." ]
train
https://github.com/pikhovkin/simple-websocket-server/blob/0f77db8d43f089c8b6a602df8b013b54d73cc367/simple_websocket_server/__init__.py#L277-L296
pikhovkin/simple-websocket-server
simple_websocket_server/__init__.py
WebSocket.send_fragment_start
def send_fragment_start(self, data): """ Send the start of a data fragment stream to a websocket client. Subsequent data should be sent using sendFragment(). A fragment stream is completed when sendFragmentEnd() is called. If data is a unicode object then the fra...
python
def send_fragment_start(self, data): """ Send the start of a data fragment stream to a websocket client. Subsequent data should be sent using sendFragment(). A fragment stream is completed when sendFragmentEnd() is called. If data is a unicode object then the fra...
[ "def", "send_fragment_start", "(", "self", ",", "data", ")", ":", "opcode", "=", "BINARY", "if", "_check_unicode", "(", "data", ")", ":", "opcode", "=", "TEXT", "self", ".", "_send_message", "(", "True", ",", "opcode", ",", "data", ")" ]
Send the start of a data fragment stream to a websocket client. Subsequent data should be sent using sendFragment(). A fragment stream is completed when sendFragmentEnd() is called. If data is a unicode object then the frame is sent as Text. If the data is a bytearray ob...
[ "Send", "the", "start", "of", "a", "data", "fragment", "stream", "to", "a", "websocket", "client", ".", "Subsequent", "data", "should", "be", "sent", "using", "sendFragment", "()", ".", "A", "fragment", "stream", "is", "completed", "when", "sendFragmentEnd", ...
train
https://github.com/pikhovkin/simple-websocket-server/blob/0f77db8d43f089c8b6a602df8b013b54d73cc367/simple_websocket_server/__init__.py#L324-L337
pikhovkin/simple-websocket-server
simple_websocket_server/__init__.py
WebSocket.send_message
def send_message(self, data): """ Send websocket data frame to the client. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. """ opcode = BINARY if _check_unicode(data): ...
python
def send_message(self, data): """ Send websocket data frame to the client. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. """ opcode = BINARY if _check_unicode(data): ...
[ "def", "send_message", "(", "self", ",", "data", ")", ":", "opcode", "=", "BINARY", "if", "_check_unicode", "(", "data", ")", ":", "opcode", "=", "TEXT", "self", ".", "_send_message", "(", "False", ",", "opcode", ",", "data", ")" ]
Send websocket data frame to the client. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary.
[ "Send", "websocket", "data", "frame", "to", "the", "client", "." ]
train
https://github.com/pikhovkin/simple-websocket-server/blob/0f77db8d43f089c8b6a602df8b013b54d73cc367/simple_websocket_server/__init__.py#L357-L368
dougn/python-plantuml
plantuml.py
deflate_and_encode
def deflate_and_encode(plantuml_text): """zlib compress the plantuml text and encode it for the plantuml server. """ zlibbed_str = zlib.compress(plantuml_text.encode('utf-8')) compressed_string = zlibbed_str[2:-4] return encode(compressed_string.decode('latin-1'))
python
def deflate_and_encode(plantuml_text): """zlib compress the plantuml text and encode it for the plantuml server. """ zlibbed_str = zlib.compress(plantuml_text.encode('utf-8')) compressed_string = zlibbed_str[2:-4] return encode(compressed_string.decode('latin-1'))
[ "def", "deflate_and_encode", "(", "plantuml_text", ")", ":", "zlibbed_str", "=", "zlib", ".", "compress", "(", "plantuml_text", ".", "encode", "(", "'utf-8'", ")", ")", "compressed_string", "=", "zlibbed_str", "[", "2", ":", "-", "4", "]", "return", "encode"...
zlib compress the plantuml text and encode it for the plantuml server.
[ "zlib", "compress", "the", "plantuml", "text", "and", "encode", "it", "for", "the", "plantuml", "server", "." ]
train
https://github.com/dougn/python-plantuml/blob/f81c51ee73f3ebad9040a2911af0519d1a835811/plantuml.py#L43-L48
dougn/python-plantuml
plantuml.py
encode
def encode(data): """encode the plantuml data which may be compresses in the proper encoding for the plantuml server """ res = "" for i in range(0,len(data), 3): if (i+2==len(data)): res += _encode3bytes(ord(data[i]), ord(data[i+1]), 0) elif (i+1==len(data)): ...
python
def encode(data): """encode the plantuml data which may be compresses in the proper encoding for the plantuml server """ res = "" for i in range(0,len(data), 3): if (i+2==len(data)): res += _encode3bytes(ord(data[i]), ord(data[i+1]), 0) elif (i+1==len(data)): ...
[ "def", "encode", "(", "data", ")", ":", "res", "=", "\"\"", "for", "i", "in", "range", "(", "0", ",", "len", "(", "data", ")", ",", "3", ")", ":", "if", "(", "i", "+", "2", "==", "len", "(", "data", ")", ")", ":", "res", "+=", "_encode3byte...
encode the plantuml data which may be compresses in the proper encoding for the plantuml server
[ "encode", "the", "plantuml", "data", "which", "may", "be", "compresses", "in", "the", "proper", "encoding", "for", "the", "plantuml", "server" ]
train
https://github.com/dougn/python-plantuml/blob/f81c51ee73f3ebad9040a2911af0519d1a835811/plantuml.py#L50-L62
dougn/python-plantuml
plantuml.py
PlantUML.processes
def processes(self, plantuml_text): """Processes the plantuml text into the raw PNG image data. :param str plantuml_text: The plantuml markup to render :returns: the raw image data """ url = self.get_url(plantuml_text) try: response, content = self.ht...
python
def processes(self, plantuml_text): """Processes the plantuml text into the raw PNG image data. :param str plantuml_text: The plantuml markup to render :returns: the raw image data """ url = self.get_url(plantuml_text) try: response, content = self.ht...
[ "def", "processes", "(", "self", ",", "plantuml_text", ")", ":", "url", "=", "self", ".", "get_url", "(", "plantuml_text", ")", "try", ":", "response", ",", "content", "=", "self", ".", "http", ".", "request", "(", "url", ",", "*", "*", "self", ".", ...
Processes the plantuml text into the raw PNG image data. :param str plantuml_text: The plantuml markup to render :returns: the raw image data
[ "Processes", "the", "plantuml", "text", "into", "the", "raw", "PNG", "image", "data", ".", ":", "param", "str", "plantuml_text", ":", "The", "plantuml", "markup", "to", "render", ":", "returns", ":", "the", "raw", "image", "data" ]
train
https://github.com/dougn/python-plantuml/blob/f81c51ee73f3ebad9040a2911af0519d1a835811/plantuml.py#L171-L184
dougn/python-plantuml
plantuml.py
PlantUML.processes_file
def processes_file(self, filename, outfile=None, errorfile=None): """Take a filename of a file containing plantuml text and processes it into a .png image. :param str filename: Text file containing plantuml markup :param str outfile: Filename to write the output image to. If not...
python
def processes_file(self, filename, outfile=None, errorfile=None): """Take a filename of a file containing plantuml text and processes it into a .png image. :param str filename: Text file containing plantuml markup :param str outfile: Filename to write the output image to. If not...
[ "def", "processes_file", "(", "self", ",", "filename", ",", "outfile", "=", "None", ",", "errorfile", "=", "None", ")", ":", "if", "outfile", "is", "None", ":", "outfile", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", ...
Take a filename of a file containing plantuml text and processes it into a .png image. :param str filename: Text file containing plantuml markup :param str outfile: Filename to write the output image to. If not supplied, then it will be the input filename with the ...
[ "Take", "a", "filename", "of", "a", "file", "containing", "plantuml", "text", "and", "processes", "it", "into", "a", ".", "png", "image", ".", ":", "param", "str", "filename", ":", "Text", "file", "containing", "plantuml", "markup", ":", "param", "str", ...
train
https://github.com/dougn/python-plantuml/blob/f81c51ee73f3ebad9040a2911af0519d1a835811/plantuml.py#L186-L216
Jellyfish-AI/jf_agent
jf_agent/jira_download.py
download_issuetypes
def download_issuetypes(jira_connection, project_ids): ''' For Jira next-gen projects, issue types can be scoped to projects. For issue types that are scoped to projects, only extract the ones in the extracted projects. ''' print('downloading jira issue types... ', end='', flush=True) result...
python
def download_issuetypes(jira_connection, project_ids): ''' For Jira next-gen projects, issue types can be scoped to projects. For issue types that are scoped to projects, only extract the ones in the extracted projects. ''' print('downloading jira issue types... ', end='', flush=True) result...
[ "def", "download_issuetypes", "(", "jira_connection", ",", "project_ids", ")", ":", "print", "(", "'downloading jira issue types... '", ",", "end", "=", "''", ",", "flush", "=", "True", ")", "result", "=", "[", "]", "for", "it", "in", "jira_connection", ".", ...
For Jira next-gen projects, issue types can be scoped to projects. For issue types that are scoped to projects, only extract the ones in the extracted projects.
[ "For", "Jira", "next", "-", "gen", "projects", "issue", "types", "can", "be", "scoped", "to", "projects", ".", "For", "issue", "types", "that", "are", "scoped", "to", "projects", "only", "extract", "the", "ones", "in", "the", "extracted", "projects", "." ]
train
https://github.com/Jellyfish-AI/jf_agent/blob/31203a294ad677c8ef9543b45509395537eb1f22/jf_agent/jira_download.py#L58-L73
hynek/pem
src/pem/twisted.py
certificateOptionsFromPEMs
def certificateOptionsFromPEMs(pemObjects, **kw): # type: (List[AbstractPEMObject], **Any) -> ssl.CerticateOptions """ Load a CertificateOptions from the given collection of PEM objects (already-loaded private keys and certificates). In those PEM objects, identify one private key and its correspond...
python
def certificateOptionsFromPEMs(pemObjects, **kw): # type: (List[AbstractPEMObject], **Any) -> ssl.CerticateOptions """ Load a CertificateOptions from the given collection of PEM objects (already-loaded private keys and certificates). In those PEM objects, identify one private key and its correspond...
[ "def", "certificateOptionsFromPEMs", "(", "pemObjects", ",", "*", "*", "kw", ")", ":", "# type: (List[AbstractPEMObject], **Any) -> ssl.CerticateOptions", "keys", "=", "[", "key", "for", "key", "in", "pemObjects", "if", "isinstance", "(", "key", ",", "Key", ")", "...
Load a CertificateOptions from the given collection of PEM objects (already-loaded private keys and certificates). In those PEM objects, identify one private key and its corresponding certificate to use as the primary certificate. Then use the rest of the certificates found as chain certificates. Rai...
[ "Load", "a", "CertificateOptions", "from", "the", "given", "collection", "of", "PEM", "objects", "(", "already", "-", "loaded", "private", "keys", "and", "certificates", ")", "." ]
train
https://github.com/hynek/pem/blob/5a98b0b0012df7211955a72740a9efca02150b04/src/pem/twisted.py#L22-L93
hynek/pem
src/pem/twisted.py
certificateOptionsFromFiles
def certificateOptionsFromFiles(*pemFiles, **kw): # type: (*str, **Any) -> ssl.CertificateOptions """ Read all files named by *pemFiles*, and parse them using :func:`certificateOptionsFromPEMs`. """ pems = [] # type: List[AbstractPEMObject] for pemFile in pemFiles: pems += parse_fil...
python
def certificateOptionsFromFiles(*pemFiles, **kw): # type: (*str, **Any) -> ssl.CertificateOptions """ Read all files named by *pemFiles*, and parse them using :func:`certificateOptionsFromPEMs`. """ pems = [] # type: List[AbstractPEMObject] for pemFile in pemFiles: pems += parse_fil...
[ "def", "certificateOptionsFromFiles", "(", "*", "pemFiles", ",", "*", "*", "kw", ")", ":", "# type: (*str, **Any) -> ssl.CertificateOptions", "pems", "=", "[", "]", "# type: List[AbstractPEMObject]", "for", "pemFile", "in", "pemFiles", ":", "pems", "+=", "parse_file",...
Read all files named by *pemFiles*, and parse them using :func:`certificateOptionsFromPEMs`.
[ "Read", "all", "files", "named", "by", "*", "pemFiles", "*", "and", "parse", "them", "using", ":", "func", ":", "certificateOptionsFromPEMs", "." ]
train
https://github.com/hynek/pem/blob/5a98b0b0012df7211955a72740a9efca02150b04/src/pem/twisted.py#L96-L106
hynek/pem
src/pem/_core.py
parse
def parse(pem_str): # type: (bytes) -> List[AbstractPEMObject] """ Extract PEM objects from *pem_str*. :param pem_str: String to parse. :type pem_str: bytes :return: list of :ref:`pem-objects` """ return [ _PEM_TO_CLASS[match.group(1)](match.group(0)) for match in _PEM_R...
python
def parse(pem_str): # type: (bytes) -> List[AbstractPEMObject] """ Extract PEM objects from *pem_str*. :param pem_str: String to parse. :type pem_str: bytes :return: list of :ref:`pem-objects` """ return [ _PEM_TO_CLASS[match.group(1)](match.group(0)) for match in _PEM_R...
[ "def", "parse", "(", "pem_str", ")", ":", "# type: (bytes) -> List[AbstractPEMObject]", "return", "[", "_PEM_TO_CLASS", "[", "match", ".", "group", "(", "1", ")", "]", "(", "match", ".", "group", "(", "0", ")", ")", "for", "match", "in", "_PEM_RE", ".", ...
Extract PEM objects from *pem_str*. :param pem_str: String to parse. :type pem_str: bytes :return: list of :ref:`pem-objects`
[ "Extract", "PEM", "objects", "from", "*", "pem_str", "*", "." ]
train
https://github.com/hynek/pem/blob/5a98b0b0012df7211955a72740a9efca02150b04/src/pem/_core.py#L188-L200
hynek/pem
src/pem/_core.py
AbstractPEMObject.sha1_hexdigest
def sha1_hexdigest(self): # type: () -> str """ A SHA-1 digest of the whole object for easy differentiation. .. versionadded:: 18.1.0 """ if self._sha1_hexdigest is None: self._sha1_hexdigest = hashlib.sha1(self._pem_bytes).hexdigest() return self._s...
python
def sha1_hexdigest(self): # type: () -> str """ A SHA-1 digest of the whole object for easy differentiation. .. versionadded:: 18.1.0 """ if self._sha1_hexdigest is None: self._sha1_hexdigest = hashlib.sha1(self._pem_bytes).hexdigest() return self._s...
[ "def", "sha1_hexdigest", "(", "self", ")", ":", "# type: () -> str", "if", "self", ".", "_sha1_hexdigest", "is", "None", ":", "self", ".", "_sha1_hexdigest", "=", "hashlib", ".", "sha1", "(", "self", ".", "_pem_bytes", ")", ".", "hexdigest", "(", ")", "ret...
A SHA-1 digest of the whole object for easy differentiation. .. versionadded:: 18.1.0
[ "A", "SHA", "-", "1", "digest", "of", "the", "whole", "object", "for", "easy", "differentiation", "." ]
train
https://github.com/hynek/pem/blob/5a98b0b0012df7211955a72740a9efca02150b04/src/pem/_core.py#L50-L60
rytilahti/python-songpal
songpal/containers.py
make
def make(cls, **kwargs): """Create a container. Reports extra keys as well as missing ones. Thanks to habnabit for the idea! """ cls_attrs = {f.name: f for f in attr.fields(cls)} unknown = {k: v for k, v in kwargs.items() if k not in cls_attrs} if len(unknown) > 0: _LOGGER.warning(...
python
def make(cls, **kwargs): """Create a container. Reports extra keys as well as missing ones. Thanks to habnabit for the idea! """ cls_attrs = {f.name: f for f in attr.fields(cls)} unknown = {k: v for k, v in kwargs.items() if k not in cls_attrs} if len(unknown) > 0: _LOGGER.warning(...
[ "def", "make", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "cls_attrs", "=", "{", "f", ".", "name", ":", "f", "for", "f", "in", "attr", ".", "fields", "(", "cls", ")", "}", "unknown", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", ...
Create a container. Reports extra keys as well as missing ones. Thanks to habnabit for the idea!
[ "Create", "a", "container", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/containers.py#L11-L46
rytilahti/python-songpal
songpal/device.py
Device.create_post_request
async def create_post_request(self, method: str, params: Dict = None): """Call the given method over POST. :param method: Name of the method :param params: dict of parameters :return: JSON object """ if params is None: params = {} headers = {"Content-...
python
async def create_post_request(self, method: str, params: Dict = None): """Call the given method over POST. :param method: Name of the method :param params: dict of parameters :return: JSON object """ if params is None: params = {} headers = {"Content-...
[ "async", "def", "create_post_request", "(", "self", ",", "method", ":", "str", ",", "params", ":", "Dict", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/jso...
Call the given method over POST. :param method: Name of the method :param params: dict of parameters :return: JSON object
[ "Call", "the", "given", "method", "over", "POST", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L74-L115
rytilahti/python-songpal
songpal/device.py
Device.get_supported_methods
async def get_supported_methods(self): """Get information about supported methods. Calling this as the first thing before doing anything else is necessary to fill the available services table. """ response = await self.request_supported_methods() if "result" in response...
python
async def get_supported_methods(self): """Get information about supported methods. Calling this as the first thing before doing anything else is necessary to fill the available services table. """ response = await self.request_supported_methods() if "result" in response...
[ "async", "def", "get_supported_methods", "(", "self", ")", ":", "response", "=", "await", "self", ".", "request_supported_methods", "(", ")", "if", "\"result\"", "in", "response", ":", "services", "=", "response", "[", "\"result\"", "]", "[", "0", "]", "_LOG...
Get information about supported methods. Calling this as the first thing before doing anything else is necessary to fill the available services table.
[ "Get", "information", "about", "supported", "methods", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L121-L151
rytilahti/python-songpal
songpal/device.py
Device.set_power
async def set_power(self, value: bool): """Toggle the device on and off.""" if value: status = "active" else: status = "off" # TODO WoL works when quickboot is not enabled return await self.services["system"]["setPowerStatus"](status=status)
python
async def set_power(self, value: bool): """Toggle the device on and off.""" if value: status = "active" else: status = "off" # TODO WoL works when quickboot is not enabled return await self.services["system"]["setPowerStatus"](status=status)
[ "async", "def", "set_power", "(", "self", ",", "value", ":", "bool", ")", ":", "if", "value", ":", "status", "=", "\"active\"", "else", ":", "status", "=", "\"off\"", "# TODO WoL works when quickboot is not enabled", "return", "await", "self", ".", "services", ...
Toggle the device on and off.
[ "Toggle", "the", "device", "on", "and", "off", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L158-L165
rytilahti/python-songpal
songpal/device.py
Device.get_play_info
async def get_play_info(self) -> PlayInfo: """Return of the device.""" info = await self.services["avContent"]["getPlayingContentInfo"]({}) return PlayInfo.make(**info.pop())
python
async def get_play_info(self) -> PlayInfo: """Return of the device.""" info = await self.services["avContent"]["getPlayingContentInfo"]({}) return PlayInfo.make(**info.pop())
[ "async", "def", "get_play_info", "(", "self", ")", "->", "PlayInfo", ":", "info", "=", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"getPlayingContentInfo\"", "]", "(", "{", "}", ")", "return", "PlayInfo", ".", "make", "(", "*", "*...
Return of the device.
[ "Return", "of", "the", "device", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L167-L170
rytilahti/python-songpal
songpal/device.py
Device.get_power_settings
async def get_power_settings(self) -> List[Setting]: """Get power settings.""" return [ Setting.make(**x) for x in await self.services["system"]["getPowerSettings"]({}) ]
python
async def get_power_settings(self) -> List[Setting]: """Get power settings.""" return [ Setting.make(**x) for x in await self.services["system"]["getPowerSettings"]({}) ]
[ "async", "def", "get_power_settings", "(", "self", ")", "->", "List", "[", "Setting", "]", ":", "return", "[", "Setting", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"system\"", "]", "[", "\"getPow...
Get power settings.
[ "Get", "power", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L172-L177
rytilahti/python-songpal
songpal/device.py
Device.set_power_settings
async def set_power_settings(self, target: str, value: str) -> None: """Set power settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["system"]["setPowerSettings"](params)
python
async def set_power_settings(self, target: str, value: str) -> None: """Set power settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["system"]["setPowerSettings"](params)
[ "async", "def", "set_power_settings", "(", "self", ",", "target", ":", "str", ",", "value", ":", "str", ")", "->", "None", ":", "params", "=", "{", "\"settings\"", ":", "[", "{", "\"target\"", ":", "target", ",", "\"value\"", ":", "value", "}", "]", ...
Set power settings.
[ "Set", "power", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L179-L182
rytilahti/python-songpal
songpal/device.py
Device.get_googlecast_settings
async def get_googlecast_settings(self) -> List[Setting]: """Get Googlecast settings.""" return [ Setting.make(**x) for x in await self.services["system"]["getWuTangInfo"]({}) ]
python
async def get_googlecast_settings(self) -> List[Setting]: """Get Googlecast settings.""" return [ Setting.make(**x) for x in await self.services["system"]["getWuTangInfo"]({}) ]
[ "async", "def", "get_googlecast_settings", "(", "self", ")", "->", "List", "[", "Setting", "]", ":", "return", "[", "Setting", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"system\"", "]", "[", "\"g...
Get Googlecast settings.
[ "Get", "Googlecast", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L184-L189
rytilahti/python-songpal
songpal/device.py
Device.set_googlecast_settings
async def set_googlecast_settings(self, target: str, value: str): """Set Googlecast settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["system"]["setWuTangInfo"](params)
python
async def set_googlecast_settings(self, target: str, value: str): """Set Googlecast settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["system"]["setWuTangInfo"](params)
[ "async", "def", "set_googlecast_settings", "(", "self", ",", "target", ":", "str", ",", "value", ":", "str", ")", ":", "params", "=", "{", "\"settings\"", ":", "[", "{", "\"target\"", ":", "target", ",", "\"value\"", ":", "value", "}", "]", "}", "retur...
Set Googlecast settings.
[ "Set", "Googlecast", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L191-L194
rytilahti/python-songpal
songpal/device.py
Device.get_settings
async def get_settings(self) -> List[SettingsEntry]: """Get a list of available settings. See :func:request_settings_tree: for raw settings. """ settings = await self.request_settings_tree() return [SettingsEntry.make(**x) for x in settings["settings"]]
python
async def get_settings(self) -> List[SettingsEntry]: """Get a list of available settings. See :func:request_settings_tree: for raw settings. """ settings = await self.request_settings_tree() return [SettingsEntry.make(**x) for x in settings["settings"]]
[ "async", "def", "get_settings", "(", "self", ")", "->", "List", "[", "SettingsEntry", "]", ":", "settings", "=", "await", "self", ".", "request_settings_tree", "(", ")", "return", "[", "SettingsEntry", ".", "make", "(", "*", "*", "x", ")", "for", "x", ...
Get a list of available settings. See :func:request_settings_tree: for raw settings.
[ "Get", "a", "list", "of", "available", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L204-L210
rytilahti/python-songpal
songpal/device.py
Device.get_misc_settings
async def get_misc_settings(self) -> List[Setting]: """Return miscellaneous settings such as name and timezone.""" misc = await self.services["system"]["getDeviceMiscSettings"](target="") return [Setting.make(**x) for x in misc]
python
async def get_misc_settings(self) -> List[Setting]: """Return miscellaneous settings such as name and timezone.""" misc = await self.services["system"]["getDeviceMiscSettings"](target="") return [Setting.make(**x) for x in misc]
[ "async", "def", "get_misc_settings", "(", "self", ")", "->", "List", "[", "Setting", "]", ":", "misc", "=", "await", "self", ".", "services", "[", "\"system\"", "]", "[", "\"getDeviceMiscSettings\"", "]", "(", "target", "=", "\"\"", ")", "return", "[", "...
Return miscellaneous settings such as name and timezone.
[ "Return", "miscellaneous", "settings", "such", "as", "name", "and", "timezone", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L212-L215
rytilahti/python-songpal
songpal/device.py
Device.set_misc_settings
async def set_misc_settings(self, target: str, value: str): """Change miscellaneous settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["system"]["setDeviceMiscSettings"](params)
python
async def set_misc_settings(self, target: str, value: str): """Change miscellaneous settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["system"]["setDeviceMiscSettings"](params)
[ "async", "def", "set_misc_settings", "(", "self", ",", "target", ":", "str", ",", "value", ":", "str", ")", ":", "params", "=", "{", "\"settings\"", ":", "[", "{", "\"target\"", ":", "target", ",", "\"value\"", ":", "value", "}", "]", "}", "return", ...
Change miscellaneous settings.
[ "Change", "miscellaneous", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L217-L220
rytilahti/python-songpal
songpal/device.py
Device.get_sleep_timer_settings
async def get_sleep_timer_settings(self) -> List[Setting]: """Get sleep timer settings.""" return [ Setting.make(**x) for x in await self.services["system"]["getSleepTimerSettings"]({}) ]
python
async def get_sleep_timer_settings(self) -> List[Setting]: """Get sleep timer settings.""" return [ Setting.make(**x) for x in await self.services["system"]["getSleepTimerSettings"]({}) ]
[ "async", "def", "get_sleep_timer_settings", "(", "self", ")", "->", "List", "[", "Setting", "]", ":", "return", "[", "Setting", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"system\"", "]", "[", "\"...
Get sleep timer settings.
[ "Get", "sleep", "timer", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L231-L236
rytilahti/python-songpal
songpal/device.py
Device.get_storage_list
async def get_storage_list(self) -> List[Storage]: """Return information about connected storage devices.""" return [ Storage.make(**x) for x in await self.services["system"]["getStorageList"]({}) ]
python
async def get_storage_list(self) -> List[Storage]: """Return information about connected storage devices.""" return [ Storage.make(**x) for x in await self.services["system"]["getStorageList"]({}) ]
[ "async", "def", "get_storage_list", "(", "self", ")", "->", "List", "[", "Storage", "]", ":", "return", "[", "Storage", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"system\"", "]", "[", "\"getStora...
Return information about connected storage devices.
[ "Return", "information", "about", "connected", "storage", "devices", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L238-L243
rytilahti/python-songpal
songpal/device.py
Device.get_update_info
async def get_update_info(self, from_network=True) -> SoftwareUpdateInfo: """Get information about updates.""" if from_network: from_network = "true" else: from_network = "false" # from_network = "" info = await self.services["system"]["getSWUpdateInfo"](n...
python
async def get_update_info(self, from_network=True) -> SoftwareUpdateInfo: """Get information about updates.""" if from_network: from_network = "true" else: from_network = "false" # from_network = "" info = await self.services["system"]["getSWUpdateInfo"](n...
[ "async", "def", "get_update_info", "(", "self", ",", "from_network", "=", "True", ")", "->", "SoftwareUpdateInfo", ":", "if", "from_network", ":", "from_network", "=", "\"true\"", "else", ":", "from_network", "=", "\"false\"", "# from_network = \"\"", "info", "=",...
Get information about updates.
[ "Get", "information", "about", "updates", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L245-L253
rytilahti/python-songpal
songpal/device.py
Device.get_inputs
async def get_inputs(self) -> List[Input]: """Return list of available outputs.""" res = await self.services["avContent"]["getCurrentExternalTerminalsStatus"]() return [Input.make(services=self.services, **x) for x in res if 'meta:zone:output' not in x['meta']]
python
async def get_inputs(self) -> List[Input]: """Return list of available outputs.""" res = await self.services["avContent"]["getCurrentExternalTerminalsStatus"]() return [Input.make(services=self.services, **x) for x in res if 'meta:zone:output' not in x['meta']]
[ "async", "def", "get_inputs", "(", "self", ")", "->", "List", "[", "Input", "]", ":", "res", "=", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"getCurrentExternalTerminalsStatus\"", "]", "(", ")", "return", "[", "Input", ".", "make",...
Return list of available outputs.
[ "Return", "list", "of", "available", "outputs", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L259-L262
rytilahti/python-songpal
songpal/device.py
Device.get_zones
async def get_zones(self) -> List[Zone]: """Return list of available zones.""" res = await self.services["avContent"]["getCurrentExternalTerminalsStatus"]() zones = [Zone.make(services=self.services, **x) for x in res if 'meta:zone:output' in x['meta']] if not zones: raise So...
python
async def get_zones(self) -> List[Zone]: """Return list of available zones.""" res = await self.services["avContent"]["getCurrentExternalTerminalsStatus"]() zones = [Zone.make(services=self.services, **x) for x in res if 'meta:zone:output' in x['meta']] if not zones: raise So...
[ "async", "def", "get_zones", "(", "self", ")", "->", "List", "[", "Zone", "]", ":", "res", "=", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"getCurrentExternalTerminalsStatus\"", "]", "(", ")", "zones", "=", "[", "Zone", ".", "mak...
Return list of available zones.
[ "Return", "list", "of", "available", "zones", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L264-L270
rytilahti/python-songpal
songpal/device.py
Device.get_setting
async def get_setting(self, service: str, method: str, target: str): """Get a single setting for service. :param service: Service to query. :param method: Getter method for the setting, read from ApiMapping. :param target: Setting to query. :return: JSON response from the device...
python
async def get_setting(self, service: str, method: str, target: str): """Get a single setting for service. :param service: Service to query. :param method: Getter method for the setting, read from ApiMapping. :param target: Setting to query. :return: JSON response from the device...
[ "async", "def", "get_setting", "(", "self", ",", "service", ":", "str", ",", "method", ":", "str", ",", "target", ":", "str", ")", ":", "return", "await", "self", ".", "services", "[", "service", "]", "[", "method", "]", "(", "target", "=", "target",...
Get a single setting for service. :param service: Service to query. :param method: Getter method for the setting, read from ApiMapping. :param target: Setting to query. :return: JSON response from the device.
[ "Get", "a", "single", "setting", "for", "service", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L280-L288
rytilahti/python-songpal
songpal/device.py
Device.get_bluetooth_settings
async def get_bluetooth_settings(self) -> List[Setting]: """Get bluetooth settings.""" bt = await self.services["avContent"]["getBluetoothSettings"]({}) return [Setting.make(**x) for x in bt]
python
async def get_bluetooth_settings(self) -> List[Setting]: """Get bluetooth settings.""" bt = await self.services["avContent"]["getBluetoothSettings"]({}) return [Setting.make(**x) for x in bt]
[ "async", "def", "get_bluetooth_settings", "(", "self", ")", "->", "List", "[", "Setting", "]", ":", "bt", "=", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"getBluetoothSettings\"", "]", "(", "{", "}", ")", "return", "[", "Setting", ...
Get bluetooth settings.
[ "Get", "bluetooth", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L290-L293