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
HPAC/matchpy
matchpy/matching/many_to_one.py
ManyToOneMatcher.add
def add(self, pattern: Pattern, label=None) -> None: """Add a new pattern to the matcher. The optional label defaults to the pattern itself and is yielded during matching. The same pattern can be added with different labels which means that every match for the pattern will result in every assoc...
python
def add(self, pattern: Pattern, label=None) -> None: """Add a new pattern to the matcher. The optional label defaults to the pattern itself and is yielded during matching. The same pattern can be added with different labels which means that every match for the pattern will result in every assoc...
[ "def", "add", "(", "self", ",", "pattern", ":", "Pattern", ",", "label", "=", "None", ")", "->", "None", ":", "if", "label", "is", "None", ":", "label", "=", "pattern", "for", "i", ",", "(", "p", ",", "l", ",", "_", ")", "in", "enumerate", "(",...
Add a new pattern to the matcher. The optional label defaults to the pattern itself and is yielded during matching. The same pattern can be added with different labels which means that every match for the pattern will result in every associated label being yielded with that match individually. ...
[ "Add", "a", "new", "pattern", "to", "the", "matcher", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L344-L367
HPAC/matchpy
matchpy/matching/many_to_one.py
ManyToOneMatcher._internal_add
def _internal_add(self, pattern: Pattern, label, renaming) -> int: """Add a new pattern to the matcher. Equivalent patterns are not added again. However, patterns that are structurally equivalent, but have different constraints or different variable names are distinguished by the matcher. ...
python
def _internal_add(self, pattern: Pattern, label, renaming) -> int: """Add a new pattern to the matcher. Equivalent patterns are not added again. However, patterns that are structurally equivalent, but have different constraints or different variable names are distinguished by the matcher. ...
[ "def", "_internal_add", "(", "self", ",", "pattern", ":", "Pattern", ",", "label", ",", "renaming", ")", "->", "int", ":", "pattern_index", "=", "len", "(", "self", ".", "patterns", ")", "renamed_constraints", "=", "[", "c", ".", "with_renamed_vars", "(", ...
Add a new pattern to the matcher. Equivalent patterns are not added again. However, patterns that are structurally equivalent, but have different constraints or different variable names are distinguished by the matcher. Args: pattern: The pattern to add. Returns: ...
[ "Add", "a", "new", "pattern", "to", "the", "matcher", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L369-L392
HPAC/matchpy
matchpy/matching/many_to_one.py
ManyToOneMatcher.match
def match(self, subject: Expression) -> Iterator[Tuple[Expression, Substitution]]: """Match the subject against all the matcher's patterns. Args: subject: The subject to match. Yields: For every match, a tuple of the matching pattern and the match substitution. ...
python
def match(self, subject: Expression) -> Iterator[Tuple[Expression, Substitution]]: """Match the subject against all the matcher's patterns. Args: subject: The subject to match. Yields: For every match, a tuple of the matching pattern and the match substitution. ...
[ "def", "match", "(", "self", ",", "subject", ":", "Expression", ")", "->", "Iterator", "[", "Tuple", "[", "Expression", ",", "Substitution", "]", "]", ":", "return", "_MatchIter", "(", "self", ",", "subject", ")" ]
Match the subject against all the matcher's patterns. Args: subject: The subject to match. Yields: For every match, a tuple of the matching pattern and the match substitution.
[ "Match", "the", "subject", "against", "all", "the", "matcher", "s", "patterns", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L434-L443
HPAC/matchpy
matchpy/matching/many_to_one.py
ManyToOneMatcher._collect_variable_renaming
def _collect_variable_renaming( cls, expression: Expression, position: List[int]=None, variables: Dict[str, str]=None ) -> Dict[str, str]: """Return renaming for the variables in the expression. The variable names are generated according to the position of the variable in the expression...
python
def _collect_variable_renaming( cls, expression: Expression, position: List[int]=None, variables: Dict[str, str]=None ) -> Dict[str, str]: """Return renaming for the variables in the expression. The variable names are generated according to the position of the variable in the expression...
[ "def", "_collect_variable_renaming", "(", "cls", ",", "expression", ":", "Expression", ",", "position", ":", "List", "[", "int", "]", "=", "None", ",", "variables", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ")", "->", "Dict", "[", "str", ...
Return renaming for the variables in the expression. The variable names are generated according to the position of the variable in the expression. The goal is to rename variables in structurally identical patterns so that the automaton contains less redundant states.
[ "Return", "renaming", "for", "the", "variables", "in", "the", "expression", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L532-L558
HPAC/matchpy
matchpy/matching/many_to_one.py
ManyToOneReplacer.add
def add(self, rule: 'functions.ReplacementRule') -> None: """Add a new rule to the replacer. Args: rule: The rule to add. """ self.matcher.add(rule.pattern, rule.replacement)
python
def add(self, rule: 'functions.ReplacementRule') -> None: """Add a new rule to the replacer. Args: rule: The rule to add. """ self.matcher.add(rule.pattern, rule.replacement)
[ "def", "add", "(", "self", ",", "rule", ":", "'functions.ReplacementRule'", ")", "->", "None", ":", "self", ".", "matcher", ".", "add", "(", "rule", ".", "pattern", ",", "rule", ".", "replacement", ")" ]
Add a new rule to the replacer. Args: rule: The rule to add.
[ "Add", "a", "new", "rule", "to", "the", "replacer", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L766-L773
HPAC/matchpy
matchpy/matching/many_to_one.py
ManyToOneReplacer.replace
def replace(self, expression: Expression, max_count: int=math.inf) -> Union[Expression, Sequence[Expression]]: """Replace all occurrences of the patterns according to the replacement rules. Args: expression: The expression to which the replacement rules are applied. ...
python
def replace(self, expression: Expression, max_count: int=math.inf) -> Union[Expression, Sequence[Expression]]: """Replace all occurrences of the patterns according to the replacement rules. Args: expression: The expression to which the replacement rules are applied. ...
[ "def", "replace", "(", "self", ",", "expression", ":", "Expression", ",", "max_count", ":", "int", "=", "math", ".", "inf", ")", "->", "Union", "[", "Expression", ",", "Sequence", "[", "Expression", "]", "]", ":", "replaced", "=", "True", "replace_count"...
Replace all occurrences of the patterns according to the replacement rules. Args: expression: The expression to which the replacement rules are applied. max_count: If given, at most *max_count* applications of the rules are performed. Otherwise, the rules...
[ "Replace", "all", "occurrences", "of", "the", "patterns", "according", "to", "the", "replacement", "rules", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L775-L804
HPAC/matchpy
matchpy/matching/many_to_one.py
ManyToOneReplacer.replace_post_order
def replace_post_order(self, expression: Expression) -> Union[Expression, Sequence[Expression]]: """Replace all occurrences of the patterns according to the replacement rules. Replaces innermost expressions first. Args: expression: The expression to which the replac...
python
def replace_post_order(self, expression: Expression) -> Union[Expression, Sequence[Expression]]: """Replace all occurrences of the patterns according to the replacement rules. Replaces innermost expressions first. Args: expression: The expression to which the replac...
[ "def", "replace_post_order", "(", "self", ",", "expression", ":", "Expression", ")", "->", "Union", "[", "Expression", ",", "Sequence", "[", "Expression", "]", "]", ":", "return", "self", ".", "_replace_post_order", "(", "expression", ")", "[", "0", "]" ]
Replace all occurrences of the patterns according to the replacement rules. Replaces innermost expressions first. Args: expression: The expression to which the replacement rules are applied. max_count: If given, at most *max_count* applications o...
[ "Replace", "all", "occurrences", "of", "the", "patterns", "according", "to", "the", "replacement", "rules", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L806-L823
HPAC/matchpy
matchpy/matching/many_to_one.py
CommutativeMatcher.bipartite_as_graph
def bipartite_as_graph(self) -> Graph: # pragma: no cover """Returns a :class:`graphviz.Graph` representation of this bipartite graph.""" if Graph is None: raise ImportError('The graphviz package is required to draw the graph.') graph = Graph() nodes_left = {} # type: Dict[...
python
def bipartite_as_graph(self) -> Graph: # pragma: no cover """Returns a :class:`graphviz.Graph` representation of this bipartite graph.""" if Graph is None: raise ImportError('The graphviz package is required to draw the graph.') graph = Graph() nodes_left = {} # type: Dict[...
[ "def", "bipartite_as_graph", "(", "self", ")", "->", "Graph", ":", "# pragma: no cover", "if", "Graph", "is", "None", ":", "raise", "ImportError", "(", "'The graphviz package is required to draw the graph.'", ")", "graph", "=", "Graph", "(", ")", "nodes_left", "=", ...
Returns a :class:`graphviz.Graph` representation of this bipartite graph.
[ "Returns", "a", ":", "class", ":", "graphviz", ".", "Graph", "representation", "of", "this", "bipartite", "graph", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L1058-L1081
HPAC/matchpy
matchpy/matching/many_to_one.py
CommutativeMatcher.concrete_bipartite_as_graph
def concrete_bipartite_as_graph(self, subjects, patterns) -> Graph: # pragma: no cover """Returns a :class:`graphviz.Graph` representation of this bipartite graph.""" if Graph is None: raise ImportError('The graphviz package is required to draw the graph.') bipartite = self._build_b...
python
def concrete_bipartite_as_graph(self, subjects, patterns) -> Graph: # pragma: no cover """Returns a :class:`graphviz.Graph` representation of this bipartite graph.""" if Graph is None: raise ImportError('The graphviz package is required to draw the graph.') bipartite = self._build_b...
[ "def", "concrete_bipartite_as_graph", "(", "self", ",", "subjects", ",", "patterns", ")", "->", "Graph", ":", "# pragma: no cover", "if", "Graph", "is", "None", ":", "raise", "ImportError", "(", "'The graphviz package is required to draw the graph.'", ")", "bipartite", ...
Returns a :class:`graphviz.Graph` representation of this bipartite graph.
[ "Returns", "a", ":", "class", ":", "graphviz", ".", "Graph", "representation", "of", "this", "bipartite", "graph", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L1083-L1109
HPAC/matchpy
matchpy/expressions/expressions.py
Expression.collect_variables
def collect_variables(self, variables: MultisetOfVariables) -> None: """Recursively adds all variables occuring in the expression to the given multiset. This is used internally by `variables`. Needs to be overwritten by inheriting container expression classes. This method can be used when gathe...
python
def collect_variables(self, variables: MultisetOfVariables) -> None: """Recursively adds all variables occuring in the expression to the given multiset. This is used internally by `variables`. Needs to be overwritten by inheriting container expression classes. This method can be used when gathe...
[ "def", "collect_variables", "(", "self", ",", "variables", ":", "MultisetOfVariables", ")", "->", "None", ":", "if", "self", ".", "variable_name", "is", "not", "None", ":", "variables", ".", "add", "(", "self", ".", "variable_name", ")" ]
Recursively adds all variables occuring in the expression to the given multiset. This is used internally by `variables`. Needs to be overwritten by inheriting container expression classes. This method can be used when gathering the `variables` of multiple expressions, because only one multiset ...
[ "Recursively", "adds", "all", "variables", "occuring", "in", "the", "expression", "to", "the", "given", "multiset", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/expressions.py#L97-L109
HPAC/matchpy
matchpy/expressions/expressions.py
_OperationMeta._simplify
def _simplify(cls, operands: List[Expression]) -> bool: """Flatten/sort the operands of associative/commutative operations. Returns: True iff *one_identity* is True and the operation contains a single argument that is not a sequence wildcard. """ if cls.associat...
python
def _simplify(cls, operands: List[Expression]) -> bool: """Flatten/sort the operands of associative/commutative operations. Returns: True iff *one_identity* is True and the operation contains a single argument that is not a sequence wildcard. """ if cls.associat...
[ "def", "_simplify", "(", "cls", ",", "operands", ":", "List", "[", "Expression", "]", ")", "->", "bool", ":", "if", "cls", ".", "associative", ":", "new_operands", "=", "[", "]", "# type: List[Expression]", "for", "operand", "in", "operands", ":", "if", ...
Flatten/sort the operands of associative/commutative operations. Returns: True iff *one_identity* is True and the operation contains a single argument that is not a sequence wildcard.
[ "Flatten", "/", "sort", "the", "operands", "of", "associative", "/", "commutative", "operations", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/expressions.py#L287-L313
HPAC/matchpy
matchpy/expressions/expressions.py
Operation.new
def new( name: str, arity: Arity, class_name: str=None, *, associative: bool=False, commutative: bool=False, one_identity: bool=False, infix: bool=False ) -> Type['Operation']: """Utility method to create a new o...
python
def new( name: str, arity: Arity, class_name: str=None, *, associative: bool=False, commutative: bool=False, one_identity: bool=False, infix: bool=False ) -> Type['Operation']: """Utility method to create a new o...
[ "def", "new", "(", "name", ":", "str", ",", "arity", ":", "Arity", ",", "class_name", ":", "str", "=", "None", ",", "*", ",", "associative", ":", "bool", "=", "False", ",", "commutative", ":", "bool", "=", "False", ",", "one_identity", ":", "bool", ...
Utility method to create a new operation type. Example: >>> Times = Operation.new('*', Arity.polyadic, 'Times', associative=True, commutative=True, one_identity=True) >>> Times Times['*', Arity(min_count=2, fixed_size=False), associative, commutative, one_identity] >>> str(Time...
[ "Utility", "method", "to", "create", "a", "new", "operation", "type", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/expressions.py#L426-L482
HPAC/matchpy
matchpy/expressions/expressions.py
Wildcard.optional
def optional(name, default) -> 'Wildcard': """Create a `Wildcard` that matches a single argument with a default value. If the wildcard does not match, the substitution will contain the default value instead. Args: name: The name for the wildcard. ...
python
def optional(name, default) -> 'Wildcard': """Create a `Wildcard` that matches a single argument with a default value. If the wildcard does not match, the substitution will contain the default value instead. Args: name: The name for the wildcard. ...
[ "def", "optional", "(", "name", ",", "default", ")", "->", "'Wildcard'", ":", "return", "Wildcard", "(", "min_count", "=", "1", ",", "fixed_size", "=", "True", ",", "variable_name", "=", "name", ",", "optional", "=", "default", ")" ]
Create a `Wildcard` that matches a single argument with a default value. If the wildcard does not match, the substitution will contain the default value instead. Args: name: The name for the wildcard. default: The default value of the wil...
[ "Create", "a", "Wildcard", "that", "matches", "a", "single", "argument", "with", "a", "default", "value", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/expressions.py#L755-L770
HPAC/matchpy
matchpy/expressions/expressions.py
Wildcard.symbol
def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard': """Create a `SymbolWildcard` that matches a single `Symbol` argument. Args: name: Optional variable name for the wildcard. symbol_type: An optional subclass of `Symb...
python
def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard': """Create a `SymbolWildcard` that matches a single `Symbol` argument. Args: name: Optional variable name for the wildcard. symbol_type: An optional subclass of `Symb...
[ "def", "symbol", "(", "name", ":", "str", "=", "None", ",", "symbol_type", ":", "Type", "[", "Symbol", "]", "=", "Symbol", ")", "->", "'SymbolWildcard'", ":", "if", "isinstance", "(", "name", ",", "type", ")", "and", "issubclass", "(", "name", ",", "...
Create a `SymbolWildcard` that matches a single `Symbol` argument. Args: name: Optional variable name for the wildcard. symbol_type: An optional subclass of `Symbol` to further limit which kind of symbols are matched by the wildcard. ...
[ "Create", "a", "SymbolWildcard", "that", "matches", "a", "single", "Symbol", "argument", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/expressions.py#L773-L788
optimizely/optimizely-client-python
optimizely/client.py
Client.request
def request(self, method, url_parts, headers=None, data=None): """ Method for making requests to the Optimizely API """ if method in self.ALLOWED_REQUESTS: # add request token header headers = headers or {} # test if Oauth token if self.token_type...
python
def request(self, method, url_parts, headers=None, data=None): """ Method for making requests to the Optimizely API """ if method in self.ALLOWED_REQUESTS: # add request token header headers = headers or {} # test if Oauth token if self.token_type...
[ "def", "request", "(", "self", ",", "method", ",", "url_parts", ",", "headers", "=", "None", ",", "data", "=", "None", ")", ":", "if", "method", "in", "self", ".", "ALLOWED_REQUESTS", ":", "# add request token header", "headers", "=", "headers", "or", "{",...
Method for making requests to the Optimizely API
[ "Method", "for", "making", "requests", "to", "the", "Optimizely", "API" ]
train
https://github.com/optimizely/optimizely-client-python/blob/c4a121e8ac66e44f6ef4ad4959ef46ed3992708a/optimizely/client.py#L45-L74
optimizely/optimizely-client-python
optimizely/client.py
Client.parse_response
def parse_response(resp): """ Method to parse response from the Optimizely API and return results as JSON. Errors are thrown for various errors that the API can throw. """ if resp.status_code in [200, 201, 202]: return resp.json() elif resp.status_code == 204:...
python
def parse_response(resp): """ Method to parse response from the Optimizely API and return results as JSON. Errors are thrown for various errors that the API can throw. """ if resp.status_code in [200, 201, 202]: return resp.json() elif resp.status_code == 204:...
[ "def", "parse_response", "(", "resp", ")", ":", "if", "resp", ".", "status_code", "in", "[", "200", ",", "201", ",", "202", "]", ":", "return", "resp", ".", "json", "(", ")", "elif", "resp", ".", "status_code", "==", "204", ":", "return", "None", "...
Method to parse response from the Optimizely API and return results as JSON. Errors are thrown for various errors that the API can throw.
[ "Method", "to", "parse", "response", "from", "the", "Optimizely", "API", "and", "return", "results", "as", "JSON", ".", "Errors", "are", "thrown", "for", "various", "errors", "that", "the", "API", "can", "throw", "." ]
train
https://github.com/optimizely/optimizely-client-python/blob/c4a121e8ac66e44f6ef4ad4959ef46ed3992708a/optimizely/client.py#L77-L99
sirrice/pygg
pygg/pygg.py
_to_r
def _to_r(o, as_data=False, level=0): """Helper function to convert python data structures to R equivalents TODO: a single model for transforming to r to handle * function args * lists as function args """ if o is None: return "NA" if isinstance(o, basestring): return o ...
python
def _to_r(o, as_data=False, level=0): """Helper function to convert python data structures to R equivalents TODO: a single model for transforming to r to handle * function args * lists as function args """ if o is None: return "NA" if isinstance(o, basestring): return o ...
[ "def", "_to_r", "(", "o", ",", "as_data", "=", "False", ",", "level", "=", "0", ")", ":", "if", "o", "is", "None", ":", "return", "\"NA\"", "if", "isinstance", "(", "o", ",", "basestring", ")", ":", "return", "o", "if", "hasattr", "(", "o", ",", ...
Helper function to convert python data structures to R equivalents TODO: a single model for transforming to r to handle * function args * lists as function args
[ "Helper", "function", "to", "convert", "python", "data", "structures", "to", "R", "equivalents" ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L32-L55
sirrice/pygg
pygg/pygg.py
data_sql
def data_sql(db, sql): """Load file using RPostgreSQL Place to edit if want to add more database backend support """ if not db: if sql: print "ERR: -db option must be set if using -sql" return "" cmd = """ library(RPostgreSQL) drv = dbDriver('PostgreSQL') c...
python
def data_sql(db, sql): """Load file using RPostgreSQL Place to edit if want to add more database backend support """ if not db: if sql: print "ERR: -db option must be set if using -sql" return "" cmd = """ library(RPostgreSQL) drv = dbDriver('PostgreSQL') c...
[ "def", "data_sql", "(", "db", ",", "sql", ")", ":", "if", "not", "db", ":", "if", "sql", ":", "print", "\"ERR: -db option must be set if using -sql\"", "return", "\"\"", "cmd", "=", "\"\"\"\n library(RPostgreSQL)\n drv = dbDriver('PostgreSQL')\n con = dbConnect(drv...
Load file using RPostgreSQL Place to edit if want to add more database backend support
[ "Load", "file", "using", "RPostgreSQL" ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L151-L173
sirrice/pygg
pygg/pygg.py
data_py
def data_py(o, *args, **kwargs): """converts python object into R Dataframe definition converts following data structures: row oriented list of dictionaries: [ { 'x': 0, 'y': 1, ...}, ... ] col oriented dictionary of lists { 'x': [0,1,2...], 'y': [...], ... } @param o p...
python
def data_py(o, *args, **kwargs): """converts python object into R Dataframe definition converts following data structures: row oriented list of dictionaries: [ { 'x': 0, 'y': 1, ...}, ... ] col oriented dictionary of lists { 'x': [0,1,2...], 'y': [...], ... } @param o p...
[ "def", "data_py", "(", "o", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "o", ",", "basestring", ")", ":", "fname", "=", "o", "else", ":", "if", "not", "is_pandas_df", "(", "o", ")", ":", "# convert incoming data layo...
converts python object into R Dataframe definition converts following data structures: row oriented list of dictionaries: [ { 'x': 0, 'y': 1, ...}, ... ] col oriented dictionary of lists { 'x': [0,1,2...], 'y': [...], ... } @param o python object to convert @param args ...
[ "converts", "python", "object", "into", "R", "Dataframe", "definition" ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L176-L208
sirrice/pygg
pygg/pygg.py
ggsave
def ggsave(name, plot, data=None, *args, **kwargs): """Save a GGStatements object to destination name @param name output file name. if None, don't run R command @param kwargs keyword args to pass to ggsave. The following are special keywords for the python save method data: a python da...
python
def ggsave(name, plot, data=None, *args, **kwargs): """Save a GGStatements object to destination name @param name output file name. if None, don't run R command @param kwargs keyword args to pass to ggsave. The following are special keywords for the python save method data: a python da...
[ "def", "ggsave", "(", "name", ",", "plot", ",", "data", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# constants", "kwdefaults", "=", "{", "'width'", ":", "10", ",", "'height'", ":", "8", ",", "'scale'", ":", "1", "}", "keys...
Save a GGStatements object to destination name @param name output file name. if None, don't run R command @param kwargs keyword args to pass to ggsave. The following are special keywords for the python save method data: a python data object (list, dict, DataFrame) used to populate ...
[ "Save", "a", "GGStatements", "object", "to", "destination", "name" ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L245-L315
sirrice/pygg
pygg/pygg.py
gg_ipython
def gg_ipython(plot, data, width=IPYTHON_IMAGE_SIZE, height=None, *args, **kwargs): """Render pygg in an IPython notebook Allows one to say things like: import pygg p = pygg.ggplot('diamonds', pygg.aes(x='carat', y='price', color='clarity')) p += pygg.geom_point(alpha=0.5, size = 2)...
python
def gg_ipython(plot, data, width=IPYTHON_IMAGE_SIZE, height=None, *args, **kwargs): """Render pygg in an IPython notebook Allows one to say things like: import pygg p = pygg.ggplot('diamonds', pygg.aes(x='carat', y='price', color='clarity')) p += pygg.geom_point(alpha=0.5, size = 2)...
[ "def", "gg_ipython", "(", "plot", ",", "data", ",", "width", "=", "IPYTHON_IMAGE_SIZE", ",", "height", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "import", "IPython", ".", "display", "tmp_image_filename", "=", "tempfile...
Render pygg in an IPython notebook Allows one to say things like: import pygg p = pygg.ggplot('diamonds', pygg.aes(x='carat', y='price', color='clarity')) p += pygg.geom_point(alpha=0.5, size = 2) p += pygg.scale_x_log10(limits=[1, 2]) pygg.gg_ipython(p, data=None, quiet=True) directly in...
[ "Render", "pygg", "in", "an", "IPython", "notebook" ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L318-L359
sirrice/pygg
pygg/pygg.py
size_r_img_inches
def size_r_img_inches(width, height): """Compute the width and height for an R image for display in IPython Neight width nor height can be null but should be integer pixel values > 0. Returns a tuple of (width, height) that should be used by ggsave in R to produce an appropriately sized jpeg/png/pdf i...
python
def size_r_img_inches(width, height): """Compute the width and height for an R image for display in IPython Neight width nor height can be null but should be integer pixel values > 0. Returns a tuple of (width, height) that should be used by ggsave in R to produce an appropriately sized jpeg/png/pdf i...
[ "def", "size_r_img_inches", "(", "width", ",", "height", ")", ":", "# both width and height are given", "aspect_ratio", "=", "height", "/", "(", "1.0", "*", "width", ")", "return", "R_IMAGE_SIZE", ",", "round", "(", "aspect_ratio", "*", "R_IMAGE_SIZE", ",", "2",...
Compute the width and height for an R image for display in IPython Neight width nor height can be null but should be integer pixel values > 0. Returns a tuple of (width, height) that should be used by ggsave in R to produce an appropriately sized jpeg/png/pdf image with the right aspect ratio. The re...
[ "Compute", "the", "width", "and", "height", "for", "an", "R", "image", "for", "display", "in", "IPython" ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L362-L374
sirrice/pygg
pygg/pygg.py
execute_r
def execute_r(prog, quiet): """Run the R code prog an R subprocess @raises ValueError if the subprocess exits with non-zero status """ FNULL = open(os.devnull, 'w') if quiet else None try: input_proc = subprocess.Popen(["echo", prog], stdout=subprocess.PIPE) status = subprocess.call...
python
def execute_r(prog, quiet): """Run the R code prog an R subprocess @raises ValueError if the subprocess exits with non-zero status """ FNULL = open(os.devnull, 'w') if quiet else None try: input_proc = subprocess.Popen(["echo", prog], stdout=subprocess.PIPE) status = subprocess.call...
[ "def", "execute_r", "(", "prog", ",", "quiet", ")", ":", "FNULL", "=", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "if", "quiet", "else", "None", "try", ":", "input_proc", "=", "subprocess", ".", "Popen", "(", "[", "\"echo\"", ",", "prog", ...
Run the R code prog an R subprocess @raises ValueError if the subprocess exits with non-zero status
[ "Run", "the", "R", "code", "prog", "an", "R", "subprocess" ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L377-L395
sirrice/pygg
pygg/pygg.py
axis_labels
def axis_labels(xtitle, ytitle, xsuffix="continuous", ysuffix="continuous", xkwargs={}, ykwargs={}): """ Helper function to create reasonable axis labels @param xtitle String for the title of the X axis. Automatically escaped @...
python
def axis_labels(xtitle, ytitle, xsuffix="continuous", ysuffix="continuous", xkwargs={}, ykwargs={}): """ Helper function to create reasonable axis labels @param xtitle String for the title of the X axis. Automatically escaped @...
[ "def", "axis_labels", "(", "xtitle", ",", "ytitle", ",", "xsuffix", "=", "\"continuous\"", ",", "ysuffix", "=", "\"continuous\"", ",", "xkwargs", "=", "{", "}", ",", "ykwargs", "=", "{", "}", ")", ":", "exec", "\"xfunc = scale_x_%s\"", "%", "xsuffix", "exe...
Helper function to create reasonable axis labels @param xtitle String for the title of the X axis. Automatically escaped @param ytitle String for the title of the Y axis. Automatically escaped @param xsuffix Suffix string appended to "scales_x_" to define the type of x axis Default: "continuou...
[ "Helper", "function", "to", "create", "reasonable", "axis", "labels" ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L403-L437
sirrice/pygg
pygg/pygg.py
make_master_binding
def make_master_binding(): """ wrap around ggplot() call to handle passed in data objects """ ggplot = make_ggplot2_binding("ggplot") def _ggplot(data, *args, **kwargs): data_var = data if not isinstance(data, basestring): data_var = "data" else: data = None stmt = ggplot(data_var,...
python
def make_master_binding(): """ wrap around ggplot() call to handle passed in data objects """ ggplot = make_ggplot2_binding("ggplot") def _ggplot(data, *args, **kwargs): data_var = data if not isinstance(data, basestring): data_var = "data" else: data = None stmt = ggplot(data_var,...
[ "def", "make_master_binding", "(", ")", ":", "ggplot", "=", "make_ggplot2_binding", "(", "\"ggplot\"", ")", "def", "_ggplot", "(", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data_var", "=", "data", "if", "not", "isinstance", "(", "data...
wrap around ggplot() call to handle passed in data objects
[ "wrap", "around", "ggplot", "()", "call", "to", "handle", "passed", "in", "data", "objects" ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L448-L462
sirrice/pygg
pygg/pygg.py
GGStatement.r
def r(self): """Convert this GGStatement into its R equivalent expression""" r_args = [_to_r(self.args), _to_r(self.kwargs)] # remove empty strings from the call args r_args = ",".join([x for x in r_args if x != ""]) return "{}({})".format(self.name, r_args)
python
def r(self): """Convert this GGStatement into its R equivalent expression""" r_args = [_to_r(self.args), _to_r(self.kwargs)] # remove empty strings from the call args r_args = ",".join([x for x in r_args if x != ""]) return "{}({})".format(self.name, r_args)
[ "def", "r", "(", "self", ")", ":", "r_args", "=", "[", "_to_r", "(", "self", ".", "args", ")", ",", "_to_r", "(", "self", ".", "kwargs", ")", "]", "# remove empty strings from the call args", "r_args", "=", "\",\"", ".", "join", "(", "[", "x", "for", ...
Convert this GGStatement into its R equivalent expression
[ "Convert", "this", "GGStatement", "into", "its", "R", "equivalent", "expression" ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L74-L79
sirrice/pygg
bin/runpygg.py
main
def main(c, prefix, csv, db, sql, o, w, h, scale): """ ggplot2 syntax in Python. Run pygg command from command line python pygg -c "ggplot('diamonds', aes('carat', 'price')) + geom_point()" Import into your python program to use ggplot \b from pygg import * p = ggplot('diamonds', aes('carat'...
python
def main(c, prefix, csv, db, sql, o, w, h, scale): """ ggplot2 syntax in Python. Run pygg command from command line python pygg -c "ggplot('diamonds', aes('carat', 'price')) + geom_point()" Import into your python program to use ggplot \b from pygg import * p = ggplot('diamonds', aes('carat'...
[ "def", "main", "(", "c", ",", "prefix", ",", "csv", ",", "db", ",", "sql", ",", "o", ",", "w", ",", "h", ",", "scale", ")", ":", "if", "not", "c", ":", "print", "\"no command. exiting\"", "return", "kwargs", "=", "{", "'width'", ":", "w", ",", ...
ggplot2 syntax in Python. Run pygg command from command line python pygg -c "ggplot('diamonds', aes('carat', 'price')) + geom_point()" Import into your python program to use ggplot \b from pygg import * p = ggplot('diamonds', aes('carat', y='price')) + geom_point() p = p + facet_wrap(None, "...
[ "ggplot2", "syntax", "in", "Python", "." ]
train
https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/bin/runpygg.py#L24-L100
pygeobuf/pygeobuf
geobuf/scripts/cli.py
encode
def encode(precision, with_z): """Given GeoJSON on stdin, writes a geobuf file to stdout.""" logger = logging.getLogger('geobuf') stdin = click.get_text_stream('stdin') sink = click.get_binary_stream('stdout') try: data = json.load(stdin) pbf = geobuf.encode( data, ...
python
def encode(precision, with_z): """Given GeoJSON on stdin, writes a geobuf file to stdout.""" logger = logging.getLogger('geobuf') stdin = click.get_text_stream('stdin') sink = click.get_binary_stream('stdout') try: data = json.load(stdin) pbf = geobuf.encode( data, ...
[ "def", "encode", "(", "precision", ",", "with_z", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'geobuf'", ")", "stdin", "=", "click", ".", "get_text_stream", "(", "'stdin'", ")", "sink", "=", "click", ".", "get_binary_stream", "(", "'stdout'...
Given GeoJSON on stdin, writes a geobuf file to stdout.
[ "Given", "GeoJSON", "on", "stdin", "writes", "a", "geobuf", "file", "to", "stdout", "." ]
train
https://github.com/pygeobuf/pygeobuf/blob/c9e055ab47532781626cfe2c931a8444820acf05/geobuf/scripts/cli.py#L46-L61
pygeobuf/pygeobuf
geobuf/scripts/cli.py
decode
def decode(): """Given a Geobuf byte string on stdin, write a GeoJSON feature collection to stdout.""" logger = logging.getLogger('geobuf') stdin = click.get_binary_stream('stdin') sink = click.get_text_stream('stdout') try: pbf = stdin.read() data = geobuf.decode(pbf) js...
python
def decode(): """Given a Geobuf byte string on stdin, write a GeoJSON feature collection to stdout.""" logger = logging.getLogger('geobuf') stdin = click.get_binary_stream('stdin') sink = click.get_text_stream('stdout') try: pbf = stdin.read() data = geobuf.decode(pbf) js...
[ "def", "decode", "(", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'geobuf'", ")", "stdin", "=", "click", ".", "get_binary_stream", "(", "'stdin'", ")", "sink", "=", "click", ".", "get_text_stream", "(", "'stdout'", ")", "try", ":", "pbf",...
Given a Geobuf byte string on stdin, write a GeoJSON feature collection to stdout.
[ "Given", "a", "Geobuf", "byte", "string", "on", "stdin", "write", "a", "GeoJSON", "feature", "collection", "to", "stdout", "." ]
train
https://github.com/pygeobuf/pygeobuf/blob/c9e055ab47532781626cfe2c931a8444820acf05/geobuf/scripts/cli.py#L65-L78
tammoippen/geohash-hilbert
geohash_hilbert/_int2str.py
encode_int
def encode_int(code, bits_per_char=6): """Encode int into a string preserving order It is using 2, 4 or 6 bits per coding character (default 6). Parameters: code: int Positive integer. bits_per_char: int The number of bits per coding character. Returns: str: the enc...
python
def encode_int(code, bits_per_char=6): """Encode int into a string preserving order It is using 2, 4 or 6 bits per coding character (default 6). Parameters: code: int Positive integer. bits_per_char: int The number of bits per coding character. Returns: str: the enc...
[ "def", "encode_int", "(", "code", ",", "bits_per_char", "=", "6", ")", ":", "if", "code", "<", "0", ":", "raise", "ValueError", "(", "'Only positive ints are allowed!'", ")", "if", "bits_per_char", "==", "6", ":", "return", "_encode_int64", "(", "code", ")",...
Encode int into a string preserving order It is using 2, 4 or 6 bits per coding character (default 6). Parameters: code: int Positive integer. bits_per_char: int The number of bits per coding character. Returns: str: the encoded integer
[ "Encode", "int", "into", "a", "string", "preserving", "order" ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_int2str.py#L27-L49
tammoippen/geohash-hilbert
geohash_hilbert/_int2str.py
decode_int
def decode_int(tag, bits_per_char=6): """Decode string into int assuming encoding with `encode_int()` It is using 2, 4 or 6 bits per coding character (default 6). Parameters: tag: str Encoded integer. bits_per_char: int The number of bits per coding character. Returns: ...
python
def decode_int(tag, bits_per_char=6): """Decode string into int assuming encoding with `encode_int()` It is using 2, 4 or 6 bits per coding character (default 6). Parameters: tag: str Encoded integer. bits_per_char: int The number of bits per coding character. Returns: ...
[ "def", "decode_int", "(", "tag", ",", "bits_per_char", "=", "6", ")", ":", "if", "bits_per_char", "==", "6", ":", "return", "_decode_int64", "(", "tag", ")", "if", "bits_per_char", "==", "4", ":", "return", "_decode_int16", "(", "tag", ")", "if", "bits_p...
Decode string into int assuming encoding with `encode_int()` It is using 2, 4 or 6 bits per coding character (default 6). Parameters: tag: str Encoded integer. bits_per_char: int The number of bits per coding character. Returns: int: the decoded string
[ "Decode", "string", "into", "int", "assuming", "encoding", "with", "encode_int", "()" ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_int2str.py#L52-L71
tammoippen/geohash-hilbert
geohash_hilbert/_hilbert.py
encode
def encode(lng, lat, precision=10, bits_per_char=6): """Encode a lng/lat position as a geohash using a hilbert curve This function encodes a lng/lat coordinate to a geohash of length `precision` on a corresponding a hilbert curve. Each character encodes `bits_per_char` bits per character (allowed are 2...
python
def encode(lng, lat, precision=10, bits_per_char=6): """Encode a lng/lat position as a geohash using a hilbert curve This function encodes a lng/lat coordinate to a geohash of length `precision` on a corresponding a hilbert curve. Each character encodes `bits_per_char` bits per character (allowed are 2...
[ "def", "encode", "(", "lng", ",", "lat", ",", "precision", "=", "10", ",", "bits_per_char", "=", "6", ")", ":", "assert", "_LNG_INTERVAL", "[", "0", "]", "<=", "lng", "<=", "_LNG_INTERVAL", "[", "1", "]", "assert", "_LAT_INTERVAL", "[", "0", "]", "<=...
Encode a lng/lat position as a geohash using a hilbert curve This function encodes a lng/lat coordinate to a geohash of length `precision` on a corresponding a hilbert curve. Each character encodes `bits_per_char` bits per character (allowed are 2, 4 and 6 bits [default 6]). Hence, the geohash encodes ...
[ "Encode", "a", "lng", "/", "lat", "position", "as", "a", "geohash", "using", "a", "hilbert", "curve" ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L41-L76
tammoippen/geohash-hilbert
geohash_hilbert/_hilbert.py
decode
def decode(code, bits_per_char=6): """Decode a geohash on a hilbert curve as a lng/lat position Decodes the geohash `code` as a lng/lat position. It assumes, that the length of `code` corresponds to the precision! And that each character in `code` encodes `bits_per_char` bits. Do not mix geohashes with...
python
def decode(code, bits_per_char=6): """Decode a geohash on a hilbert curve as a lng/lat position Decodes the geohash `code` as a lng/lat position. It assumes, that the length of `code` corresponds to the precision! And that each character in `code` encodes `bits_per_char` bits. Do not mix geohashes with...
[ "def", "decode", "(", "code", ",", "bits_per_char", "=", "6", ")", ":", "assert", "bits_per_char", "in", "(", "2", ",", "4", ",", "6", ")", "if", "len", "(", "code", ")", "==", "0", ":", "return", "0.", ",", "0.", "lng", ",", "lat", ",", "_lng_...
Decode a geohash on a hilbert curve as a lng/lat position Decodes the geohash `code` as a lng/lat position. It assumes, that the length of `code` corresponds to the precision! And that each character in `code` encodes `bits_per_char` bits. Do not mix geohashes with different `bits_per_char`! Param...
[ "Decode", "a", "geohash", "on", "a", "hilbert", "curve", "as", "a", "lng", "/", "lat", "position" ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L79-L100
tammoippen/geohash-hilbert
geohash_hilbert/_hilbert.py
decode_exactly
def decode_exactly(code, bits_per_char=6): """Decode a geohash on a hilbert curve as a lng/lat position with error-margins Decodes the geohash `code` as a lng/lat position with error-margins. It assumes, that the length of `code` corresponds to the precision! And that each character in `code` encodes `...
python
def decode_exactly(code, bits_per_char=6): """Decode a geohash on a hilbert curve as a lng/lat position with error-margins Decodes the geohash `code` as a lng/lat position with error-margins. It assumes, that the length of `code` corresponds to the precision! And that each character in `code` encodes `...
[ "def", "decode_exactly", "(", "code", ",", "bits_per_char", "=", "6", ")", ":", "assert", "bits_per_char", "in", "(", "2", ",", "4", ",", "6", ")", "if", "len", "(", "code", ")", "==", "0", ":", "return", "0.", ",", "0.", ",", "_LNG_INTERVAL", "[",...
Decode a geohash on a hilbert curve as a lng/lat position with error-margins Decodes the geohash `code` as a lng/lat position with error-margins. It assumes, that the length of `code` corresponds to the precision! And that each character in `code` encodes `bits_per_char` bits. Do not mix geohashes with dif...
[ "Decode", "a", "geohash", "on", "a", "hilbert", "curve", "as", "a", "lng", "/", "lat", "position", "with", "error", "-", "margins" ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L103-L136
tammoippen/geohash-hilbert
geohash_hilbert/_hilbert.py
_coord2int
def _coord2int(lng, lat, dim): """Convert lon, lat values into a dim x dim-grid coordinate system. Parameters: lng: float Longitude value of coordinate (-180.0, 180.0); corresponds to X axis lat: float Latitude value of coordinate (-90.0, 90.0); corresponds to Y axis dim: int ...
python
def _coord2int(lng, lat, dim): """Convert lon, lat values into a dim x dim-grid coordinate system. Parameters: lng: float Longitude value of coordinate (-180.0, 180.0); corresponds to X axis lat: float Latitude value of coordinate (-90.0, 90.0); corresponds to Y axis dim: int ...
[ "def", "_coord2int", "(", "lng", ",", "lat", ",", "dim", ")", ":", "assert", "dim", ">=", "1", "lat_y", "=", "(", "lat", "+", "_LAT_INTERVAL", "[", "1", "]", ")", "/", "180.0", "*", "dim", "# [0 ... dim)", "lng_x", "=", "(", "lng", "+", "_LNG_INTER...
Convert lon, lat values into a dim x dim-grid coordinate system. Parameters: lng: float Longitude value of coordinate (-180.0, 180.0); corresponds to X axis lat: float Latitude value of coordinate (-90.0, 90.0); corresponds to Y axis dim: int Number of coding points each x, y val...
[ "Convert", "lon", "lat", "values", "into", "a", "dim", "x", "dim", "-", "grid", "coordinate", "system", "." ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L157-L177
tammoippen/geohash-hilbert
geohash_hilbert/_hilbert.py
_int2coord
def _int2coord(x, y, dim): """Convert x, y values in dim x dim-grid coordinate system into lng, lat values. Parameters: x: int x value of point [0, dim); corresponds to longitude y: int y value of point [0, dim); corresponds to latitude dim: int Number of coding point...
python
def _int2coord(x, y, dim): """Convert x, y values in dim x dim-grid coordinate system into lng, lat values. Parameters: x: int x value of point [0, dim); corresponds to longitude y: int y value of point [0, dim); corresponds to latitude dim: int Number of coding point...
[ "def", "_int2coord", "(", "x", ",", "y", ",", "dim", ")", ":", "assert", "dim", ">=", "1", "assert", "x", "<", "dim", "assert", "y", "<", "dim", "lng", "=", "x", "/", "dim", "*", "360", "-", "180", "lat", "=", "y", "/", "dim", "*", "180", "...
Convert x, y values in dim x dim-grid coordinate system into lng, lat values. Parameters: x: int x value of point [0, dim); corresponds to longitude y: int y value of point [0, dim); corresponds to latitude dim: int Number of coding points each x, y value can take. ...
[ "Convert", "x", "y", "values", "in", "dim", "x", "dim", "-", "grid", "coordinate", "system", "into", "lng", "lat", "values", "." ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L180-L201
tammoippen/geohash-hilbert
geohash_hilbert/_hilbert.py
_xy2hash
def _xy2hash(x, y, dim): """Convert (x, y) to hashcode. Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: x: int x value of point [0, dim) in dim x dim coord system y: int ...
python
def _xy2hash(x, y, dim): """Convert (x, y) to hashcode. Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: x: int x value of point [0, dim) in dim x dim coord system y: int ...
[ "def", "_xy2hash", "(", "x", ",", "y", ",", "dim", ")", ":", "d", "=", "0", "lvl", "=", "dim", ">>", "1", "while", "(", "lvl", ">", "0", ")", ":", "rx", "=", "int", "(", "(", "x", "&", "lvl", ")", ">", "0", ")", "ry", "=", "int", "(", ...
Convert (x, y) to hashcode. Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: x: int x value of point [0, dim) in dim x dim coord system y: int y value of point [0, dim) ...
[ "Convert", "(", "x", "y", ")", "to", "hashcode", "." ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L205-L230
tammoippen/geohash-hilbert
geohash_hilbert/_hilbert.py
_hash2xy
def _hash2xy(hashcode, dim): """Convert hashcode to (x, y). Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: hashcode: int Hashcode to decode [0, dim**2) dim: int Number of...
python
def _hash2xy(hashcode, dim): """Convert hashcode to (x, y). Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: hashcode: int Hashcode to decode [0, dim**2) dim: int Number of...
[ "def", "_hash2xy", "(", "hashcode", ",", "dim", ")", ":", "assert", "(", "hashcode", "<=", "dim", "*", "dim", "-", "1", ")", "x", "=", "y", "=", "0", "lvl", "=", "1", "while", "(", "lvl", "<", "dim", ")", ":", "rx", "=", "1", "&", "(", "has...
Convert hashcode to (x, y). Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: hashcode: int Hashcode to decode [0, dim**2) dim: int Number of coding points each x, y value can t...
[ "Convert", "hashcode", "to", "(", "x", "y", ")", "." ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L233-L260
tammoippen/geohash-hilbert
geohash_hilbert/_hilbert.py
_rotate
def _rotate(n, x, y, rx, ry): """Rotate and flip a quadrant appropriately Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 """ if ry == 0: if rx == 1: x = n - 1 - x y = n - 1 - y return y, x r...
python
def _rotate(n, x, y, rx, ry): """Rotate and flip a quadrant appropriately Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 """ if ry == 0: if rx == 1: x = n - 1 - x y = n - 1 - y return y, x r...
[ "def", "_rotate", "(", "n", ",", "x", ",", "y", ",", "rx", ",", "ry", ")", ":", "if", "ry", "==", "0", ":", "if", "rx", "==", "1", ":", "x", "=", "n", "-", "1", "-", "x", "y", "=", "n", "-", "1", "-", "y", "return", "y", ",", "x", "...
Rotate and flip a quadrant appropriately Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
[ "Rotate", "and", "flip", "a", "quadrant", "appropriately" ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L263-L275
tammoippen/geohash-hilbert
geohash_hilbert/_utils.py
neighbours
def neighbours(code, bits_per_char=6): """Get the neighbouring geohashes for `code`. Look for the north, north-east, east, south-east, south, south-west, west, north-west neighbours. If you are at the east/west edge of the grid (lng ∈ (-180, 180)), then it wraps around the globe and gets the correspond...
python
def neighbours(code, bits_per_char=6): """Get the neighbouring geohashes for `code`. Look for the north, north-east, east, south-east, south, south-west, west, north-west neighbours. If you are at the east/west edge of the grid (lng ∈ (-180, 180)), then it wraps around the globe and gets the correspond...
[ "def", "neighbours", "(", "code", ",", "bits_per_char", "=", "6", ")", ":", "lng", ",", "lat", ",", "lng_err", ",", "lat_err", "=", "decode_exactly", "(", "code", ",", "bits_per_char", ")", "precision", "=", "len", "(", "code", ")", "north", "=", "lat"...
Get the neighbouring geohashes for `code`. Look for the north, north-east, east, south-east, south, south-west, west, north-west neighbours. If you are at the east/west edge of the grid (lng ∈ (-180, 180)), then it wraps around the globe and gets the corresponding neighbor. Parameters: cod...
[ "Get", "the", "neighbouring", "geohashes", "for", "code", "." ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_utils.py#L30-L84
tammoippen/geohash-hilbert
geohash_hilbert/_utils.py
rectangle
def rectangle(code, bits_per_char=6): """Builds a (geojson) rectangle from `code` The center of the rectangle decodes as the lng/lat for code and the rectangle corresponds to the error-margin, i.e. every lng/lat point within this rectangle will be encoded as `code`, given `precision == len(code)`. ...
python
def rectangle(code, bits_per_char=6): """Builds a (geojson) rectangle from `code` The center of the rectangle decodes as the lng/lat for code and the rectangle corresponds to the error-margin, i.e. every lng/lat point within this rectangle will be encoded as `code`, given `precision == len(code)`. ...
[ "def", "rectangle", "(", "code", ",", "bits_per_char", "=", "6", ")", ":", "lng", ",", "lat", ",", "lng_err", ",", "lat_err", "=", "decode_exactly", "(", "code", ",", "bits_per_char", ")", "return", "{", "'type'", ":", "'Feature'", ",", "'properties'", "...
Builds a (geojson) rectangle from `code` The center of the rectangle decodes as the lng/lat for code and the rectangle corresponds to the error-margin, i.e. every lng/lat point within this rectangle will be encoded as `code`, given `precision == len(code)`. Parameters: code: str The ...
[ "Builds", "a", "(", "geojson", ")", "rectangle", "from", "code" ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_utils.py#L87-L129
tammoippen/geohash-hilbert
geohash_hilbert/_utils.py
hilbert_curve
def hilbert_curve(precision, bits_per_char=6): """Build the (geojson) `LineString` of the used hilbert-curve Builds the `LineString` of the used hilbert-curve given the `precision` and the `bits_per_char`. The number of bits to encode the geohash is equal to `precision * bits_per_char`, and for each le...
python
def hilbert_curve(precision, bits_per_char=6): """Build the (geojson) `LineString` of the used hilbert-curve Builds the `LineString` of the used hilbert-curve given the `precision` and the `bits_per_char`. The number of bits to encode the geohash is equal to `precision * bits_per_char`, and for each le...
[ "def", "hilbert_curve", "(", "precision", ",", "bits_per_char", "=", "6", ")", ":", "bits", "=", "precision", "*", "bits_per_char", "coords", "=", "[", "]", "for", "i", "in", "range", "(", "1", "<<", "bits", ")", ":", "code", "=", "encode_int", "(", ...
Build the (geojson) `LineString` of the used hilbert-curve Builds the `LineString` of the used hilbert-curve given the `precision` and the `bits_per_char`. The number of bits to encode the geohash is equal to `precision * bits_per_char`, and for each level, you need 2 bits, hence the number of bits has...
[ "Build", "the", "(", "geojson", ")", "LineString", "of", "the", "used", "hilbert", "-", "curve" ]
train
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_utils.py#L132-L164
cocagne/txdbus
txdbus/objects.py
isSignatureValid
def isSignatureValid(expected, received): """ Verifies that the received signature matches the expected value """ if expected: if not received or expected != received: return False else: if received: return False return True
python
def isSignatureValid(expected, received): """ Verifies that the received signature matches the expected value """ if expected: if not received or expected != received: return False else: if received: return False return True
[ "def", "isSignatureValid", "(", "expected", ",", "received", ")", ":", "if", "expected", ":", "if", "not", "received", "or", "expected", "!=", "received", ":", "return", "False", "else", ":", "if", "received", ":", "return", "False", "return", "True" ]
Verifies that the received signature matches the expected value
[ "Verifies", "that", "the", "received", "signature", "matches", "the", "expected", "value" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L17-L27
cocagne/txdbus
txdbus/objects.py
RemoteDBusObject.notifyOnDisconnect
def notifyOnDisconnect(self, callback): """ Registers a callback that will be called when the DBus connection underlying the remote object is lost @type callback: Callable object accepting a L{RemoteDBusObject} and L{twisted.python.failure.Failure} @param...
python
def notifyOnDisconnect(self, callback): """ Registers a callback that will be called when the DBus connection underlying the remote object is lost @type callback: Callable object accepting a L{RemoteDBusObject} and L{twisted.python.failure.Failure} @param...
[ "def", "notifyOnDisconnect", "(", "self", ",", "callback", ")", ":", "if", "self", ".", "_disconnectCBs", "is", "None", ":", "self", ".", "_disconnectCBs", "=", "[", "]", "self", ".", "_disconnectCBs", ".", "append", "(", "callback", ")" ]
Registers a callback that will be called when the DBus connection underlying the remote object is lost @type callback: Callable object accepting a L{RemoteDBusObject} and L{twisted.python.failure.Failure} @param callback: Function that will be called when the connection ...
[ "Registers", "a", "callback", "that", "will", "be", "called", "when", "the", "DBus", "connection", "underlying", "the", "remote", "object", "is", "lost" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L112-L127
cocagne/txdbus
txdbus/objects.py
RemoteDBusObject.connectionLost
def connectionLost(self, reason): """ Called by the L{DBusObjectHandler} when the connection is lost """ if self._disconnectCBs: for cb in self._disconnectCBs: cb(self, reason)
python
def connectionLost(self, reason): """ Called by the L{DBusObjectHandler} when the connection is lost """ if self._disconnectCBs: for cb in self._disconnectCBs: cb(self, reason)
[ "def", "connectionLost", "(", "self", ",", "reason", ")", ":", "if", "self", ".", "_disconnectCBs", ":", "for", "cb", "in", "self", ".", "_disconnectCBs", ":", "cb", "(", "self", ",", "reason", ")" ]
Called by the L{DBusObjectHandler} when the connection is lost
[ "Called", "by", "the", "L", "{", "DBusObjectHandler", "}", "when", "the", "connection", "is", "lost" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L136-L142
cocagne/txdbus
txdbus/objects.py
RemoteDBusObject.notifyOnSignal
def notifyOnSignal(self, signalName, callback, interface=None): """ Informs the DBus daemon of the process's interest in the specified signal and registers the callback function to be called when the signal arrives. Multiple callbacks may be registered. @type signalName: C{strin...
python
def notifyOnSignal(self, signalName, callback, interface=None): """ Informs the DBus daemon of the process's interest in the specified signal and registers the callback function to be called when the signal arrives. Multiple callbacks may be registered. @type signalName: C{strin...
[ "def", "notifyOnSignal", "(", "self", ",", "signalName", ",", "callback", ",", "interface", "=", "None", ")", ":", "iface", "=", "None", "signal", "=", "None", "for", "i", "in", "self", ".", "interfaces", ":", "if", "interface", "and", "not", "i", ".",...
Informs the DBus daemon of the process's interest in the specified signal and registers the callback function to be called when the signal arrives. Multiple callbacks may be registered. @type signalName: C{string} @param signalName: Name of the signal to register the callback for ...
[ "Informs", "the", "DBus", "daemon", "of", "the", "process", "s", "interest", "in", "the", "specified", "signal", "and", "registers", "the", "callback", "function", "to", "be", "called", "when", "the", "signal", "arrives", ".", "Multiple", "callbacks", "may", ...
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L144-L211
cocagne/txdbus
txdbus/objects.py
RemoteDBusObject.cancelSignalNotification
def cancelSignalNotification(self, rule_id): """ Cancels a callback previously registered with notifyOnSignal """ if self._signalRules and rule_id in self._signalRules: self.objHandler.conn.delMatch(rule_id) self._signalRules.remove(rule_id)
python
def cancelSignalNotification(self, rule_id): """ Cancels a callback previously registered with notifyOnSignal """ if self._signalRules and rule_id in self._signalRules: self.objHandler.conn.delMatch(rule_id) self._signalRules.remove(rule_id)
[ "def", "cancelSignalNotification", "(", "self", ",", "rule_id", ")", ":", "if", "self", ".", "_signalRules", "and", "rule_id", "in", "self", ".", "_signalRules", ":", "self", ".", "objHandler", ".", "conn", ".", "delMatch", "(", "rule_id", ")", "self", "."...
Cancels a callback previously registered with notifyOnSignal
[ "Cancels", "a", "callback", "previously", "registered", "with", "notifyOnSignal" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L213-L219
cocagne/txdbus
txdbus/objects.py
RemoteDBusObject.callRemote
def callRemote(self, methodName, *args, **kwargs): """ Calls the remote method and returns a Deferred instance to the result. DBus does not support passing keyword arguments over the wire. The keyword arguments accepted by this method alter the behavior of the remote call as desc...
python
def callRemote(self, methodName, *args, **kwargs): """ Calls the remote method and returns a Deferred instance to the result. DBus does not support passing keyword arguments over the wire. The keyword arguments accepted by this method alter the behavior of the remote call as desc...
[ "def", "callRemote", "(", "self", ",", "methodName", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "expectReply", "=", "kwargs", ".", "get", "(", "'expectReply'", ",", "True", ")", "autoStart", "=", "kwargs", ".", "get", "(", "'autoStart'", ",",...
Calls the remote method and returns a Deferred instance to the result. DBus does not support passing keyword arguments over the wire. The keyword arguments accepted by this method alter the behavior of the remote call as described in the kwargs prameter description. @type methodName: C{...
[ "Calls", "the", "remote", "method", "and", "returns", "a", "Deferred", "instance", "to", "the", "result", ".", "DBus", "does", "not", "support", "passing", "keyword", "arguments", "over", "the", "wire", ".", "The", "keyword", "arguments", "accepted", "by", "...
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L221-L283
cocagne/txdbus
txdbus/objects.py
DBusObjectHandler.connectionLost
def connectionLost(self, reason): """ Called by the DBus Connection object when the connection is lost. @type reason: L{twistd.python.failure.Failure} @param reason: The value passed to the associated connection's connectionLost method. """ for wre...
python
def connectionLost(self, reason): """ Called by the DBus Connection object when the connection is lost. @type reason: L{twistd.python.failure.Failure} @param reason: The value passed to the associated connection's connectionLost method. """ for wre...
[ "def", "connectionLost", "(", "self", ",", "reason", ")", ":", "for", "wref", "in", "self", ".", "_weakProxies", ".", "valuerefs", "(", ")", ":", "p", "=", "wref", "(", ")", "if", "p", "is", "not", "None", ":", "p", ".", "connectionLost", "(", "rea...
Called by the DBus Connection object when the connection is lost. @type reason: L{twistd.python.failure.Failure} @param reason: The value passed to the associated connection's connectionLost method.
[ "Called", "by", "the", "DBus", "Connection", "object", "when", "the", "connection", "is", "lost", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L649-L660
cocagne/txdbus
txdbus/objects.py
DBusObjectHandler.exportObject
def exportObject(self, dbusObject): """ Makes the specified object available over DBus @type dbusObject: an object implementing the L{IDBusObject} interface @param dbusObject: The object to export over DBus """ o = IDBusObject(dbusObject) self.exports[o.getObject...
python
def exportObject(self, dbusObject): """ Makes the specified object available over DBus @type dbusObject: an object implementing the L{IDBusObject} interface @param dbusObject: The object to export over DBus """ o = IDBusObject(dbusObject) self.exports[o.getObject...
[ "def", "exportObject", "(", "self", ",", "dbusObject", ")", ":", "o", "=", "IDBusObject", "(", "dbusObject", ")", "self", ".", "exports", "[", "o", ".", "getObjectPath", "(", ")", "]", "=", "o", "o", ".", "setObjectHandler", "(", "self", ")", "i", "=...
Makes the specified object available over DBus @type dbusObject: an object implementing the L{IDBusObject} interface @param dbusObject: The object to export over DBus
[ "Makes", "the", "specified", "object", "available", "over", "DBus" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L662-L685
cocagne/txdbus
txdbus/objects.py
DBusObjectHandler.getManagedObjects
def getManagedObjects(self, objectPath): """ Returns a Python dictionary containing the reply content for org.freedesktop.DBus.ObjectManager.GetManagedObjects """ d = {} for p in sorted(self.exports.keys()): if not p.startswith(objectPath) or p == objectPath:...
python
def getManagedObjects(self, objectPath): """ Returns a Python dictionary containing the reply content for org.freedesktop.DBus.ObjectManager.GetManagedObjects """ d = {} for p in sorted(self.exports.keys()): if not p.startswith(objectPath) or p == objectPath:...
[ "def", "getManagedObjects", "(", "self", ",", "objectPath", ")", ":", "d", "=", "{", "}", "for", "p", "in", "sorted", "(", "self", ".", "exports", ".", "keys", "(", ")", ")", ":", "if", "not", "p", ".", "startswith", "(", "objectPath", ")", "or", ...
Returns a Python dictionary containing the reply content for org.freedesktop.DBus.ObjectManager.GetManagedObjects
[ "Returns", "a", "Python", "dictionary", "containing", "the", "reply", "content", "for", "org", ".", "freedesktop", ".", "DBus", ".", "ObjectManager", ".", "GetManagedObjects" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L708-L724
cocagne/txdbus
txdbus/objects.py
DBusObjectHandler._send_err
def _send_err(self, msg, errName, errMsg): """ Helper method for sending error messages """ r = message.ErrorMessage( errName, msg.serial, body=[errMsg], signature='s', destination=msg.sender, ) self.conn.sendMe...
python
def _send_err(self, msg, errName, errMsg): """ Helper method for sending error messages """ r = message.ErrorMessage( errName, msg.serial, body=[errMsg], signature='s', destination=msg.sender, ) self.conn.sendMe...
[ "def", "_send_err", "(", "self", ",", "msg", ",", "errName", ",", "errMsg", ")", ":", "r", "=", "message", ".", "ErrorMessage", "(", "errName", ",", "msg", ".", "serial", ",", "body", "=", "[", "errMsg", "]", ",", "signature", "=", "'s'", ",", "des...
Helper method for sending error messages
[ "Helper", "method", "for", "sending", "error", "messages" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L726-L738
cocagne/txdbus
txdbus/objects.py
DBusObjectHandler.handleMethodCallMessage
def handleMethodCallMessage(self, msg): """ Handles DBus MethodCall messages on behalf of the DBus Connection and dispatches them to the appropriate exported object """ if ( msg.interface == 'org.freedesktop.DBus.Peer' and msg.member == 'Ping' ): ...
python
def handleMethodCallMessage(self, msg): """ Handles DBus MethodCall messages on behalf of the DBus Connection and dispatches them to the appropriate exported object """ if ( msg.interface == 'org.freedesktop.DBus.Peer' and msg.member == 'Ping' ): ...
[ "def", "handleMethodCallMessage", "(", "self", ",", "msg", ")", ":", "if", "(", "msg", ".", "interface", "==", "'org.freedesktop.DBus.Peer'", "and", "msg", ".", "member", "==", "'Ping'", ")", ":", "r", "=", "message", ".", "MethodReturnMessage", "(", "msg", ...
Handles DBus MethodCall messages on behalf of the DBus Connection and dispatches them to the appropriate exported object
[ "Handles", "DBus", "MethodCall", "messages", "on", "behalf", "of", "the", "DBus", "Connection", "and", "dispatches", "them", "to", "the", "appropriate", "exported", "object" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L740-L896
cocagne/txdbus
txdbus/objects.py
DBusObjectHandler.getRemoteObject
def getRemoteObject(self, busName, objectPath, interfaces=None, replaceKnownInterfaces=False): """ Creates a L{RemoteDBusObject} instance to represent the specified DBus object. If explicit interfaces are not supplied, DBus object introspection will be used to ob...
python
def getRemoteObject(self, busName, objectPath, interfaces=None, replaceKnownInterfaces=False): """ Creates a L{RemoteDBusObject} instance to represent the specified DBus object. If explicit interfaces are not supplied, DBus object introspection will be used to ob...
[ "def", "getRemoteObject", "(", "self", ",", "busName", ",", "objectPath", ",", "interfaces", "=", "None", ",", "replaceKnownInterfaces", "=", "False", ")", ":", "weak_id", "=", "(", "busName", ",", "objectPath", ",", "interfaces", ")", "need_introspection", "=...
Creates a L{RemoteDBusObject} instance to represent the specified DBus object. If explicit interfaces are not supplied, DBus object introspection will be used to obtain them automatically. @type busName: C{string} @param busName: Name of the bus exporting the desired object ...
[ "Creates", "a", "L", "{", "RemoteDBusObject", "}", "instance", "to", "represent", "the", "specified", "DBus", "object", ".", "If", "explicit", "interfaces", "are", "not", "supplied", "DBus", "object", "introspection", "will", "be", "used", "to", "obtain", "the...
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L898-L984
cocagne/txdbus
txdbus/interface.py
DBusInterface.addMethod
def addMethod(self, m): """ Adds a L{Method} to the interface """ if m.nargs == -1: m.nargs = len([a for a in marshal.genCompleteTypes(m.sigIn)]) m.nret = len([a for a in marshal.genCompleteTypes(m.sigOut)]) self.methods[m.name] = m self._xml = Non...
python
def addMethod(self, m): """ Adds a L{Method} to the interface """ if m.nargs == -1: m.nargs = len([a for a in marshal.genCompleteTypes(m.sigIn)]) m.nret = len([a for a in marshal.genCompleteTypes(m.sigOut)]) self.methods[m.name] = m self._xml = Non...
[ "def", "addMethod", "(", "self", ",", "m", ")", ":", "if", "m", ".", "nargs", "==", "-", "1", ":", "m", ".", "nargs", "=", "len", "(", "[", "a", "for", "a", "in", "marshal", ".", "genCompleteTypes", "(", "m", ".", "sigIn", ")", "]", ")", "m",...
Adds a L{Method} to the interface
[ "Adds", "a", "L", "{", "Method", "}", "to", "the", "interface" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/interface.py#L162-L170
cocagne/txdbus
txdbus/interface.py
DBusInterface.addSignal
def addSignal(self, s): """ Adds a L{Signal} to the interface """ if s.nargs == -1: s.nargs = len([a for a in marshal.genCompleteTypes(s.sig)]) self.signals[s.name] = s self._xml = None
python
def addSignal(self, s): """ Adds a L{Signal} to the interface """ if s.nargs == -1: s.nargs = len([a for a in marshal.genCompleteTypes(s.sig)]) self.signals[s.name] = s self._xml = None
[ "def", "addSignal", "(", "self", ",", "s", ")", ":", "if", "s", ".", "nargs", "==", "-", "1", ":", "s", ".", "nargs", "=", "len", "(", "[", "a", "for", "a", "in", "marshal", ".", "genCompleteTypes", "(", "s", ".", "sig", ")", "]", ")", "self"...
Adds a L{Signal} to the interface
[ "Adds", "a", "L", "{", "Signal", "}", "to", "the", "interface" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/interface.py#L172-L179
cocagne/txdbus
txdbus/client.py
connect
def connect(reactor, busAddress='session'): """ Connects to the specified bus and returns a L{twisted.internet.defer.Deferred} to the fully-connected L{DBusClientConnection}. @param reactor: L{twisted.internet.interfaces.IReactor} implementor @param busAddress: 'session', 'system', or a valid ...
python
def connect(reactor, busAddress='session'): """ Connects to the specified bus and returns a L{twisted.internet.defer.Deferred} to the fully-connected L{DBusClientConnection}. @param reactor: L{twisted.internet.interfaces.IReactor} implementor @param busAddress: 'session', 'system', or a valid ...
[ "def", "connect", "(", "reactor", ",", "busAddress", "=", "'session'", ")", ":", "from", "txdbus", "import", "endpoints", "f", "=", "DBusClientFactory", "(", ")", "d", "=", "f", ".", "getConnection", "(", ")", "eplist", "=", "endpoints", ".", "getDBusEndpo...
Connects to the specified bus and returns a L{twisted.internet.defer.Deferred} to the fully-connected L{DBusClientConnection}. @param reactor: L{twisted.internet.interfaces.IReactor} implementor @param busAddress: 'session', 'system', or a valid bus address as defined by the DBus specification...
[ "Connects", "to", "the", "specified", "bus", "and", "returns", "a", "L", "{", "twisted", ".", "internet", ".", "defer", ".", "Deferred", "}", "to", "the", "fully", "-", "connected", "L", "{", "DBusClientConnection", "}", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L671-L726
cocagne/txdbus
txdbus/client.py
DBusClientConnection.connectionAuthenticated
def connectionAuthenticated(self): """ Called by L{protocol.BasicDBusProtocol} when the DBus authentication has completed successfully. """ self.router = router.MessageRouter() self.match_rules = {} self.objHandler = objects.DBusObjectHandler(self) # seria...
python
def connectionAuthenticated(self): """ Called by L{protocol.BasicDBusProtocol} when the DBus authentication has completed successfully. """ self.router = router.MessageRouter() self.match_rules = {} self.objHandler = objects.DBusObjectHandler(self) # seria...
[ "def", "connectionAuthenticated", "(", "self", ")", ":", "self", ".", "router", "=", "router", ".", "MessageRouter", "(", ")", "self", ".", "match_rules", "=", "{", "}", "self", ".", "objHandler", "=", "objects", ".", "DBusObjectHandler", "(", "self", ")",...
Called by L{protocol.BasicDBusProtocol} when the DBus authentication has completed successfully.
[ "Called", "by", "L", "{", "protocol", ".", "BasicDBusProtocol", "}", "when", "the", "DBus", "authentication", "has", "completed", "successfully", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L57-L79
cocagne/txdbus
txdbus/client.py
DBusClientConnection._cbGotHello
def _cbGotHello(self, busName): """ Called in reply to the initial Hello remote method invocation """ self.busName = busName # print 'Connection Bus Name = ', self.busName self.factory._ok(self)
python
def _cbGotHello(self, busName): """ Called in reply to the initial Hello remote method invocation """ self.busName = busName # print 'Connection Bus Name = ', self.busName self.factory._ok(self)
[ "def", "_cbGotHello", "(", "self", ",", "busName", ")", ":", "self", ".", "busName", "=", "busName", "# print 'Connection Bus Name = ', self.busName", "self", ".", "factory", ".", "_ok", "(", "self", ")" ]
Called in reply to the initial Hello remote method invocation
[ "Called", "in", "reply", "to", "the", "initial", "Hello", "remote", "method", "invocation" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L81-L89
cocagne/txdbus
txdbus/client.py
DBusClientConnection.connectionLost
def connectionLost(self, reason): """ Called when the transport loses connection to the bus """ if self.busName is None: return for cb in self._dcCallbacks: cb(self, reason) for d, timeout in self._pendingCalls.values(): if timeout: ...
python
def connectionLost(self, reason): """ Called when the transport loses connection to the bus """ if self.busName is None: return for cb in self._dcCallbacks: cb(self, reason) for d, timeout in self._pendingCalls.values(): if timeout: ...
[ "def", "connectionLost", "(", "self", ",", "reason", ")", ":", "if", "self", ".", "busName", "is", "None", ":", "return", "for", "cb", "in", "self", ".", "_dcCallbacks", ":", "cb", "(", "self", ",", "reason", ")", "for", "d", ",", "timeout", "in", ...
Called when the transport loses connection to the bus
[ "Called", "when", "the", "transport", "loses", "connection", "to", "the", "bus" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L97-L113
cocagne/txdbus
txdbus/client.py
DBusClientConnection.getRemoteObject
def getRemoteObject(self, busName, objectPath, interfaces=None, replaceKnownInterfaces=False): """ Creates a L{objects.RemoteDBusObject} instance to represent the specified DBus object. If explicit interfaces are not supplied, DBus object introspection will be us...
python
def getRemoteObject(self, busName, objectPath, interfaces=None, replaceKnownInterfaces=False): """ Creates a L{objects.RemoteDBusObject} instance to represent the specified DBus object. If explicit interfaces are not supplied, DBus object introspection will be us...
[ "def", "getRemoteObject", "(", "self", ",", "busName", ",", "objectPath", ",", "interfaces", "=", "None", ",", "replaceKnownInterfaces", "=", "False", ")", ":", "return", "self", ".", "objHandler", ".", "getRemoteObject", "(", "busName", ",", "objectPath", ","...
Creates a L{objects.RemoteDBusObject} instance to represent the specified DBus object. If explicit interfaces are not supplied, DBus object introspection will be used to obtain them automatically. @param interfaces: May be None, a single value, or a list of string in...
[ "Creates", "a", "L", "{", "objects", ".", "RemoteDBusObject", "}", "instance", "to", "represent", "the", "specified", "DBus", "object", ".", "If", "explicit", "interfaces", "are", "not", "supplied", "DBus", "object", "introspection", "will", "be", "used", "to"...
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L153-L178
cocagne/txdbus
txdbus/client.py
DBusClientConnection.delMatch
def delMatch(self, rule_id): """ Removes a message matching rule previously registered with addMatch """ rule = self.match_rules[rule_id] d = self.callRemote( '/org/freedesktop/DBus', 'RemoveMatch', interface='org.freedesktop.DBus', ...
python
def delMatch(self, rule_id): """ Removes a message matching rule previously registered with addMatch """ rule = self.match_rules[rule_id] d = self.callRemote( '/org/freedesktop/DBus', 'RemoveMatch', interface='org.freedesktop.DBus', ...
[ "def", "delMatch", "(", "self", ",", "rule_id", ")", ":", "rule", "=", "self", ".", "match_rules", "[", "rule_id", "]", "d", "=", "self", ".", "callRemote", "(", "'/org/freedesktop/DBus'", ",", "'RemoveMatch'", ",", "interface", "=", "'org.freedesktop.DBus'", ...
Removes a message matching rule previously registered with addMatch
[ "Removes", "a", "message", "matching", "rule", "previously", "registered", "with", "addMatch" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L180-L201
cocagne/txdbus
txdbus/client.py
DBusClientConnection.addMatch
def addMatch(self, callback, mtype=None, sender=None, interface=None, member=None, path=None, path_namespace=None, destination=None, arg=None, arg_path=None, arg0namespace=None): """ Creates a message matching rule, associates it with the specified callback func...
python
def addMatch(self, callback, mtype=None, sender=None, interface=None, member=None, path=None, path_namespace=None, destination=None, arg=None, arg_path=None, arg0namespace=None): """ Creates a message matching rule, associates it with the specified callback func...
[ "def", "addMatch", "(", "self", ",", "callback", ",", "mtype", "=", "None", ",", "sender", "=", "None", ",", "interface", "=", "None", ",", "member", "=", "None", ",", "path", "=", "None", ",", "path_namespace", "=", "None", ",", "destination", "=", ...
Creates a message matching rule, associates it with the specified callback function, and sends the match rule to the DBus daemon. The arguments to this function are exactly follow the DBus specification. Refer to the \"Message Bus Message Routing\" section of the DBus specification for ...
[ "Creates", "a", "message", "matching", "rule", "associates", "it", "with", "the", "specified", "callback", "function", "and", "sends", "the", "match", "rule", "to", "the", "DBus", "daemon", ".", "The", "arguments", "to", "this", "function", "are", "exactly", ...
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L203-L272
cocagne/txdbus
txdbus/client.py
DBusClientConnection.getNameOwner
def getNameOwner(self, busName): """ Calls org.freedesktop.DBus.GetNameOwner @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred to the unique connection name owning the bus name """ d = self.callRemote( '/org/freedesktop/DBus', 'GetNam...
python
def getNameOwner(self, busName): """ Calls org.freedesktop.DBus.GetNameOwner @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred to the unique connection name owning the bus name """ d = self.callRemote( '/org/freedesktop/DBus', 'GetNam...
[ "def", "getNameOwner", "(", "self", ",", "busName", ")", ":", "d", "=", "self", ".", "callRemote", "(", "'/org/freedesktop/DBus'", ",", "'GetNameOwner'", ",", "interface", "=", "'org.freedesktop.DBus'", ",", "signature", "=", "'s'", ",", "body", "=", "[", "b...
Calls org.freedesktop.DBus.GetNameOwner @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred to the unique connection name owning the bus name
[ "Calls", "org", ".", "freedesktop", ".", "DBus", ".", "GetNameOwner" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L274-L288
cocagne/txdbus
txdbus/client.py
DBusClientConnection.requestBusName
def requestBusName(self, newName, allowReplacement=False, replaceExisting=False, doNotQueue=True, errbackUnlessAcquired=True): """ Calls org.freedesktop.DBus.RequestName to request that the specified bus ...
python
def requestBusName(self, newName, allowReplacement=False, replaceExisting=False, doNotQueue=True, errbackUnlessAcquired=True): """ Calls org.freedesktop.DBus.RequestName to request that the specified bus ...
[ "def", "requestBusName", "(", "self", ",", "newName", ",", "allowReplacement", "=", "False", ",", "replaceExisting", "=", "False", ",", "doNotQueue", "=", "True", ",", "errbackUnlessAcquired", "=", "True", ")", ":", "flags", "=", "0", "if", "allowReplacement",...
Calls org.freedesktop.DBus.RequestName to request that the specified bus name be associated with the connection. @type newName: C{string} @param newName: Bus name to acquire @type allowReplacement: C{bool} @param allowReplacement: If True (defaults to False) and another ...
[ "Calls", "org", ".", "freedesktop", ".", "DBus", ".", "RequestName", "to", "request", "that", "the", "specified", "bus", "name", "be", "associated", "with", "the", "connection", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L342-L404
cocagne/txdbus
txdbus/client.py
DBusClientConnection.introspectRemoteObject
def introspectRemoteObject(self, busName, objectPath, replaceKnownInterfaces=False): """ Calls org.freedesktop.DBus.Introspectable.Introspect @type busName: C{string} @param busName: Name of the bus containing the object @type objectPath: C{string...
python
def introspectRemoteObject(self, busName, objectPath, replaceKnownInterfaces=False): """ Calls org.freedesktop.DBus.Introspectable.Introspect @type busName: C{string} @param busName: Name of the bus containing the object @type objectPath: C{string...
[ "def", "introspectRemoteObject", "(", "self", ",", "busName", ",", "objectPath", ",", "replaceKnownInterfaces", "=", "False", ")", ":", "d", "=", "self", ".", "callRemote", "(", "objectPath", ",", "'Introspect'", ",", "interface", "=", "'org.freedesktop.DBus.Intro...
Calls org.freedesktop.DBus.Introspectable.Introspect @type busName: C{string} @param busName: Name of the bus containing the object @type objectPath: C{string} @param objectPath: Object Path to introspect @type replaceKnownInterfaces: C{bool} @param replaceKnownInterfa...
[ "Calls", "org", ".", "freedesktop", ".", "DBus", ".", "Introspectable", ".", "Introspect" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L406-L447
cocagne/txdbus
txdbus/client.py
DBusClientConnection._cbCvtReply
def _cbCvtReply(self, msg, returnSignature): """ Converts a remote method call reply message into an appropriate callback value. """ if msg is None: return None if returnSignature != _NO_CHECK_RETURN: if not returnSignature: ...
python
def _cbCvtReply(self, msg, returnSignature): """ Converts a remote method call reply message into an appropriate callback value. """ if msg is None: return None if returnSignature != _NO_CHECK_RETURN: if not returnSignature: ...
[ "def", "_cbCvtReply", "(", "self", ",", "msg", ",", "returnSignature", ")", ":", "if", "msg", "is", "None", ":", "return", "None", "if", "returnSignature", "!=", "_NO_CHECK_RETURN", ":", "if", "not", "returnSignature", ":", "if", "msg", ".", "signature", "...
Converts a remote method call reply message into an appropriate callback value.
[ "Converts", "a", "remote", "method", "call", "reply", "message", "into", "an", "appropriate", "callback", "value", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L449-L482
cocagne/txdbus
txdbus/client.py
DBusClientConnection.callRemote
def callRemote(self, objectPath, methodName, interface=None, destination=None, signature=None, body=None, expectReply=True, autoStart=True, timeout=None, returnSignatur...
python
def callRemote(self, objectPath, methodName, interface=None, destination=None, signature=None, body=None, expectReply=True, autoStart=True, timeout=None, returnSignatur...
[ "def", "callRemote", "(", "self", ",", "objectPath", ",", "methodName", ",", "interface", "=", "None", ",", "destination", "=", "None", ",", "signature", "=", "None", ",", "body", "=", "None", ",", "expectReply", "=", "True", ",", "autoStart", "=", "True...
Calls a method on a remote DBus object and returns a deferred to the result. @type objectPath: C{string} @param objectPath: Path of the remote object @type methodName: C{string} @param methodName: Name of the method to call @type interface: None or C{string} @p...
[ "Calls", "a", "method", "on", "a", "remote", "DBus", "object", "and", "returns", "a", "deferred", "to", "the", "result", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L484-L568
cocagne/txdbus
txdbus/client.py
DBusClientConnection._onMethodTimeout
def _onMethodTimeout(self, serial, d): """ Called when a remote method invocation timeout occurs """ del self._pendingCalls[serial] d.errback(error.TimeOut('Method call timed out'))
python
def _onMethodTimeout(self, serial, d): """ Called when a remote method invocation timeout occurs """ del self._pendingCalls[serial] d.errback(error.TimeOut('Method call timed out'))
[ "def", "_onMethodTimeout", "(", "self", ",", "serial", ",", "d", ")", ":", "del", "self", ".", "_pendingCalls", "[", "serial", "]", "d", ".", "errback", "(", "error", ".", "TimeOut", "(", "'Method call timed out'", ")", ")" ]
Called when a remote method invocation timeout occurs
[ "Called", "when", "a", "remote", "method", "invocation", "timeout", "occurs" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L570-L575
cocagne/txdbus
txdbus/client.py
DBusClientConnection.callRemoteMessage
def callRemoteMessage(self, mcall, timeout=None): """ Uses the specified L{message.MethodCallMessage} to call a remote method @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred to the result of the remote method call """ assert isinstance(mcall, message.Meth...
python
def callRemoteMessage(self, mcall, timeout=None): """ Uses the specified L{message.MethodCallMessage} to call a remote method @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred to the result of the remote method call """ assert isinstance(mcall, message.Meth...
[ "def", "callRemoteMessage", "(", "self", ",", "mcall", ",", "timeout", "=", "None", ")", ":", "assert", "isinstance", "(", "mcall", ",", "message", ".", "MethodCallMessage", ")", "if", "mcall", ".", "expectReply", ":", "d", "=", "defer", ".", "Deferred", ...
Uses the specified L{message.MethodCallMessage} to call a remote method @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred to the result of the remote method call
[ "Uses", "the", "specified", "L", "{", "message", ".", "MethodCallMessage", "}", "to", "call", "a", "remote", "method" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L577-L601
cocagne/txdbus
txdbus/client.py
DBusClientConnection.methodReturnReceived
def methodReturnReceived(self, mret): """ Called when a method return message is received """ d, timeout = self._pendingCalls.get(mret.reply_serial, (None, None)) if timeout: timeout.cancel() if d: del self._pendingCalls[mret.reply_serial] ...
python
def methodReturnReceived(self, mret): """ Called when a method return message is received """ d, timeout = self._pendingCalls.get(mret.reply_serial, (None, None)) if timeout: timeout.cancel() if d: del self._pendingCalls[mret.reply_serial] ...
[ "def", "methodReturnReceived", "(", "self", ",", "mret", ")", ":", "d", ",", "timeout", "=", "self", ".", "_pendingCalls", ".", "get", "(", "mret", ".", "reply_serial", ",", "(", "None", ",", "None", ")", ")", "if", "timeout", ":", "timeout", ".", "c...
Called when a method return message is received
[ "Called", "when", "a", "method", "return", "message", "is", "received" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L609-L618
cocagne/txdbus
txdbus/client.py
DBusClientConnection.errorReceived
def errorReceived(self, merr): """ Called when an error message is received """ d, timeout = self._pendingCalls.get(merr.reply_serial, (None, None)) if timeout: timeout.cancel() if d: del self._pendingCalls[merr.reply_serial] e = error....
python
def errorReceived(self, merr): """ Called when an error message is received """ d, timeout = self._pendingCalls.get(merr.reply_serial, (None, None)) if timeout: timeout.cancel() if d: del self._pendingCalls[merr.reply_serial] e = error....
[ "def", "errorReceived", "(", "self", ",", "merr", ")", ":", "d", ",", "timeout", "=", "self", ".", "_pendingCalls", ".", "get", "(", "merr", ".", "reply_serial", ",", "(", "None", ",", "None", ")", ")", "if", "timeout", ":", "timeout", ".", "cancel",...
Called when an error message is received
[ "Called", "when", "an", "error", "message", "is", "received" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L620-L636
cocagne/txdbus
txdbus/endpoints.py
getDBusEnvEndpoints
def getDBusEnvEndpoints(reactor, client=True): """ Creates endpoints from the DBUS_SESSION_BUS_ADDRESS environment variable @rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint} @returns: A list of endpoint instances """ env = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None) ...
python
def getDBusEnvEndpoints(reactor, client=True): """ Creates endpoints from the DBUS_SESSION_BUS_ADDRESS environment variable @rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint} @returns: A list of endpoint instances """ env = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None) ...
[ "def", "getDBusEnvEndpoints", "(", "reactor", ",", "client", "=", "True", ")", ":", "env", "=", "os", ".", "environ", ".", "get", "(", "'DBUS_SESSION_BUS_ADDRESS'", ",", "None", ")", "if", "env", "is", "None", ":", "raise", "Exception", "(", "'DBus Session...
Creates endpoints from the DBUS_SESSION_BUS_ADDRESS environment variable @rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint} @returns: A list of endpoint instances
[ "Creates", "endpoints", "from", "the", "DBUS_SESSION_BUS_ADDRESS", "environment", "variable" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/endpoints.py#L16-L27
cocagne/txdbus
txdbus/endpoints.py
getDBusEndpoints
def getDBusEndpoints(reactor, busAddress, client=True): """ Creates DBus endpoints. @param busAddress: 'session', 'system', or a valid bus address as defined by the DBus specification. If 'session' (the default) or 'system' is supplied, the contents of the DBUS_SESSION_BUS_ADDRESS or ...
python
def getDBusEndpoints(reactor, busAddress, client=True): """ Creates DBus endpoints. @param busAddress: 'session', 'system', or a valid bus address as defined by the DBus specification. If 'session' (the default) or 'system' is supplied, the contents of the DBUS_SESSION_BUS_ADDRESS or ...
[ "def", "getDBusEndpoints", "(", "reactor", ",", "busAddress", ",", "client", "=", "True", ")", ":", "if", "busAddress", "==", "'session'", ":", "addrString", "=", "os", ".", "environ", ".", "get", "(", "'DBUS_SESSION_BUS_ADDRESS'", ",", "None", ")", "if", ...
Creates DBus endpoints. @param busAddress: 'session', 'system', or a valid bus address as defined by the DBus specification. If 'session' (the default) or 'system' is supplied, the contents of the DBUS_SESSION_BUS_ADDRESS or DBUS_SYSTEM_BUS_ADDRESS environment variables will be used for the...
[ "Creates", "DBus", "endpoints", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/endpoints.py#L30-L113
cocagne/txdbus
txdbus/marshal.py
validateObjectPath
def validateObjectPath(p): """ Ensures that the provided object path conforms to the DBus standard. Throws a L{error.MarshallingError} if non-conformant @type p: C{string} @param p: A DBus object path """ if not p.startswith('/'): raise MarshallingError('Object paths must begin with...
python
def validateObjectPath(p): """ Ensures that the provided object path conforms to the DBus standard. Throws a L{error.MarshallingError} if non-conformant @type p: C{string} @param p: A DBus object path """ if not p.startswith('/'): raise MarshallingError('Object paths must begin with...
[ "def", "validateObjectPath", "(", "p", ")", ":", "if", "not", "p", ".", "startswith", "(", "'/'", ")", ":", "raise", "MarshallingError", "(", "'Object paths must begin with a \"/\"'", ")", "if", "len", "(", "p", ")", ">", "1", "and", "p", "[", "-", "1", ...
Ensures that the provided object path conforms to the DBus standard. Throws a L{error.MarshallingError} if non-conformant @type p: C{string} @param p: A DBus object path
[ "Ensures", "that", "the", "provided", "object", "path", "conforms", "to", "the", "DBus", "standard", ".", "Throws", "a", "L", "{", "error", ".", "MarshallingError", "}", "if", "non", "-", "conformant" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/marshal.py#L138-L153
cocagne/txdbus
txdbus/marshal.py
validateInterfaceName
def validateInterfaceName(n): """ Verifies that the supplied name is a valid DBus Interface name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus interface name """ try: if '.' not in n: raise Exception('At least two compo...
python
def validateInterfaceName(n): """ Verifies that the supplied name is a valid DBus Interface name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus interface name """ try: if '.' not in n: raise Exception('At least two compo...
[ "def", "validateInterfaceName", "(", "n", ")", ":", "try", ":", "if", "'.'", "not", "in", "n", ":", "raise", "Exception", "(", "'At least two components required'", ")", "if", "'..'", "in", "n", ":", "raise", "Exception", "(", "'\"..\" not allowed in interface n...
Verifies that the supplied name is a valid DBus Interface name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus interface name
[ "Verifies", "that", "the", "supplied", "name", "is", "a", "valid", "DBus", "Interface", "name", ".", "Throws", "an", "L", "{", "error", ".", "MarshallingError", "}", "if", "the", "format", "is", "invalid" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/marshal.py#L156-L182
cocagne/txdbus
txdbus/marshal.py
validateBusName
def validateBusName(n): """ Verifies that the supplied name is a valid DBus Bus name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus bus name """ try: if '.' not in n: raise Exception('At least two components required') ...
python
def validateBusName(n): """ Verifies that the supplied name is a valid DBus Bus name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus bus name """ try: if '.' not in n: raise Exception('At least two components required') ...
[ "def", "validateBusName", "(", "n", ")", ":", "try", ":", "if", "'.'", "not", "in", "n", ":", "raise", "Exception", "(", "'At least two components required'", ")", "if", "'..'", "in", "n", ":", "raise", "Exception", "(", "'\"..\" not allowed in bus names'", ")...
Verifies that the supplied name is a valid DBus Bus name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus bus name
[ "Verifies", "that", "the", "supplied", "name", "is", "a", "valid", "DBus", "Bus", "name", ".", "Throws", "an", "L", "{", "error", ".", "MarshallingError", "}", "if", "the", "format", "is", "invalid" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/marshal.py#L192-L218
cocagne/txdbus
txdbus/marshal.py
validateMemberName
def validateMemberName(n): """ Verifies that the supplied name is a valid DBus member name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus member name """ try: if len(n) < 1: raise Exception('Name must be at least one byt...
python
def validateMemberName(n): """ Verifies that the supplied name is a valid DBus member name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus member name """ try: if len(n) < 1: raise Exception('Name must be at least one byt...
[ "def", "validateMemberName", "(", "n", ")", ":", "try", ":", "if", "len", "(", "n", ")", "<", "1", ":", "raise", "Exception", "(", "'Name must be at least one byte in length'", ")", "if", "len", "(", "n", ")", ">", "255", ":", "raise", "Exception", "(", ...
Verifies that the supplied name is a valid DBus member name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus member name
[ "Verifies", "that", "the", "supplied", "name", "is", "a", "valid", "DBus", "member", "name", ".", "Throws", "an", "L", "{", "error", ".", "MarshallingError", "}", "if", "the", "format", "is", "invalid" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/marshal.py#L221-L240
cocagne/txdbus
doc/examples/fd_server.py
FDObject.dbus_lenFD
def dbus_lenFD(self, fd): """ Returns the byte count after reading till EOF. """ f = os.fdopen(fd, 'rb') result = len(f.read()) f.close() return result
python
def dbus_lenFD(self, fd): """ Returns the byte count after reading till EOF. """ f = os.fdopen(fd, 'rb') result = len(f.read()) f.close() return result
[ "def", "dbus_lenFD", "(", "self", ",", "fd", ")", ":", "f", "=", "os", ".", "fdopen", "(", "fd", ",", "'rb'", ")", "result", "=", "len", "(", "f", ".", "read", "(", ")", ")", "f", ".", "close", "(", ")", "return", "result" ]
Returns the byte count after reading till EOF.
[ "Returns", "the", "byte", "count", "after", "reading", "till", "EOF", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/doc/examples/fd_server.py#L46-L53
cocagne/txdbus
doc/examples/fd_server.py
FDObject.dbus_readBytesFD
def dbus_readBytesFD(self, fd, byte_count): """ Reads byte_count bytes from fd and returns them. """ f = os.fdopen(fd, 'rb') result = f.read(byte_count) f.close() return bytearray(result)
python
def dbus_readBytesFD(self, fd, byte_count): """ Reads byte_count bytes from fd and returns them. """ f = os.fdopen(fd, 'rb') result = f.read(byte_count) f.close() return bytearray(result)
[ "def", "dbus_readBytesFD", "(", "self", ",", "fd", ",", "byte_count", ")", ":", "f", "=", "os", ".", "fdopen", "(", "fd", ",", "'rb'", ")", "result", "=", "f", ".", "read", "(", "byte_count", ")", "f", ".", "close", "(", ")", "return", "bytearray",...
Reads byte_count bytes from fd and returns them.
[ "Reads", "byte_count", "bytes", "from", "fd", "and", "returns", "them", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/doc/examples/fd_server.py#L56-L63
cocagne/txdbus
doc/examples/fd_server.py
FDObject.dbus_readBytesTwoFDs
def dbus_readBytesTwoFDs(self, fd1, fd2, byte_count): """ Reads byte_count from fd1 and fd2. Returns concatenation. """ result = bytearray() for fd in (fd1, fd2): f = os.fdopen(fd, 'rb') result.extend(f.read(byte_count)) f.close() retur...
python
def dbus_readBytesTwoFDs(self, fd1, fd2, byte_count): """ Reads byte_count from fd1 and fd2. Returns concatenation. """ result = bytearray() for fd in (fd1, fd2): f = os.fdopen(fd, 'rb') result.extend(f.read(byte_count)) f.close() retur...
[ "def", "dbus_readBytesTwoFDs", "(", "self", ",", "fd1", ",", "fd2", ",", "byte_count", ")", ":", "result", "=", "bytearray", "(", ")", "for", "fd", "in", "(", "fd1", ",", "fd2", ")", ":", "f", "=", "os", ".", "fdopen", "(", "fd", ",", "'rb'", ")"...
Reads byte_count from fd1 and fd2. Returns concatenation.
[ "Reads", "byte_count", "from", "fd1", "and", "fd2", ".", "Returns", "concatenation", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/doc/examples/fd_server.py#L66-L75
cocagne/txdbus
txdbus/introspection.py
generateIntrospectionXML
def generateIntrospectionXML(objectPath, exportedObjects): """ Generates the introspection XML for an object path or partial object path that matches exported objects. This allows for browsing the exported objects with tools such as d-feet. @rtype: C{string} """ l = [_dtd_decl] l.appen...
python
def generateIntrospectionXML(objectPath, exportedObjects): """ Generates the introspection XML for an object path or partial object path that matches exported objects. This allows for browsing the exported objects with tools such as d-feet. @rtype: C{string} """ l = [_dtd_decl] l.appen...
[ "def", "generateIntrospectionXML", "(", "objectPath", ",", "exportedObjects", ")", ":", "l", "=", "[", "_dtd_decl", "]", "l", ".", "append", "(", "'<node name=\"%s\">'", "%", "(", "objectPath", ",", ")", ")", "obj", "=", "exportedObjects", ".", "get", "(", ...
Generates the introspection XML for an object path or partial object path that matches exported objects. This allows for browsing the exported objects with tools such as d-feet. @rtype: C{string}
[ "Generates", "the", "introspection", "XML", "for", "an", "object", "path", "or", "partial", "object", "path", "that", "matches", "exported", "objects", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/introspection.py#L34-L70
cocagne/txdbus
txdbus/introspection.py
getInterfacesFromXML
def getInterfacesFromXML(xmlStr, replaceKnownInterfaces=False): """ Parses the supplied Introspection XML string and returns a list of L{interface.DBusInerface} instances representing the XML interface definitions. @type replaceKnownInterfaces: C{bool} @param replaceKnownInterfaces: If true, pr...
python
def getInterfacesFromXML(xmlStr, replaceKnownInterfaces=False): """ Parses the supplied Introspection XML string and returns a list of L{interface.DBusInerface} instances representing the XML interface definitions. @type replaceKnownInterfaces: C{bool} @param replaceKnownInterfaces: If true, pr...
[ "def", "getInterfacesFromXML", "(", "xmlStr", ",", "replaceKnownInterfaces", "=", "False", ")", ":", "handler", "=", "IntrospectionHandler", "(", "replaceKnownInterfaces", ")", "xmlStr", "=", "xmlStr", ".", "strip", "(", ")", "if", "xmlStr", ".", "startswith", "...
Parses the supplied Introspection XML string and returns a list of L{interface.DBusInerface} instances representing the XML interface definitions. @type replaceKnownInterfaces: C{bool} @param replaceKnownInterfaces: If true, pre-existing interface definitions will be ...
[ "Parses", "the", "supplied", "Introspection", "XML", "string", "and", "returns", "a", "list", "of", "L", "{", "interface", ".", "DBusInerface", "}", "instances", "representing", "the", "XML", "interface", "definitions", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/introspection.py#L75-L101
cocagne/txdbus
txdbus/bus.py
Bus.clientConnected
def clientConnected(self, proto): """ Called when a client connects to the bus. This method assigns the new connection a unique bus name. """ proto.uniqueName = ':1.%d' % (self.next_id,) self.next_id += 1 self.clients[proto.uniqueName] = proto
python
def clientConnected(self, proto): """ Called when a client connects to the bus. This method assigns the new connection a unique bus name. """ proto.uniqueName = ':1.%d' % (self.next_id,) self.next_id += 1 self.clients[proto.uniqueName] = proto
[ "def", "clientConnected", "(", "self", ",", "proto", ")", ":", "proto", ".", "uniqueName", "=", "':1.%d'", "%", "(", "self", ".", "next_id", ",", ")", "self", ".", "next_id", "+=", "1", "self", ".", "clients", "[", "proto", ".", "uniqueName", "]", "=...
Called when a client connects to the bus. This method assigns the new connection a unique bus name.
[ "Called", "when", "a", "client", "connects", "to", "the", "bus", ".", "This", "method", "assigns", "the", "new", "connection", "a", "unique", "bus", "name", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/bus.py#L174-L181
cocagne/txdbus
txdbus/bus.py
Bus.clientDisconnected
def clientDisconnected(self, proto): """ Called when a client disconnects from the bus """ for rule_id in proto.matchRules: self.router.delMatch(rule_id) for busName in proto.busNames.keys(): self.dbus_ReleaseName(busName, proto.uniqueName) if pr...
python
def clientDisconnected(self, proto): """ Called when a client disconnects from the bus """ for rule_id in proto.matchRules: self.router.delMatch(rule_id) for busName in proto.busNames.keys(): self.dbus_ReleaseName(busName, proto.uniqueName) if pr...
[ "def", "clientDisconnected", "(", "self", ",", "proto", ")", ":", "for", "rule_id", "in", "proto", ".", "matchRules", ":", "self", ".", "router", ".", "delMatch", "(", "rule_id", ")", "for", "busName", "in", "proto", ".", "busNames", ".", "keys", "(", ...
Called when a client disconnects from the bus
[ "Called", "when", "a", "client", "disconnects", "from", "the", "bus" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/bus.py#L183-L194
cocagne/txdbus
txdbus/bus.py
Bus.sendMessage
def sendMessage(self, msg): """ Sends the supplied message to the correct destination. The @type msg: L{message.DBusMessage} @param msg: The 'destination' field of the message must be set for method calls and returns """ if msg._messageType in (1, 2): ...
python
def sendMessage(self, msg): """ Sends the supplied message to the correct destination. The @type msg: L{message.DBusMessage} @param msg: The 'destination' field of the message must be set for method calls and returns """ if msg._messageType in (1, 2): ...
[ "def", "sendMessage", "(", "self", ",", "msg", ")", ":", "if", "msg", ".", "_messageType", "in", "(", "1", ",", "2", ")", ":", "assert", "msg", ".", "destination", ",", "'Failed to specify a message destination'", "if", "msg", ".", "destination", "is", "no...
Sends the supplied message to the correct destination. The @type msg: L{message.DBusMessage} @param msg: The 'destination' field of the message must be set for method calls and returns
[ "Sends", "the", "supplied", "message", "to", "the", "correct", "destination", ".", "The" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/bus.py#L196-L225
cocagne/txdbus
txdbus/bus.py
Bus.sendSignal
def sendSignal(self, p, member, signature=None, body=None, path='/org/freedesktop/DBus', interface='org.freedesktop.DBus'): """ Sends a signal to a specific connection @type p: L{BusProtocol} @param p: L{BusProtocol} instance to send a signal to ...
python
def sendSignal(self, p, member, signature=None, body=None, path='/org/freedesktop/DBus', interface='org.freedesktop.DBus'): """ Sends a signal to a specific connection @type p: L{BusProtocol} @param p: L{BusProtocol} instance to send a signal to ...
[ "def", "sendSignal", "(", "self", ",", "p", ",", "member", ",", "signature", "=", "None", ",", "body", "=", "None", ",", "path", "=", "'/org/freedesktop/DBus'", ",", "interface", "=", "'org.freedesktop.DBus'", ")", ":", "if", "not", "isinstance", "(", "bod...
Sends a signal to a specific connection @type p: L{BusProtocol} @param p: L{BusProtocol} instance to send a signal to @type member: C{string} @param member: Name of the signal to send @type path: C{string} @param path: Path of the object emitting the signal. Defaults t...
[ "Sends", "a", "signal", "to", "a", "specific", "connection" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/bus.py#L277-L312
cocagne/txdbus
txdbus/bus.py
Bus.broadcastSignal
def broadcastSignal(self, member, signature=None, body=None, path='/org/freedesktop/DBus', interface='org.freedesktop.DBus'): """ Sends a signal to all connections with registered interest @type member: C{string} @param member: Name of the...
python
def broadcastSignal(self, member, signature=None, body=None, path='/org/freedesktop/DBus', interface='org.freedesktop.DBus'): """ Sends a signal to all connections with registered interest @type member: C{string} @param member: Name of the...
[ "def", "broadcastSignal", "(", "self", ",", "member", ",", "signature", "=", "None", ",", "body", "=", "None", ",", "path", "=", "'/org/freedesktop/DBus'", ",", "interface", "=", "'org.freedesktop.DBus'", ")", ":", "if", "not", "isinstance", "(", "body", ","...
Sends a signal to all connections with registered interest @type member: C{string} @param member: Name of the signal to send @type path: C{string} @param path: Path of the object emitting the signal. Defaults to 'org/freedesktop/DBus' @type interface: C{st...
[ "Sends", "a", "signal", "to", "all", "connections", "with", "registered", "interest" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/bus.py#L314-L346
cocagne/txdbus
txdbus/message.py
parseMessage
def parseMessage(rawMessage, oobFDs): """ Parses the raw binary message and returns a L{DBusMessage} subclass. Unmarshalling DBUS 'h' (UNIX_FD) gets the FDs from the oobFDs list. @type rawMessage: C{str} @param rawMessage: Raw binary message to parse @rtype: L{DBusMessage} subclass @return...
python
def parseMessage(rawMessage, oobFDs): """ Parses the raw binary message and returns a L{DBusMessage} subclass. Unmarshalling DBUS 'h' (UNIX_FD) gets the FDs from the oobFDs list. @type rawMessage: C{str} @param rawMessage: Raw binary message to parse @rtype: L{DBusMessage} subclass @return...
[ "def", "parseMessage", "(", "rawMessage", ",", "oobFDs", ")", ":", "lendian", "=", "rawMessage", "[", "0", "]", "==", "b'l'", "[", "0", "]", "nheader", ",", "hval", "=", "marshal", ".", "unmarshal", "(", "_headerFormat", ",", "rawMessage", ",", "0", ",...
Parses the raw binary message and returns a L{DBusMessage} subclass. Unmarshalling DBUS 'h' (UNIX_FD) gets the FDs from the oobFDs list. @type rawMessage: C{str} @param rawMessage: Raw binary message to parse @rtype: L{DBusMessage} subclass @returns: The L{DBusMessage} subclass corresponding to th...
[ "Parses", "the", "raw", "binary", "message", "and", "returns", "a", "L", "{", "DBusMessage", "}", "subclass", ".", "Unmarshalling", "DBUS", "h", "(", "UNIX_FD", ")", "gets", "the", "FDs", "from", "the", "oobFDs", "list", "." ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/message.py#L354-L410
cocagne/txdbus
txdbus/message.py
DBusMessage._marshal
def _marshal(self, newSerial=True, oobFDs=None): """ Encodes the message into binary format. The resulting binary message is stored in C{self.rawMessage} """ flags = 0 if not self.expectReply: flags |= 0x1 if not self.autoStart: flags |= ...
python
def _marshal(self, newSerial=True, oobFDs=None): """ Encodes the message into binary format. The resulting binary message is stored in C{self.rawMessage} """ flags = 0 if not self.expectReply: flags |= 0x1 if not self.autoStart: flags |= ...
[ "def", "_marshal", "(", "self", ",", "newSerial", "=", "True", ",", "oobFDs", "=", "None", ")", ":", "flags", "=", "0", "if", "not", "self", ".", "expectReply", ":", "flags", "|=", "0x1", "if", "not", "self", ".", "autoStart", ":", "flags", "|=", "...
Encodes the message into binary format. The resulting binary message is stored in C{self.rawMessage}
[ "Encodes", "the", "message", "into", "binary", "format", ".", "The", "resulting", "binary", "message", "is", "stored", "in", "C", "{", "self", ".", "rawMessage", "}" ]
train
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/message.py#L74-L156
tonyo/pyope
pyope/ope.py
OPE.encrypt
def encrypt(self, plaintext): """Encrypt the given plaintext value""" if not isinstance(plaintext, int): raise ValueError('Plaintext must be an integer value') if not self.in_range.contains(plaintext): raise OutOfRangeError('Plaintext is not within the input range') ...
python
def encrypt(self, plaintext): """Encrypt the given plaintext value""" if not isinstance(plaintext, int): raise ValueError('Plaintext must be an integer value') if not self.in_range.contains(plaintext): raise OutOfRangeError('Plaintext is not within the input range') ...
[ "def", "encrypt", "(", "self", ",", "plaintext", ")", ":", "if", "not", "isinstance", "(", "plaintext", ",", "int", ")", ":", "raise", "ValueError", "(", "'Plaintext must be an integer value'", ")", "if", "not", "self", ".", "in_range", ".", "contains", "(",...
Encrypt the given plaintext value
[ "Encrypt", "the", "given", "plaintext", "value" ]
train
https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/ope.py#L100-L106
tonyo/pyope
pyope/ope.py
OPE.decrypt
def decrypt(self, ciphertext): """Decrypt the given ciphertext value""" if not isinstance(ciphertext, int): raise ValueError('Ciphertext must be an integer value') if not self.out_range.contains(ciphertext): raise OutOfRangeError('Ciphertext is not within the output range...
python
def decrypt(self, ciphertext): """Decrypt the given ciphertext value""" if not isinstance(ciphertext, int): raise ValueError('Ciphertext must be an integer value') if not self.out_range.contains(ciphertext): raise OutOfRangeError('Ciphertext is not within the output range...
[ "def", "decrypt", "(", "self", ",", "ciphertext", ")", ":", "if", "not", "isinstance", "(", "ciphertext", ",", "int", ")", ":", "raise", "ValueError", "(", "'Ciphertext must be an integer value'", ")", "if", "not", "self", ".", "out_range", ".", "contains", ...
Decrypt the given ciphertext value
[ "Decrypt", "the", "given", "ciphertext", "value" ]
train
https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/ope.py#L130-L136
tonyo/pyope
pyope/ope.py
OPE.tape_gen
def tape_gen(self, data): """Return a bit string, generated from the given data string""" # FIXME data = str(data).encode() # Derive a key from data hmac_obj = hmac.HMAC(self.key, digestmod=hashlib.sha256) hmac_obj.update(data) assert hmac_obj.digest_size == 32 ...
python
def tape_gen(self, data): """Return a bit string, generated from the given data string""" # FIXME data = str(data).encode() # Derive a key from data hmac_obj = hmac.HMAC(self.key, digestmod=hashlib.sha256) hmac_obj.update(data) assert hmac_obj.digest_size == 32 ...
[ "def", "tape_gen", "(", "self", ",", "data", ")", ":", "# FIXME", "data", "=", "str", "(", "data", ")", ".", "encode", "(", ")", "# Derive a key from data", "hmac_obj", "=", "hmac", ".", "HMAC", "(", "self", ".", "key", ",", "digestmod", "=", "hashlib"...
Return a bit string, generated from the given data string
[ "Return", "a", "bit", "string", "generated", "from", "the", "given", "data", "string" ]
train
https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/ope.py#L164-L186
tonyo/pyope
pyope/ope.py
OPE.generate_key
def generate_key(block_size=32): """Generate random key for ope cipher. Parameters ---------- block_size : int, optional Length of random bytes. Returns ------- random_key : str A random key for encryption. Notes: ------ ...
python
def generate_key(block_size=32): """Generate random key for ope cipher. Parameters ---------- block_size : int, optional Length of random bytes. Returns ------- random_key : str A random key for encryption. Notes: ------ ...
[ "def", "generate_key", "(", "block_size", "=", "32", ")", ":", "random_seq", "=", "os", ".", "urandom", "(", "block_size", ")", "random_key", "=", "base64", ".", "b64encode", "(", "random_seq", ")", "return", "random_key" ]
Generate random key for ope cipher. Parameters ---------- block_size : int, optional Length of random bytes. Returns ------- random_key : str A random key for encryption. Notes: ------ Implementation follows https://githu...
[ "Generate", "random", "key", "for", "ope", "cipher", "." ]
train
https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/ope.py#L189-L208
tonyo/pyope
pyope/util.py
byte_to_bitstring
def byte_to_bitstring(byte): """Convert one byte to a list of bits""" assert 0 <= byte <= 0xff bits = [int(x) for x in list(bin(byte + 0x100)[3:])] return bits
python
def byte_to_bitstring(byte): """Convert one byte to a list of bits""" assert 0 <= byte <= 0xff bits = [int(x) for x in list(bin(byte + 0x100)[3:])] return bits
[ "def", "byte_to_bitstring", "(", "byte", ")", ":", "assert", "0", "<=", "byte", "<=", "0xff", "bits", "=", "[", "int", "(", "x", ")", "for", "x", "in", "list", "(", "bin", "(", "byte", "+", "0x100", ")", "[", "3", ":", "]", ")", "]", "return", ...
Convert one byte to a list of bits
[ "Convert", "one", "byte", "to", "a", "list", "of", "bits" ]
train
https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/util.py#L3-L7
tonyo/pyope
pyope/util.py
str_to_bitstring
def str_to_bitstring(data): """Convert a string to a list of bits""" assert isinstance(data, bytes), "Data must be an instance of bytes" byte_list = data_to_byte_list(data) bit_list = [bit for data_byte in byte_list for bit in byte_to_bitstring(data_byte)] return bit_list
python
def str_to_bitstring(data): """Convert a string to a list of bits""" assert isinstance(data, bytes), "Data must be an instance of bytes" byte_list = data_to_byte_list(data) bit_list = [bit for data_byte in byte_list for bit in byte_to_bitstring(data_byte)] return bit_list
[ "def", "str_to_bitstring", "(", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "bytes", ")", ",", "\"Data must be an instance of bytes\"", "byte_list", "=", "data_to_byte_list", "(", "data", ")", "bit_list", "=", "[", "bit", "for", "data_byte", "in"...
Convert a string to a list of bits
[ "Convert", "a", "string", "to", "a", "list", "of", "bits" ]
train
https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/util.py#L18-L23
tonyo/pyope
pyope/stat.py
sample_hgd
def sample_hgd(in_range, out_range, nsample, seed_coins): """Get a sample from the hypergeometric distribution, using the provided bit list as a source of randomness""" in_size = in_range.size() out_size = out_range.size() assert in_size > 0 and out_size > 0 assert in_size <= out_size assert out...
python
def sample_hgd(in_range, out_range, nsample, seed_coins): """Get a sample from the hypergeometric distribution, using the provided bit list as a source of randomness""" in_size = in_range.size() out_size = out_range.size() assert in_size > 0 and out_size > 0 assert in_size <= out_size assert out...
[ "def", "sample_hgd", "(", "in_range", ",", "out_range", ",", "nsample", ",", "seed_coins", ")", ":", "in_size", "=", "in_range", ".", "size", "(", ")", "out_size", "=", "out_range", ".", "size", "(", ")", "assert", "in_size", ">", "0", "and", "out_size",...
Get a sample from the hypergeometric distribution, using the provided bit list as a source of randomness
[ "Get", "a", "sample", "from", "the", "hypergeometric", "distribution", "using", "the", "provided", "bit", "list", "as", "a", "source", "of", "randomness" ]
train
https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/stat.py#L5-L25
tonyo/pyope
pyope/stat.py
sample_uniform
def sample_uniform(in_range, seed_coins): """Uniformly select a number from the range using the bit list as a source of randomness""" if isinstance(seed_coins, list): seed_coins.append(None) seed_coins = iter(seed_coins) cur_range = in_range.copy() assert cur_range.size() != 0 while ...
python
def sample_uniform(in_range, seed_coins): """Uniformly select a number from the range using the bit list as a source of randomness""" if isinstance(seed_coins, list): seed_coins.append(None) seed_coins = iter(seed_coins) cur_range = in_range.copy() assert cur_range.size() != 0 while ...
[ "def", "sample_uniform", "(", "in_range", ",", "seed_coins", ")", ":", "if", "isinstance", "(", "seed_coins", ",", "list", ")", ":", "seed_coins", ".", "append", "(", "None", ")", "seed_coins", "=", "iter", "(", "seed_coins", ")", "cur_range", "=", "in_ran...
Uniformly select a number from the range using the bit list as a source of randomness
[ "Uniformly", "select", "a", "number", "from", "the", "range", "using", "the", "bit", "list", "as", "a", "source", "of", "randomness" ]
train
https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/stat.py#L28-L47
dustin/twitty-twister
twittytwister/twitter.py
__downloadPage
def __downloadPage(factory, *args, **kwargs): """Start a HTTP download, returning a HTTPDownloader object""" # The Twisted API is weird: # 1) web.client.downloadPage() doesn't give us the HTTP headers # 2) there is no method that simply accepts a URL and gives you back # a HTTPDownloader object ...
python
def __downloadPage(factory, *args, **kwargs): """Start a HTTP download, returning a HTTPDownloader object""" # The Twisted API is weird: # 1) web.client.downloadPage() doesn't give us the HTTP headers # 2) there is no method that simply accepts a URL and gives you back # a HTTPDownloader object ...
[ "def", "__downloadPage", "(", "factory", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# The Twisted API is weird:", "# 1) web.client.downloadPage() doesn't give us the HTTP headers", "# 2) there is no method that simply accepts a URL and gives you back", "# a HTTPDownload...
Start a HTTP download, returning a HTTPDownloader object
[ "Start", "a", "HTTP", "download", "returning", "a", "HTTPDownloader", "object" ]
train
https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L76-L95
dustin/twitty-twister
twittytwister/twitter.py
Twitter.__encodeMultipart
def __encodeMultipart(self, fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ ...
python
def __encodeMultipart(self, fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ ...
[ "def", "__encodeMultipart", "(", "self", ",", "fields", ",", "files", ")", ":", "boundary", "=", "mimetools", ".", "choose_boundary", "(", ")", "crlf", "=", "'\\r\\n'", "l", "=", "[", "]", "for", "k", ",", "v", "in", "fields", ":", "l", ".", "append"...
fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance
[ "fields", "is", "a", "sequence", "of", "(", "name", "value", ")", "elements", "for", "regular", "form", "fields", ".", "files", "is", "a", "sequence", "of", "(", "name", "filename", "value", ")", "elements", "for", "data", "to", "be", "uploaded", "as", ...
train
https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L179-L204