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
rh-marketingops/dwm
dwm/cleaning.py
DeriveDataLookup
def DeriveDataLookup(fieldName, db, deriveInput, overwrite=True, fieldVal='', histObj={}, blankIfNoMatch=False): """ Return new field value based on single or multi-value lookup against MongoDB :param string fieldName: Field name to query against :param MongoClient db: MongoClient ...
python
def DeriveDataLookup(fieldName, db, deriveInput, overwrite=True, fieldVal='', histObj={}, blankIfNoMatch=False): """ Return new field value based on single or multi-value lookup against MongoDB :param string fieldName: Field name to query against :param MongoClient db: MongoClient ...
[ "def", "DeriveDataLookup", "(", "fieldName", ",", "db", ",", "deriveInput", ",", "overwrite", "=", "True", ",", "fieldVal", "=", "''", ",", "histObj", "=", "{", "}", ",", "blankIfNoMatch", "=", "False", ")", ":", "lookup_vals", "=", "OrderedDict", "(", "...
Return new field value based on single or multi-value lookup against MongoDB :param string fieldName: Field name to query against :param MongoClient db: MongoClient instance connected to MongoDB :param dict deriveInput: Values to perform lookup against: {"lookupField1": "lookupVal1", "lookupFiel...
[ "Return", "new", "field", "value", "based", "on", "single", "or", "multi", "-", "value", "lookup", "against", "MongoDB" ]
train
https://github.com/rh-marketingops/dwm/blob/66c7d18db857afbe5d574478ceaaad6159ae7469/dwm/cleaning.py#L221-L276
rh-marketingops/dwm
dwm/cleaning.py
DeriveDataCopyValue
def DeriveDataCopyValue(fieldName, deriveInput, overwrite, fieldVal, histObj={}): """ Return new value based on value from another field :param string fieldName: Field name to query against :param dict deriveInput: Values to perform lookup against: {"copyField1": "copyVal1"} :param bool ...
python
def DeriveDataCopyValue(fieldName, deriveInput, overwrite, fieldVal, histObj={}): """ Return new value based on value from another field :param string fieldName: Field name to query against :param dict deriveInput: Values to perform lookup against: {"copyField1": "copyVal1"} :param bool ...
[ "def", "DeriveDataCopyValue", "(", "fieldName", ",", "deriveInput", ",", "overwrite", ",", "fieldVal", ",", "histObj", "=", "{", "}", ")", ":", "if", "len", "(", "deriveInput", ")", ">", "1", ":", "raise", "Exception", "(", "\"more than one field/value in deri...
Return new value based on value from another field :param string fieldName: Field name to query against :param dict deriveInput: Values to perform lookup against: {"copyField1": "copyVal1"} :param bool overwrite: Should an existing field value be replaced :param string fieldVal: Current fiel...
[ "Return", "new", "value", "based", "on", "value", "from", "another", "field" ]
train
https://github.com/rh-marketingops/dwm/blob/66c7d18db857afbe5d574478ceaaad6159ae7469/dwm/cleaning.py#L279-L310
rh-marketingops/dwm
dwm/cleaning.py
DeriveDataRegex
def DeriveDataRegex(fieldName, db, deriveInput, overwrite, fieldVal, histObj={}, blankIfNoMatch=False): """ Return a new field value based on match (of another field) against regex queried from MongoDB :param string fieldName: Field name to query against :param MongoClient db: M...
python
def DeriveDataRegex(fieldName, db, deriveInput, overwrite, fieldVal, histObj={}, blankIfNoMatch=False): """ Return a new field value based on match (of another field) against regex queried from MongoDB :param string fieldName: Field name to query against :param MongoClient db: M...
[ "def", "DeriveDataRegex", "(", "fieldName", ",", "db", ",", "deriveInput", ",", "overwrite", ",", "fieldVal", ",", "histObj", "=", "{", "}", ",", "blankIfNoMatch", "=", "False", ")", ":", "if", "len", "(", "deriveInput", ")", ">", "1", ":", "raise", "E...
Return a new field value based on match (of another field) against regex queried from MongoDB :param string fieldName: Field name to query against :param MongoClient db: MongoClient instance connected to MongoDB :param dict deriveInput: Values to perform lookup against: {"lookupField1": "loo...
[ "Return", "a", "new", "field", "value", "based", "on", "match", "(", "of", "another", "field", ")", "against", "regex", "queried", "from", "MongoDB" ]
train
https://github.com/rh-marketingops/dwm/blob/66c7d18db857afbe5d574478ceaaad6159ae7469/dwm/cleaning.py#L313-L390
klahnakoski/pyLibrary
jx_base/query.py
_normalize_select
def _normalize_select(select, frum, schema=None): """ :param select: ONE SELECT COLUMN :param frum: TABLE TO get_columns() :param schema: SCHEMA TO LOOKUP NAMES FOR DEFINITIONS :return: AN ARRAY OF SELECT COLUMNS """ if not _Column: _late_import() if is_text(select): can...
python
def _normalize_select(select, frum, schema=None): """ :param select: ONE SELECT COLUMN :param frum: TABLE TO get_columns() :param schema: SCHEMA TO LOOKUP NAMES FOR DEFINITIONS :return: AN ARRAY OF SELECT COLUMNS """ if not _Column: _late_import() if is_text(select): can...
[ "def", "_normalize_select", "(", "select", ",", "frum", ",", "schema", "=", "None", ")", ":", "if", "not", "_Column", ":", "_late_import", "(", ")", "if", "is_text", "(", "select", ")", ":", "canonical", "=", "select", "=", "Data", "(", "value", "=", ...
:param select: ONE SELECT COLUMN :param frum: TABLE TO get_columns() :param schema: SCHEMA TO LOOKUP NAMES FOR DEFINITIONS :return: AN ARRAY OF SELECT COLUMNS
[ ":", "param", "select", ":", "ONE", "SELECT", "COLUMN", ":", "param", "frum", ":", "TABLE", "TO", "get_columns", "()", ":", "param", "schema", ":", "SCHEMA", "TO", "LOOKUP", "NAMES", "FOR", "DEFINITIONS", ":", "return", ":", "AN", "ARRAY", "OF", "SELECT"...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/query.py#L309-L370
klahnakoski/pyLibrary
jx_base/query.py
_normalize_select_no_context
def _normalize_select_no_context(select, schema=None): """ SAME NORMALIZE, BUT NO SOURCE OF COLUMNS """ if not _Column: _late_import() if is_text(select): select = Data(value=select) else: select = wrap(select) output = select.copy() if not select.value: ...
python
def _normalize_select_no_context(select, schema=None): """ SAME NORMALIZE, BUT NO SOURCE OF COLUMNS """ if not _Column: _late_import() if is_text(select): select = Data(value=select) else: select = wrap(select) output = select.copy() if not select.value: ...
[ "def", "_normalize_select_no_context", "(", "select", ",", "schema", "=", "None", ")", ":", "if", "not", "_Column", ":", "_late_import", "(", ")", "if", "is_text", "(", "select", ")", ":", "select", "=", "Data", "(", "value", "=", "select", ")", "else", ...
SAME NORMALIZE, BUT NO SOURCE OF COLUMNS
[ "SAME", "NORMALIZE", "BUT", "NO", "SOURCE", "OF", "COLUMNS" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/query.py#L373-L421
klahnakoski/pyLibrary
jx_base/query.py
_normalize_edge
def _normalize_edge(edge, dim_index, limit, schema=None): """ :param edge: Not normalized edge :param dim_index: Dimensions are ordered; this is this edge's index into that order :param schema: for context :return: a normalized edge """ if not _Column: _late_import() if not edge...
python
def _normalize_edge(edge, dim_index, limit, schema=None): """ :param edge: Not normalized edge :param dim_index: Dimensions are ordered; this is this edge's index into that order :param schema: for context :return: a normalized edge """ if not _Column: _late_import() if not edge...
[ "def", "_normalize_edge", "(", "edge", ",", "dim_index", ",", "limit", ",", "schema", "=", "None", ")", ":", "if", "not", "_Column", ":", "_late_import", "(", ")", "if", "not", "edge", ":", "Log", ".", "error", "(", "\"Edge has no value, or expression is emp...
:param edge: Not normalized edge :param dim_index: Dimensions are ordered; this is this edge's index into that order :param schema: for context :return: a normalized edge
[ ":", "param", "edge", ":", "Not", "normalized", "edge", ":", "param", "dim_index", ":", "Dimensions", "are", "ordered", ";", "this", "is", "this", "edge", "s", "index", "into", "that", "order", ":", "param", "schema", ":", "for", "context", ":", "return"...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/query.py#L428-L513
klahnakoski/pyLibrary
jx_base/query.py
_normalize_group
def _normalize_group(edge, dim_index, limit, schema=None): """ :param edge: Not normalized groupby :param dim_index: Dimensions are ordered; this is this groupby's index into that order :param schema: for context :return: a normalized groupby """ if is_text(edge): if edge.endswith("....
python
def _normalize_group(edge, dim_index, limit, schema=None): """ :param edge: Not normalized groupby :param dim_index: Dimensions are ordered; this is this groupby's index into that order :param schema: for context :return: a normalized groupby """ if is_text(edge): if edge.endswith("....
[ "def", "_normalize_group", "(", "edge", ",", "dim_index", ",", "limit", ",", "schema", "=", "None", ")", ":", "if", "is_text", "(", "edge", ")", ":", "if", "edge", ".", "endswith", "(", "\".*\"", ")", ":", "prefix", "=", "edge", "[", ":", "-", "2",...
:param edge: Not normalized groupby :param dim_index: Dimensions are ordered; this is this groupby's index into that order :param schema: for context :return: a normalized groupby
[ ":", "param", "edge", ":", "Not", "normalized", "groupby", ":", "param", "dim_index", ":", "Dimensions", "are", "ordered", ";", "this", "is", "this", "groupby", "s", "index", "into", "that", "order", ":", "param", "schema", ":", "for", "context", ":", "r...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/query.py#L527-L580
klahnakoski/pyLibrary
jx_base/query.py
_map_term_using_schema
def _map_term_using_schema(master, path, term, schema_edges): """ IF THE WHERE CLAUSE REFERS TO FIELDS IN THE SCHEMA, THEN EXPAND THEM """ output = FlatList() for k, v in term.items(): dimension = schema_edges[k] if isinstance(dimension, Dimension): domain = dimension.get...
python
def _map_term_using_schema(master, path, term, schema_edges): """ IF THE WHERE CLAUSE REFERS TO FIELDS IN THE SCHEMA, THEN EXPAND THEM """ output = FlatList() for k, v in term.items(): dimension = schema_edges[k] if isinstance(dimension, Dimension): domain = dimension.get...
[ "def", "_map_term_using_schema", "(", "master", ",", "path", ",", "term", ",", "schema_edges", ")", ":", "output", "=", "FlatList", "(", ")", "for", "k", ",", "v", "in", "term", ".", "items", "(", ")", ":", "dimension", "=", "schema_edges", "[", "k", ...
IF THE WHERE CLAUSE REFERS TO FIELDS IN THE SCHEMA, THEN EXPAND THEM
[ "IF", "THE", "WHERE", "CLAUSE", "REFERS", "TO", "FIELDS", "IN", "THE", "SCHEMA", "THEN", "EXPAND", "THEM" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/query.py#L643-L702
klahnakoski/pyLibrary
jx_base/query.py
_where_terms
def _where_terms(master, where, schema): """ USE THE SCHEMA TO CONVERT DIMENSION NAMES TO ES FILTERS master - TOP LEVEL WHERE (FOR PLACING NESTED FILTERS) """ if is_data(where): if where.term: # MAP TERM try: output = _map_term_using_schema(master, [],...
python
def _where_terms(master, where, schema): """ USE THE SCHEMA TO CONVERT DIMENSION NAMES TO ES FILTERS master - TOP LEVEL WHERE (FOR PLACING NESTED FILTERS) """ if is_data(where): if where.term: # MAP TERM try: output = _map_term_using_schema(master, [],...
[ "def", "_where_terms", "(", "master", ",", "where", ",", "schema", ")", ":", "if", "is_data", "(", "where", ")", ":", "if", "where", ".", "term", ":", "# MAP TERM", "try", ":", "output", "=", "_map_term_using_schema", "(", "master", ",", "[", "]", ",",...
USE THE SCHEMA TO CONVERT DIMENSION NAMES TO ES FILTERS master - TOP LEVEL WHERE (FOR PLACING NESTED FILTERS)
[ "USE", "THE", "SCHEMA", "TO", "CONVERT", "DIMENSION", "NAMES", "TO", "ES", "FILTERS", "master", "-", "TOP", "LEVEL", "WHERE", "(", "FOR", "PLACING", "NESTED", "FILTERS", ")" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/query.py#L705-L757
klahnakoski/pyLibrary
jx_base/query.py
_normalize_sort
def _normalize_sort(sort=None): """ CONVERT SORT PARAMETERS TO A NORMAL FORM SO EASIER TO USE """ if sort==None: return FlatList.EMPTY output = FlatList() for s in listwrap(sort): if is_text(s): output.append({"value": jx_expression(s), "sort": 1}) elif is_e...
python
def _normalize_sort(sort=None): """ CONVERT SORT PARAMETERS TO A NORMAL FORM SO EASIER TO USE """ if sort==None: return FlatList.EMPTY output = FlatList() for s in listwrap(sort): if is_text(s): output.append({"value": jx_expression(s), "sort": 1}) elif is_e...
[ "def", "_normalize_sort", "(", "sort", "=", "None", ")", ":", "if", "sort", "==", "None", ":", "return", "FlatList", ".", "EMPTY", "output", "=", "FlatList", "(", ")", "for", "s", "in", "listwrap", "(", "sort", ")", ":", "if", "is_text", "(", "s", ...
CONVERT SORT PARAMETERS TO A NORMAL FORM SO EASIER TO USE
[ "CONVERT", "SORT", "PARAMETERS", "TO", "A", "NORMAL", "FORM", "SO", "EASIER", "TO", "USE" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/query.py#L760-L783
klahnakoski/pyLibrary
jx_base/query.py
QueryOp.vars
def vars(self, exclude_where=False, exclude_select=False): """ :return: variables in query """ def edges_get_all_vars(e): output = set() if is_text(e.value): output.add(e.value) if is_expression(e.value): output |= e.val...
python
def vars(self, exclude_where=False, exclude_select=False): """ :return: variables in query """ def edges_get_all_vars(e): output = set() if is_text(e.value): output.add(e.value) if is_expression(e.value): output |= e.val...
[ "def", "vars", "(", "self", ",", "exclude_where", "=", "False", ",", "exclude_select", "=", "False", ")", ":", "def", "edges_get_all_vars", "(", "e", ")", ":", "output", "=", "set", "(", ")", "if", "is_text", "(", "e", ".", "value", ")", ":", "output...
:return: variables in query
[ ":", "return", ":", "variables", "in", "query" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/query.py#L103-L149
klahnakoski/pyLibrary
jx_base/query.py
QueryOp.wrap
def wrap(query, container, namespace): """ NORMALIZE QUERY SO IT CAN STILL BE JSON """ if is_op(query, QueryOp) or query == None: return query query = wrap(query) table = container.get_table(query['from']) schema = table.schema output = QueryO...
python
def wrap(query, container, namespace): """ NORMALIZE QUERY SO IT CAN STILL BE JSON """ if is_op(query, QueryOp) or query == None: return query query = wrap(query) table = container.get_table(query['from']) schema = table.schema output = QueryO...
[ "def", "wrap", "(", "query", ",", "container", ",", "namespace", ")", ":", "if", "is_op", "(", "query", ",", "QueryOp", ")", "or", "query", "==", "None", ":", "return", "query", "query", "=", "wrap", "(", "query", ")", "table", "=", "container", ".",...
NORMALIZE QUERY SO IT CAN STILL BE JSON
[ "NORMALIZE", "QUERY", "SO", "IT", "CAN", "STILL", "BE", "JSON" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/query.py#L200-L245
ff0000/scarlet
scarlet/cache/manager.py
CacheManager.register_cache
def register_cache(self, cache_group): """ Register a cache_group with this manager. Use this method to register more complicated groups that you create yourself. Such as if you need to register several models each with different parameters. :param cache_group: ...
python
def register_cache(self, cache_group): """ Register a cache_group with this manager. Use this method to register more complicated groups that you create yourself. Such as if you need to register several models each with different parameters. :param cache_group: ...
[ "def", "register_cache", "(", "self", ",", "cache_group", ")", ":", "if", "cache_group", ".", "key", "in", "self", ".", "_registry", ":", "raise", "Exception", "(", "\"%s is already registered\"", "%", "cache_group", ".", "key", ")", "self", ".", "_registry", ...
Register a cache_group with this manager. Use this method to register more complicated groups that you create yourself. Such as if you need to register several models each with different parameters. :param cache_group: The group to register. \ The group is registered wi...
[ "Register", "a", "cache_group", "with", "this", "manager", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cache/manager.py#L25-L41
ff0000/scarlet
scarlet/cache/manager.py
CacheManager.register_model
def register_model(self, key, *models, **kwargs): """ Register a cache_group with this manager. Use this method to register more simple groups where all models share the same parameters. Any arguments are treated as models that you would like to register. Any k...
python
def register_model(self, key, *models, **kwargs): """ Register a cache_group with this manager. Use this method to register more simple groups where all models share the same parameters. Any arguments are treated as models that you would like to register. Any k...
[ "def", "register_model", "(", "self", ",", "key", ",", "*", "models", ",", "*", "*", "kwargs", ")", ":", "cache_group", "=", "CacheGroup", "(", "key", ")", "for", "model", "in", "models", ":", "cache_group", ".", "register", "(", "model", ",", "*", "...
Register a cache_group with this manager. Use this method to register more simple groups where all models share the same parameters. Any arguments are treated as models that you would like to register. Any keyword arguments received are passed to the register method wh...
[ "Register", "a", "cache_group", "with", "this", "manager", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cache/manager.py#L43-L64
ff0000/scarlet
scarlet/cache/manager.py
CacheManager.invalidate_cache
def invalidate_cache(self, klass, extra=None, **kwargs): """ Invalidate a cache for a specific class. This will loop through all registered groups that have registered the given model class and call their invalidate_cache method. All keyword arguments will be directly passed th...
python
def invalidate_cache(self, klass, extra=None, **kwargs): """ Invalidate a cache for a specific class. This will loop through all registered groups that have registered the given model class and call their invalidate_cache method. All keyword arguments will be directly passed th...
[ "def", "invalidate_cache", "(", "self", ",", "klass", ",", "extra", "=", "None", ",", "*", "*", "kwargs", ")", ":", "extra", "=", "extra", "or", "kwargs", ".", "pop", "(", "'extra'", ",", "{", "}", ")", "for", "group", "in", "self", ".", "_registry...
Invalidate a cache for a specific class. This will loop through all registered groups that have registered the given model class and call their invalidate_cache method. All keyword arguments will be directly passed through to the group's invalidate_cache method, with the exception of *...
[ "Invalidate", "a", "cache", "for", "a", "specific", "class", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cache/manager.py#L66-L91
finklabs/banana
banana/store_prompt.py
create_store_prompt
def create_store_prompt(name): """Create a prompt which implements the `store` feature. :param name: name of the generator :return: prompt """ def _prompt(questions, answers=None, **kwargs): stored_answers = _read_stored_answers(name) to_store = [] for q in questions: ...
python
def create_store_prompt(name): """Create a prompt which implements the `store` feature. :param name: name of the generator :return: prompt """ def _prompt(questions, answers=None, **kwargs): stored_answers = _read_stored_answers(name) to_store = [] for q in questions: ...
[ "def", "create_store_prompt", "(", "name", ")", ":", "def", "_prompt", "(", "questions", ",", "answers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "stored_answers", "=", "_read_stored_answers", "(", "name", ")", "to_store", "=", "[", "]", "for", "q...
Create a prompt which implements the `store` feature. :param name: name of the generator :return: prompt
[ "Create", "a", "prompt", "which", "implements", "the", "store", "feature", "." ]
train
https://github.com/finklabs/banana/blob/bc416b5a3971fba0b0a90644760ccaddb95b0149/banana/store_prompt.py#L47-L72
jmoiron/micromongo
micromongo/utils.py
memoize
def memoize(function): """Memoizing function. Potentially not thread-safe, since it will return resuts across threads. Make sure this is okay with callers.""" _cache = {} @wraps(function) def wrapper(*args, **kwargs): key = str(args) + str(kwargs) if key not in _cache: ...
python
def memoize(function): """Memoizing function. Potentially not thread-safe, since it will return resuts across threads. Make sure this is okay with callers.""" _cache = {} @wraps(function) def wrapper(*args, **kwargs): key = str(args) + str(kwargs) if key not in _cache: ...
[ "def", "memoize", "(", "function", ")", ":", "_cache", "=", "{", "}", "@", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "key", "=", "str", "(", "args", ")", "+", "str", "(", "kwargs", ")"...
Memoizing function. Potentially not thread-safe, since it will return resuts across threads. Make sure this is okay with callers.
[ "Memoizing", "function", ".", "Potentially", "not", "thread", "-", "safe", "since", "it", "will", "return", "resuts", "across", "threads", ".", "Make", "sure", "this", "is", "okay", "with", "callers", "." ]
train
https://github.com/jmoiron/micromongo/blob/0d7dd1396e2f25ece6648619ccff32345bc306a1/micromongo/utils.py#L9-L19
openfisca/openfisca-france-indirect-taxation
openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py
get_inflators_bdf_to_cn
def get_inflators_bdf_to_cn(data_year): ''' Calcule les ratios de calage (bdf sur cn pour année de données) à partir des masses de comptabilité nationale et des masses de consommation de bdf. ''' data_cn = get_cn_aggregates(data_year) data_bdf = get_bdf_aggregates(data_year) masses = data_cn...
python
def get_inflators_bdf_to_cn(data_year): ''' Calcule les ratios de calage (bdf sur cn pour année de données) à partir des masses de comptabilité nationale et des masses de consommation de bdf. ''' data_cn = get_cn_aggregates(data_year) data_bdf = get_bdf_aggregates(data_year) masses = data_cn...
[ "def", "get_inflators_bdf_to_cn", "(", "data_year", ")", ":", "data_cn", "=", "get_cn_aggregates", "(", "data_year", ")", "data_bdf", "=", "get_bdf_aggregates", "(", "data_year", ")", "masses", "=", "data_cn", ".", "merge", "(", "data_bdf", ",", "left_index", "=...
Calcule les ratios de calage (bdf sur cn pour année de données) à partir des masses de comptabilité nationale et des masses de consommation de bdf.
[ "Calcule", "les", "ratios", "de", "calage", "(", "bdf", "sur", "cn", "pour", "année", "de", "données", ")", "à", "partir", "des", "masses", "de", "comptabilité", "nationale", "et", "des", "masses", "de", "consommation", "de", "bdf", "." ]
train
https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py#L82-L95
openfisca/openfisca-france-indirect-taxation
openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py
get_inflators_cn_to_cn
def get_inflators_cn_to_cn(target_year): ''' Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale. ''' data_year = find_nearest_inferior(data_years, target_year) data_year_cn_aggregates = get_cn_aggregates(data_year)['consoCN_COICOP_{}'.format(data_year)].to_dict()...
python
def get_inflators_cn_to_cn(target_year): ''' Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale. ''' data_year = find_nearest_inferior(data_years, target_year) data_year_cn_aggregates = get_cn_aggregates(data_year)['consoCN_COICOP_{}'.format(data_year)].to_dict()...
[ "def", "get_inflators_cn_to_cn", "(", "target_year", ")", ":", "data_year", "=", "find_nearest_inferior", "(", "data_years", ",", "target_year", ")", "data_year_cn_aggregates", "=", "get_cn_aggregates", "(", "data_year", ")", "[", "'consoCN_COICOP_{}'", ".", "format", ...
Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale.
[ "Calcule", "l", "inflateur", "de", "vieillissement", "à", "partir", "des", "masses", "de", "comptabilité", "nationale", "." ]
train
https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py#L98-L109
openfisca/openfisca-france-indirect-taxation
openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py
get_inflators
def get_inflators(target_year): ''' Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement à partir des masses de comptabilité nationale et des masses de consommation de bdf. ''' data_year = find_nearest_inferior(data_years, target_year) inflators_bdf_t...
python
def get_inflators(target_year): ''' Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement à partir des masses de comptabilité nationale et des masses de consommation de bdf. ''' data_year = find_nearest_inferior(data_years, target_year) inflators_bdf_t...
[ "def", "get_inflators", "(", "target_year", ")", ":", "data_year", "=", "find_nearest_inferior", "(", "data_years", ",", "target_year", ")", "inflators_bdf_to_cn", "=", "get_inflators_bdf_to_cn", "(", "data_year", ")", "inflators_cn_to_cn", "=", "get_inflators_cn_to_cn", ...
Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement à partir des masses de comptabilité nationale et des masses de consommation de bdf.
[ "Fonction", "qui", "calcule", "les", "ratios", "de", "calage", "(", "bdf", "sur", "cn", "pour", "année", "de", "données", ")", "et", "de", "vieillissement", "à", "partir", "des", "masses", "de", "comptabilité", "nationale", "et", "des", "masses", "de", "co...
train
https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py#L112-L125
klahnakoski/pyLibrary
tuid/util.py
map_to_array
def map_to_array(pairs): """ MAP THE (tuid, line) PAIRS TO A SINGLE ARRAY OF TUIDS :param pairs: :return: """ if pairs: pairs = [TuidMap(*p) for p in pairs] max_line = max(p.line for p in pairs) tuids = [None] * max_line for p in pairs: if p.line: # l...
python
def map_to_array(pairs): """ MAP THE (tuid, line) PAIRS TO A SINGLE ARRAY OF TUIDS :param pairs: :return: """ if pairs: pairs = [TuidMap(*p) for p in pairs] max_line = max(p.line for p in pairs) tuids = [None] * max_line for p in pairs: if p.line: # l...
[ "def", "map_to_array", "(", "pairs", ")", ":", "if", "pairs", ":", "pairs", "=", "[", "TuidMap", "(", "*", "p", ")", "for", "p", "in", "pairs", "]", "max_line", "=", "max", "(", "p", ".", "line", "for", "p", "in", "pairs", ")", "tuids", "=", "[...
MAP THE (tuid, line) PAIRS TO A SINGLE ARRAY OF TUIDS :param pairs: :return:
[ "MAP", "THE", "(", "tuid", "line", ")", "PAIRS", "TO", "A", "SINGLE", "ARRAY", "OF", "TUIDS", ":", "param", "pairs", ":", ":", "return", ":" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/util.py#L10-L25
rh-marketingops/dwm
dwm/dwm.py
dwmAll
def dwmAll(data, db, configName='', config={}, udfNamespace=__name__, verbose=False): """ Return list of dictionaries after cleaning rules have been applied; optionally with a history record ID appended. :param list data: list of dictionaries (records) to which cleaning rules should be applied :param M...
python
def dwmAll(data, db, configName='', config={}, udfNamespace=__name__, verbose=False): """ Return list of dictionaries after cleaning rules have been applied; optionally with a history record ID appended. :param list data: list of dictionaries (records) to which cleaning rules should be applied :param M...
[ "def", "dwmAll", "(", "data", ",", "db", ",", "configName", "=", "''", ",", "config", "=", "{", "}", ",", "udfNamespace", "=", "__name__", ",", "verbose", "=", "False", ")", ":", "if", "config", "==", "{", "}", "and", "configName", "==", "''", ":",...
Return list of dictionaries after cleaning rules have been applied; optionally with a history record ID appended. :param list data: list of dictionaries (records) to which cleaning rules should be applied :param MongoClient db: MongoDB connection :param string configName: name of configuration to use; will...
[ "Return", "list", "of", "dictionaries", "after", "cleaning", "rules", "have", "been", "applied", ";", "optionally", "with", "a", "history", "record", "ID", "appended", "." ]
train
https://github.com/rh-marketingops/dwm/blob/66c7d18db857afbe5d574478ceaaad6159ae7469/dwm/dwm.py#L11-L61
rh-marketingops/dwm
dwm/dwm.py
dwmOne
def dwmOne(data, db, config, writeContactHistory=True, returnHistoryId=True, histIdField={"name": "emailAddress", "value": "emailAddress"}, udfNamespace=__name__): """ Return a single dictionary (record) after cleaning rules have been applied; optionally insert history record to collection 'contactHistory' ...
python
def dwmOne(data, db, config, writeContactHistory=True, returnHistoryId=True, histIdField={"name": "emailAddress", "value": "emailAddress"}, udfNamespace=__name__): """ Return a single dictionary (record) after cleaning rules have been applied; optionally insert history record to collection 'contactHistory' ...
[ "def", "dwmOne", "(", "data", ",", "db", ",", "config", ",", "writeContactHistory", "=", "True", ",", "returnHistoryId", "=", "True", ",", "histIdField", "=", "{", "\"name\"", ":", "\"emailAddress\"", ",", "\"value\"", ":", "\"emailAddress\"", "}", ",", "udf...
Return a single dictionary (record) after cleaning rules have been applied; optionally insert history record to collection 'contactHistory' :param dict data: single record (dictionary) to which cleaning rules should be applied :param MongoClient db: MongoClient instance connected to MongoDB :param dict con...
[ "Return", "a", "single", "dictionary", "(", "record", ")", "after", "cleaning", "rules", "have", "been", "applied", ";", "optionally", "insert", "history", "record", "to", "collection", "contactHistory" ]
train
https://github.com/rh-marketingops/dwm/blob/66c7d18db857afbe5d574478ceaaad6159ae7469/dwm/dwm.py#L65-L156
klahnakoski/pyLibrary
mo_threads/signal.py
Signal.wait
def wait(self): """ PUT THREAD IN WAIT STATE UNTIL SIGNAL IS ACTIVATED """ if self._go: return True with self.lock: if self._go: return True stopper = _allocate_lock() stopper.acquire() if not self.waiti...
python
def wait(self): """ PUT THREAD IN WAIT STATE UNTIL SIGNAL IS ACTIVATED """ if self._go: return True with self.lock: if self._go: return True stopper = _allocate_lock() stopper.acquire() if not self.waiti...
[ "def", "wait", "(", "self", ")", ":", "if", "self", ".", "_go", ":", "return", "True", "with", "self", ".", "lock", ":", "if", "self", ".", "_go", ":", "return", "True", "stopper", "=", "_allocate_lock", "(", ")", "stopper", ".", "acquire", "(", ")...
PUT THREAD IN WAIT STATE UNTIL SIGNAL IS ACTIVATED
[ "PUT", "THREAD", "IN", "WAIT", "STATE", "UNTIL", "SIGNAL", "IS", "ACTIVATED" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/signal.py#L57-L77
klahnakoski/pyLibrary
mo_threads/signal.py
Signal.go
def go(self): """ ACTIVATE SIGNAL (DOES NOTHING IF SIGNAL IS ALREADY ACTIVATED) """ DEBUG and self._name and Log.note("GO! {{name|quote}}", name=self.name) if self._go: return with self.lock: if self._go: return self._...
python
def go(self): """ ACTIVATE SIGNAL (DOES NOTHING IF SIGNAL IS ALREADY ACTIVATED) """ DEBUG and self._name and Log.note("GO! {{name|quote}}", name=self.name) if self._go: return with self.lock: if self._go: return self._...
[ "def", "go", "(", "self", ")", ":", "DEBUG", "and", "self", ".", "_name", "and", "Log", ".", "note", "(", "\"GO! {{name|quote}}\"", ",", "name", "=", "self", ".", "name", ")", "if", "self", ".", "_go", ":", "return", "with", "self", ".", "lock", ":...
ACTIVATE SIGNAL (DOES NOTHING IF SIGNAL IS ALREADY ACTIVATED)
[ "ACTIVATE", "SIGNAL", "(", "DOES", "NOTHING", "IF", "SIGNAL", "IS", "ALREADY", "ACTIVATED", ")" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/signal.py#L79-L107
klahnakoski/pyLibrary
mo_threads/signal.py
Signal.on_go
def on_go(self, target): """ RUN target WHEN SIGNALED """ if not target: Log.error("expecting target") with self.lock: if not self._go: DEBUG and self._name and Log.note("Adding target to signal {{name|quote}}", name=self.name) ...
python
def on_go(self, target): """ RUN target WHEN SIGNALED """ if not target: Log.error("expecting target") with self.lock: if not self._go: DEBUG and self._name and Log.note("Adding target to signal {{name|quote}}", name=self.name) ...
[ "def", "on_go", "(", "self", ",", "target", ")", ":", "if", "not", "target", ":", "Log", ".", "error", "(", "\"expecting target\"", ")", "with", "self", ".", "lock", ":", "if", "not", "self", ".", "_go", ":", "DEBUG", "and", "self", ".", "_name", "...
RUN target WHEN SIGNALED
[ "RUN", "target", "WHEN", "SIGNALED" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/signal.py#L109-L127
klahnakoski/pyLibrary
mo_threads/signal.py
Signal.remove_go
def remove_go(self, target): """ FOR SAVING MEMORY """ with self.lock: if not self._go: try: self.job_queue.remove(target) except ValueError: pass
python
def remove_go(self, target): """ FOR SAVING MEMORY """ with self.lock: if not self._go: try: self.job_queue.remove(target) except ValueError: pass
[ "def", "remove_go", "(", "self", ",", "target", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "self", ".", "_go", ":", "try", ":", "self", ".", "job_queue", ".", "remove", "(", "target", ")", "except", "ValueError", ":", "pass" ]
FOR SAVING MEMORY
[ "FOR", "SAVING", "MEMORY" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/signal.py#L129-L138
klahnakoski/pyLibrary
jx_base/expressions.py
_jx_expression
def _jx_expression(expr, lang): """ WRAP A JSON EXPRESSION WITH OBJECT REPRESENTATION """ if is_expression(expr): # CONVERT TO lang new_op = lang[expr.id] if not new_op: # CAN NOT BE FOUND, TRY SOME PARTIAL EVAL return language[expr.id].partial_eval() ...
python
def _jx_expression(expr, lang): """ WRAP A JSON EXPRESSION WITH OBJECT REPRESENTATION """ if is_expression(expr): # CONVERT TO lang new_op = lang[expr.id] if not new_op: # CAN NOT BE FOUND, TRY SOME PARTIAL EVAL return language[expr.id].partial_eval() ...
[ "def", "_jx_expression", "(", "expr", ",", "lang", ")", ":", "if", "is_expression", "(", "expr", ")", ":", "# CONVERT TO lang", "new_op", "=", "lang", "[", "expr", ".", "id", "]", "if", "not", "new_op", ":", "# CAN NOT BE FOUND, TRY SOME PARTIAL EVAL", "return...
WRAP A JSON EXPRESSION WITH OBJECT REPRESENTATION
[ "WRAP", "A", "JSON", "EXPRESSION", "WITH", "OBJECT", "REPRESENTATION" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/expressions.py#L91-L135
klahnakoski/pyLibrary
jx_base/expressions.py
Expression.define
def define(cls, expr): """ GENERAL SUPPORT FOR BUILDING EXPRESSIONS FROM JSON EXPRESSIONS OVERRIDE THIS IF AN OPERATOR EXPECTS COMPLICATED PARAMETERS :param expr: Data representing a JSON Expression :return: parse tree """ try: lang = cls.lang ...
python
def define(cls, expr): """ GENERAL SUPPORT FOR BUILDING EXPRESSIONS FROM JSON EXPRESSIONS OVERRIDE THIS IF AN OPERATOR EXPECTS COMPLICATED PARAMETERS :param expr: Data representing a JSON Expression :return: parse tree """ try: lang = cls.lang ...
[ "def", "define", "(", "cls", ",", "expr", ")", ":", "try", ":", "lang", "=", "cls", ".", "lang", "items", "=", "items_", "(", "expr", ")", "for", "item", "in", "items", ":", "op", ",", "term", "=", "item", "full_op", "=", "operators", ".", "get",...
GENERAL SUPPORT FOR BUILDING EXPRESSIONS FROM JSON EXPRESSIONS OVERRIDE THIS IF AN OPERATOR EXPECTS COMPLICATED PARAMETERS :param expr: Data representing a JSON Expression :return: parse tree
[ "GENERAL", "SUPPORT", "FOR", "BUILDING", "EXPRESSIONS", "FROM", "JSON", "EXPRESSIONS", "OVERRIDE", "THIS", "IF", "AN", "OPERATOR", "EXPECTS", "COMPLICATED", "PARAMETERS", ":", "param", "expr", ":", "Data", "representing", "a", "JSON", "Expression", ":", "return", ...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/expressions.py#L157-L201
klahnakoski/pyLibrary
jx_base/expressions.py
Expression.missing
def missing(self): """ THERE IS PLENTY OF OPPORTUNITY TO SIMPLIFY missing EXPRESSIONS OVERRIDE THIS METHOD TO SIMPLIFY :return: """ if self.type == BOOLEAN: Log.error("programmer error") return self.lang[MissingOp(self)]
python
def missing(self): """ THERE IS PLENTY OF OPPORTUNITY TO SIMPLIFY missing EXPRESSIONS OVERRIDE THIS METHOD TO SIMPLIFY :return: """ if self.type == BOOLEAN: Log.error("programmer error") return self.lang[MissingOp(self)]
[ "def", "missing", "(", "self", ")", ":", "if", "self", ".", "type", "==", "BOOLEAN", ":", "Log", ".", "error", "(", "\"programmer error\"", ")", "return", "self", ".", "lang", "[", "MissingOp", "(", "self", ")", "]" ]
THERE IS PLENTY OF OPPORTUNITY TO SIMPLIFY missing EXPRESSIONS OVERRIDE THIS METHOD TO SIMPLIFY :return:
[ "THERE", "IS", "PLENTY", "OF", "OPPORTUNITY", "TO", "SIMPLIFY", "missing", "EXPRESSIONS", "OVERRIDE", "THIS", "METHOD", "TO", "SIMPLIFY", ":", "return", ":" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/expressions.py#L224-L232
klahnakoski/pyLibrary
mo_threads/lock.py
Lock.wait
def wait(self, till=None): """ THE ASSUMPTION IS wait() WILL ALWAYS RETURN WITH THE LOCK ACQUIRED :param till: WHEN TO GIVE UP WAITING FOR ANOTHER THREAD TO SIGNAL :return: True IF SIGNALED TO GO, False IF till WAS SIGNALED """ waiter = Signal() if self.waiting: ...
python
def wait(self, till=None): """ THE ASSUMPTION IS wait() WILL ALWAYS RETURN WITH THE LOCK ACQUIRED :param till: WHEN TO GIVE UP WAITING FOR ANOTHER THREAD TO SIGNAL :return: True IF SIGNALED TO GO, False IF till WAS SIGNALED """ waiter = Signal() if self.waiting: ...
[ "def", "wait", "(", "self", ",", "till", "=", "None", ")", ":", "waiter", "=", "Signal", "(", ")", "if", "self", ".", "waiting", ":", "DEBUG", "and", "_Log", ".", "note", "(", "\"waiting with {{num}} others on {{name|quote}}\"", ",", "num", "=", "len", "...
THE ASSUMPTION IS wait() WILL ALWAYS RETURN WITH THE LOCK ACQUIRED :param till: WHEN TO GIVE UP WAITING FOR ANOTHER THREAD TO SIGNAL :return: True IF SIGNALED TO GO, False IF till WAS SIGNALED
[ "THE", "ASSUMPTION", "IS", "wait", "()", "WILL", "ALWAYS", "RETURN", "WITH", "THE", "LOCK", "ACQUIRED", ":", "param", "till", ":", "WHEN", "TO", "GIVE", "UP", "WAITING", "FOR", "ANOTHER", "THREAD", "TO", "SIGNAL", ":", "return", ":", "True", "IF", "SIGNA...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/lock.py#L75-L109
sbaechler/django-multilingual-search
multilingual/elasticsearch_backend.py
ElasticsearchMultilingualSearchBackend.setup
def setup(self): """ Defers loading until needed. Compares the existing mapping for each language with the current codebase. If they differ, it automatically updates the index. """ # Get the existing mapping & cache it. We'll compare it # during the ``update`` & i...
python
def setup(self): """ Defers loading until needed. Compares the existing mapping for each language with the current codebase. If they differ, it automatically updates the index. """ # Get the existing mapping & cache it. We'll compare it # during the ``update`` & i...
[ "def", "setup", "(", "self", ")", ":", "# Get the existing mapping & cache it. We'll compare it", "# during the ``update`` & if it doesn't match, we'll put the new", "# mapping.", "for", "language", "in", "self", ".", "languages", ":", "self", ".", "index_name", "=", "self", ...
Defers loading until needed. Compares the existing mapping for each language with the current codebase. If they differ, it automatically updates the index.
[ "Defers", "loading", "until", "needed", ".", "Compares", "the", "existing", "mapping", "for", "each", "language", "with", "the", "current", "codebase", ".", "If", "they", "differ", "it", "automatically", "updates", "the", "index", "." ]
train
https://github.com/sbaechler/django-multilingual-search/blob/485c690d865da3267b19e073e28d3e2290f36611/multilingual/elasticsearch_backend.py#L42-L94
sbaechler/django-multilingual-search
multilingual/elasticsearch_backend.py
ElasticsearchMultilingualSearchBackend.clear
def clear(self, models=None, commit=True): """ Clears all indexes for the current project. :param models: if specified, only deletes the entries for the given models. :param commit: This is ignored by Haystack (maybe a bug?) """ for language in self.languages: ...
python
def clear(self, models=None, commit=True): """ Clears all indexes for the current project. :param models: if specified, only deletes the entries for the given models. :param commit: This is ignored by Haystack (maybe a bug?) """ for language in self.languages: ...
[ "def", "clear", "(", "self", ",", "models", "=", "None", ",", "commit", "=", "True", ")", ":", "for", "language", "in", "self", ".", "languages", ":", "self", ".", "log", ".", "debug", "(", "'clearing index for {0}'", ".", "format", "(", "language", ")...
Clears all indexes for the current project. :param models: if specified, only deletes the entries for the given models. :param commit: This is ignored by Haystack (maybe a bug?)
[ "Clears", "all", "indexes", "for", "the", "current", "project", ".", ":", "param", "models", ":", "if", "specified", "only", "deletes", "the", "entries", "for", "the", "given", "models", ".", ":", "param", "commit", ":", "This", "is", "ignored", "by", "H...
train
https://github.com/sbaechler/django-multilingual-search/blob/485c690d865da3267b19e073e28d3e2290f36611/multilingual/elasticsearch_backend.py#L96-L106
sbaechler/django-multilingual-search
multilingual/elasticsearch_backend.py
ElasticsearchMultilingualSearchBackend.update
def update(self, index, iterable, commit=True): """ Updates the index with current data. :param index: The search_indexes.Index object :param iterable: The queryset :param commit: commit to the backend. """ parler = False # setup here because self.existing...
python
def update(self, index, iterable, commit=True): """ Updates the index with current data. :param index: The search_indexes.Index object :param iterable: The queryset :param commit: commit to the backend. """ parler = False # setup here because self.existing...
[ "def", "update", "(", "self", ",", "index", ",", "iterable", ",", "commit", "=", "True", ")", ":", "parler", "=", "False", "# setup here because self.existing_mappings are overridden.", "if", "not", "self", ".", "setup_complete", ":", "try", ":", "self", ".", ...
Updates the index with current data. :param index: The search_indexes.Index object :param iterable: The queryset :param commit: commit to the backend.
[ "Updates", "the", "index", "with", "current", "data", ".", ":", "param", "index", ":", "The", "search_indexes", ".", "Index", "object", ":", "param", "iterable", ":", "The", "queryset", ":", "param", "commit", ":", "commit", "to", "the", "backend", "." ]
train
https://github.com/sbaechler/django-multilingual-search/blob/485c690d865da3267b19e073e28d3e2290f36611/multilingual/elasticsearch_backend.py#L108-L142
sbaechler/django-multilingual-search
multilingual/elasticsearch_backend.py
ElasticsearchMultilingualSearchBackend.build_schema
def build_schema(self, fields, language): """ Build the index schema for the given field. New argument language. :param fields: :param language: the language code :return: a dictionary wit the field name (string) and the mapping configuration (dictionary) ...
python
def build_schema(self, fields, language): """ Build the index schema for the given field. New argument language. :param fields: :param language: the language code :return: a dictionary wit the field name (string) and the mapping configuration (dictionary) ...
[ "def", "build_schema", "(", "self", ",", "fields", ",", "language", ")", ":", "content_field_name", "=", "''", "mapping", "=", "{", "DJANGO_CT", ":", "{", "'type'", ":", "'string'", ",", "'index'", ":", "'not_analyzed'", ",", "'include_in_all'", ":", "False"...
Build the index schema for the given field. New argument language. :param fields: :param language: the language code :return: a dictionary wit the field name (string) and the mapping configuration (dictionary)
[ "Build", "the", "index", "schema", "for", "the", "given", "field", ".", "New", "argument", "language", ".", ":", "param", "fields", ":", ":", "param", "language", ":", "the", "language", "code", ":", "return", ":", "a", "dictionary", "wit", "the", "field...
train
https://github.com/sbaechler/django-multilingual-search/blob/485c690d865da3267b19e073e28d3e2290f36611/multilingual/elasticsearch_backend.py#L144-L178
sbaechler/django-multilingual-search
multilingual/elasticsearch_backend.py
ElasticsearchMultilingualSearchBackend.search
def search(self, query_string, **kwargs): """ The main search method :param query_string: The string to pass to Elasticsearch. e.g. '*:*' :param kwargs: start_offset, end_offset, result_class :return: result_class instance """ self.index_name = self._index_name_fo...
python
def search(self, query_string, **kwargs): """ The main search method :param query_string: The string to pass to Elasticsearch. e.g. '*:*' :param kwargs: start_offset, end_offset, result_class :return: result_class instance """ self.index_name = self._index_name_fo...
[ "def", "search", "(", "self", ",", "query_string", ",", "*", "*", "kwargs", ")", ":", "self", ".", "index_name", "=", "self", ".", "_index_name_for_language", "(", "translation", ".", "get_language", "(", ")", ")", "# self.log.debug('search method called (%s): %s'...
The main search method :param query_string: The string to pass to Elasticsearch. e.g. '*:*' :param kwargs: start_offset, end_offset, result_class :return: result_class instance
[ "The", "main", "search", "method", ":", "param", "query_string", ":", "The", "string", "to", "pass", "to", "Elasticsearch", ".", "e", ".", "g", ".", "*", ":", "*", ":", "param", "kwargs", ":", "start_offset", "end_offset", "result_class", ":", "return", ...
train
https://github.com/sbaechler/django-multilingual-search/blob/485c690d865da3267b19e073e28d3e2290f36611/multilingual/elasticsearch_backend.py#L180-L190
sbaechler/django-multilingual-search
multilingual/elasticsearch_backend.py
ElasticsearchMultilingualSearchBackend.remove
def remove(self, obj_or_string, commit=True): """ Removes an object from the index. :param obj_or_string: :param commit: """ if not self.setup_complete: try: self.setup() except elasticsearch.TransportError as e: if ...
python
def remove(self, obj_or_string, commit=True): """ Removes an object from the index. :param obj_or_string: :param commit: """ if not self.setup_complete: try: self.setup() except elasticsearch.TransportError as e: if ...
[ "def", "remove", "(", "self", ",", "obj_or_string", ",", "commit", "=", "True", ")", ":", "if", "not", "self", ".", "setup_complete", ":", "try", ":", "self", ".", "setup", "(", ")", "except", "elasticsearch", ".", "TransportError", "as", "e", ":", "if...
Removes an object from the index. :param obj_or_string: :param commit:
[ "Removes", "an", "object", "from", "the", "index", ".", ":", "param", "obj_or_string", ":", ":", "param", "commit", ":" ]
train
https://github.com/sbaechler/django-multilingual-search/blob/485c690d865da3267b19e073e28d3e2290f36611/multilingual/elasticsearch_backend.py#L192-L213
acorg/pymds
version.py
get
def get(): """Returns the current version without importing pymds.""" pkgnames = find_packages() if len(pkgnames) == 0: raise ValueError("Can't find any packages") pkgname = pkgnames[0] content = open(join(pkgname, '__init__.py')).read() c = re.compile(r"__version__ *= *('[^']+'|\"[^\...
python
def get(): """Returns the current version without importing pymds.""" pkgnames = find_packages() if len(pkgnames) == 0: raise ValueError("Can't find any packages") pkgname = pkgnames[0] content = open(join(pkgname, '__init__.py')).read() c = re.compile(r"__version__ *= *('[^']+'|\"[^\...
[ "def", "get", "(", ")", ":", "pkgnames", "=", "find_packages", "(", ")", "if", "len", "(", "pkgnames", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Can't find any packages\"", ")", "pkgname", "=", "pkgnames", "[", "0", "]", "content", "=", "open",...
Returns the current version without importing pymds.
[ "Returns", "the", "current", "version", "without", "importing", "pymds", "." ]
train
https://github.com/acorg/pymds/blob/b82939c9df0d434538bd30b7b548908a40f70bbe/version.py#L11-L27
ignacysokolowski/sphinx-readable-theme
docs/source/example.py
store_integers
def store_integers(items, allow_zero=True): """Store integers from the given list in a storage. This is an example function to show autodoc style. Return :class:`Storage` instance with integers from the given list. Examples:: >>> storage = store_integers([1, 'foo', 2, 'bar', 0]) >>> ...
python
def store_integers(items, allow_zero=True): """Store integers from the given list in a storage. This is an example function to show autodoc style. Return :class:`Storage` instance with integers from the given list. Examples:: >>> storage = store_integers([1, 'foo', 2, 'bar', 0]) >>> ...
[ "def", "store_integers", "(", "items", ",", "allow_zero", "=", "True", ")", ":", "ints", "=", "[", "x", "for", "x", "in", "items", "if", "isinstance", "(", "x", ",", "int", ")", "and", "(", "allow_zero", "or", "x", "!=", "0", ")", "]", "storage", ...
Store integers from the given list in a storage. This is an example function to show autodoc style. Return :class:`Storage` instance with integers from the given list. Examples:: >>> storage = store_integers([1, 'foo', 2, 'bar', 0]) >>> storage.items [1, 2, 0] >>> storage...
[ "Store", "integers", "from", "the", "given", "list", "in", "a", "storage", "." ]
train
https://github.com/ignacysokolowski/sphinx-readable-theme/blob/80f4437ae587ad3d21db3c97574beb41e6cf1909/docs/source/example.py#L62-L88
ignacysokolowski/sphinx-readable-theme
docs/source/example.py
Storage.add_item
def add_item(self, item): """Append item to the list. :attr:`last_updated` will be set to :py:meth:`datetime.datetime.now`. :param item: Something to append to :attr:`items`. """ self.items.append(item) self.last_updated = datetime.datetime.now()
python
def add_item(self, item): """Append item to the list. :attr:`last_updated` will be set to :py:meth:`datetime.datetime.now`. :param item: Something to append to :attr:`items`. """ self.items.append(item) self.last_updated = datetime.datetime.now()
[ "def", "add_item", "(", "self", ",", "item", ")", ":", "self", ".", "items", ".", "append", "(", "item", ")", "self", ".", "last_updated", "=", "datetime", ".", "datetime", ".", "now", "(", ")" ]
Append item to the list. :attr:`last_updated` will be set to :py:meth:`datetime.datetime.now`. :param item: Something to append to :attr:`items`.
[ "Append", "item", "to", "the", "list", "." ]
train
https://github.com/ignacysokolowski/sphinx-readable-theme/blob/80f4437ae587ad3d21db3c97574beb41e6cf1909/docs/source/example.py#L49-L59
payplug/payplug-python
payplug/exceptions.py
HttpError.map_http_status_to_exception
def map_http_status_to_exception(http_code): """ Bind a HTTP status to an HttpError. :param http_code: The HTTP code :type http_code: int :return The HttpError that fits to the http_code or HttpError. :rtype Any subclass of HttpError or HttpError """ htt...
python
def map_http_status_to_exception(http_code): """ Bind a HTTP status to an HttpError. :param http_code: The HTTP code :type http_code: int :return The HttpError that fits to the http_code or HttpError. :rtype Any subclass of HttpError or HttpError """ htt...
[ "def", "map_http_status_to_exception", "(", "http_code", ")", ":", "http_exceptions", "=", "HttpError", ".", "__subclasses__", "(", ")", "for", "http_exception", "in", "http_exceptions", ":", "http_statuses", "=", "http_exception", ".", "HTTP_STATUSES", "if", "isinsta...
Bind a HTTP status to an HttpError. :param http_code: The HTTP code :type http_code: int :return The HttpError that fits to the http_code or HttpError. :rtype Any subclass of HttpError or HttpError
[ "Bind", "a", "HTTP", "status", "to", "an", "HttpError", "." ]
train
https://github.com/payplug/payplug-python/blob/42dec9d6bff420dd0c26e51a84dd000adff04331/payplug/exceptions.py#L102-L124
astroswego/plotypus
src/plotypus/periodogram.py
Lomb_Scargle
def Lomb_Scargle(data, precision, min_period, max_period, period_jobs=1): """ Returns the period of *data* according to the `Lomb-Scargle periodogram <https://en.wikipedia.org/wiki/Least-squares_spectral_analysis#The_Lomb.E2.80.93Scargle_periodogram>`_. **Parameters** data : array-like, shape = [n...
python
def Lomb_Scargle(data, precision, min_period, max_period, period_jobs=1): """ Returns the period of *data* according to the `Lomb-Scargle periodogram <https://en.wikipedia.org/wiki/Least-squares_spectral_analysis#The_Lomb.E2.80.93Scargle_periodogram>`_. **Parameters** data : array-like, shape = [n...
[ "def", "Lomb_Scargle", "(", "data", ",", "precision", ",", "min_period", ",", "max_period", ",", "period_jobs", "=", "1", ")", ":", "time", ",", "mags", ",", "", "*", "err", "=", "data", ".", "T", "scaled_mags", "=", "(", "mags", "-", "mags", ".", ...
Returns the period of *data* according to the `Lomb-Scargle periodogram <https://en.wikipedia.org/wiki/Least-squares_spectral_analysis#The_Lomb.E2.80.93Scargle_periodogram>`_. **Parameters** data : array-like, shape = [n_samples, 2] or [n_samples, 3] Array containing columns *time*, *mag*, and (op...
[ "Returns", "the", "period", "of", "*", "data", "*", "according", "to", "the", "Lomb", "-", "Scargle", "periodogram", "<https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Least", "-", "squares_spectral_analysis#The_Lomb", ".", "E2", "...
train
https://github.com/astroswego/plotypus/blob/b1162194ca1d4f6c00e79afe3e6fb40f0eaffcb9/src/plotypus/periodogram.py#L20-L51
astroswego/plotypus
src/plotypus/periodogram.py
conditional_entropy
def conditional_entropy(data, precision, min_period, max_period, xbins=10, ybins=5, period_jobs=1): """ Returns the period of *data* by minimizing conditional entropy. See `link <http://arxiv.org/pdf/1306.6664v2.pdf>`_ [GDDMD] for details. **Parameters** data : array-like, ...
python
def conditional_entropy(data, precision, min_period, max_period, xbins=10, ybins=5, period_jobs=1): """ Returns the period of *data* by minimizing conditional entropy. See `link <http://arxiv.org/pdf/1306.6664v2.pdf>`_ [GDDMD] for details. **Parameters** data : array-like, ...
[ "def", "conditional_entropy", "(", "data", ",", "precision", ",", "min_period", ",", "max_period", ",", "xbins", "=", "10", ",", "ybins", "=", "5", ",", "period_jobs", "=", "1", ")", ":", "periods", "=", "np", ".", "arange", "(", "min_period", ",", "ma...
Returns the period of *data* by minimizing conditional entropy. See `link <http://arxiv.org/pdf/1306.6664v2.pdf>`_ [GDDMD] for details. **Parameters** data : array-like, shape = [n_samples, 2] or [n_samples, 3] Array containing columns *time*, *mag*, and (optional) *error*. precision : number ...
[ "Returns", "the", "period", "of", "*", "data", "*", "by", "minimizing", "conditional", "entropy", ".", "See", "link", "<http", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1306", ".", "6664v2", ".", "pdf", ">", "_", "[", "GDDMD", "]", "for", "...
train
https://github.com/astroswego/plotypus/blob/b1162194ca1d4f6c00e79afe3e6fb40f0eaffcb9/src/plotypus/periodogram.py#L54-L99
astroswego/plotypus
src/plotypus/periodogram.py
CE
def CE(period, data, xbins=10, ybins=5): """ Returns the conditional entropy of *data* rephased with *period*. **Parameters** period : number The period to rephase *data* by. data : array-like, shape = [n_samples, 2] or [n_samples, 3] Array containing columns *time*, *mag*, and (op...
python
def CE(period, data, xbins=10, ybins=5): """ Returns the conditional entropy of *data* rephased with *period*. **Parameters** period : number The period to rephase *data* by. data : array-like, shape = [n_samples, 2] or [n_samples, 3] Array containing columns *time*, *mag*, and (op...
[ "def", "CE", "(", "period", ",", "data", ",", "xbins", "=", "10", ",", "ybins", "=", "5", ")", ":", "if", "period", "<=", "0", ":", "return", "np", ".", "PINF", "r", "=", "rephase", "(", "data", ",", "period", ")", "bins", ",", "", "*", "_", ...
Returns the conditional entropy of *data* rephased with *period*. **Parameters** period : number The period to rephase *data* by. data : array-like, shape = [n_samples, 2] or [n_samples, 3] Array containing columns *time*, *mag*, and (optional) *error*. xbins : int, optional Nu...
[ "Returns", "the", "conditional", "entropy", "of", "*", "data", "*", "rephased", "with", "*", "period", "*", "." ]
train
https://github.com/astroswego/plotypus/blob/b1162194ca1d4f6c00e79afe3e6fb40f0eaffcb9/src/plotypus/periodogram.py#L102-L164
astroswego/plotypus
src/plotypus/periodogram.py
find_period
def find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=Lomb_Scargle, period_jobs=1): """find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=L...
python
def find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=Lomb_Scargle, period_jobs=1): """find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=L...
[ "def", "find_period", "(", "data", ",", "min_period", "=", "0.2", ",", "max_period", "=", "32.0", ",", "coarse_precision", "=", "1e-5", ",", "fine_precision", "=", "1e-9", ",", "periodogram", "=", "Lomb_Scargle", ",", "period_jobs", "=", "1", ")", ":", "if...
find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=Lomb_Scargle, period_jobs=1) Returns the period of *data* according to the given *periodogram*, searching first with a coarse precision, and then a fine precision. **Parameters** data : array-li...
[ "find_period", "(", "data", "min_period", "=", "0", ".", "2", "max_period", "=", "32", ".", "0", "coarse_precision", "=", "1e", "-", "5", "fine_precision", "=", "1e", "-", "9", "periodogram", "=", "Lomb_Scargle", "period_jobs", "=", "1", ")" ]
train
https://github.com/astroswego/plotypus/blob/b1162194ca1d4f6c00e79afe3e6fb40f0eaffcb9/src/plotypus/periodogram.py#L167-L212
astroswego/plotypus
src/plotypus/periodogram.py
rephase
def rephase(data, period=1.0, shift=0.0, col=0, copy=True): """ Returns *data* (or a copy) phased with *period*, and shifted by a phase-shift *shift*. **Parameters** data : array-like, shape = [n_samples, n_cols] Array containing the time or phase values to be rephased in column *c...
python
def rephase(data, period=1.0, shift=0.0, col=0, copy=True): """ Returns *data* (or a copy) phased with *period*, and shifted by a phase-shift *shift*. **Parameters** data : array-like, shape = [n_samples, n_cols] Array containing the time or phase values to be rephased in column *c...
[ "def", "rephase", "(", "data", ",", "period", "=", "1.0", ",", "shift", "=", "0.0", ",", "col", "=", "0", ",", "copy", "=", "True", ")", ":", "rephased", "=", "np", ".", "ma", ".", "array", "(", "data", ",", "copy", "=", "copy", ")", "rephased"...
Returns *data* (or a copy) phased with *period*, and shifted by a phase-shift *shift*. **Parameters** data : array-like, shape = [n_samples, n_cols] Array containing the time or phase values to be rephased in column *col*. period : number, optional Period to phase *data* by (de...
[ "Returns", "*", "data", "*", "(", "or", "a", "copy", ")", "phased", "with", "*", "period", "*", "and", "shifted", "by", "a", "phase", "-", "shift", "*", "shift", "*", "." ]
train
https://github.com/astroswego/plotypus/blob/b1162194ca1d4f6c00e79afe3e6fb40f0eaffcb9/src/plotypus/periodogram.py#L215-L244
rodynnz/xccdf
src/xccdf/models/ident.py
Ident.update_xml_element
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) ...
python
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) ...
[ "def", "update_xml_element", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'xml_element'", ")", ":", "self", ".", "xml_element", "=", "etree", ".", "Element", "(", "self", ".", "name", ",", "nsmap", "=", "NSMAP", ")", "self", ".", ...
Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element
[ "Updates", "the", "xml", "element", "contents", "to", "matches", "the", "instance", "contents", "." ]
train
https://github.com/rodynnz/xccdf/blob/1b9dc2f06b5cce8db2a54c5f95a8f6bcf5cb6981/src/xccdf/models/ident.py#L70-L84
rodynnz/xccdf
src/xccdf/models/ident.py
Ident.to_xml_string
def to_xml_string(self): """ Exports the element in XML format. :returns: element in XML format. :rtype: str """ self.update_xml_element() xml = self.xml_element return etree.tostring(xml, pretty_print=True).decode('utf-8')
python
def to_xml_string(self): """ Exports the element in XML format. :returns: element in XML format. :rtype: str """ self.update_xml_element() xml = self.xml_element return etree.tostring(xml, pretty_print=True).decode('utf-8')
[ "def", "to_xml_string", "(", "self", ")", ":", "self", ".", "update_xml_element", "(", ")", "xml", "=", "self", ".", "xml_element", "return", "etree", ".", "tostring", "(", "xml", ",", "pretty_print", "=", "True", ")", ".", "decode", "(", "'utf-8'", ")" ...
Exports the element in XML format. :returns: element in XML format. :rtype: str
[ "Exports", "the", "element", "in", "XML", "format", "." ]
train
https://github.com/rodynnz/xccdf/blob/1b9dc2f06b5cce8db2a54c5f95a8f6bcf5cb6981/src/xccdf/models/ident.py#L86-L97
jsvine/tinyapi
tinyapi/draft.py
Draft.fetch
def fetch(self): """Fetch data corresponding to this draft and store it as ``self.data``.""" if self.message_id is None: raise Exception(".message_id not set.") response = self.session.request("find:Message.content", [ self.message_id ]) if response == None: raise...
python
def fetch(self): """Fetch data corresponding to this draft and store it as ``self.data``.""" if self.message_id is None: raise Exception(".message_id not set.") response = self.session.request("find:Message.content", [ self.message_id ]) if response == None: raise...
[ "def", "fetch", "(", "self", ")", ":", "if", "self", ".", "message_id", "is", "None", ":", "raise", "Exception", "(", "\".message_id not set.\"", ")", "response", "=", "self", ".", "session", ".", "request", "(", "\"find:Message.content\"", ",", "[", "self",...
Fetch data corresponding to this draft and store it as ``self.data``.
[ "Fetch", "data", "corresponding", "to", "this", "draft", "and", "store", "it", "as", "self", ".", "data", "." ]
train
https://github.com/jsvine/tinyapi/blob/ac2cf0400b2a9b22bd0b1f43b36be99f5d1a787c/tinyapi/draft.py#L22-L30
jsvine/tinyapi
tinyapi/draft.py
Draft.save
def save(self): """Save current draft state.""" response = self.session.request("save:Message", [ self.data ]) self.data = response self.message_id = self.data["id"] return self
python
def save(self): """Save current draft state.""" response = self.session.request("save:Message", [ self.data ]) self.data = response self.message_id = self.data["id"] return self
[ "def", "save", "(", "self", ")", ":", "response", "=", "self", ".", "session", ".", "request", "(", "\"save:Message\"", ",", "[", "self", ".", "data", "]", ")", "self", ".", "data", "=", "response", "self", ".", "message_id", "=", "self", ".", "data"...
Save current draft state.
[ "Save", "current", "draft", "state", "." ]
train
https://github.com/jsvine/tinyapi/blob/ac2cf0400b2a9b22bd0b1f43b36be99f5d1a787c/tinyapi/draft.py#L32-L37
jsvine/tinyapi
tinyapi/draft.py
Draft.send_preview
def send_preview(self): # pragma: no cover """Send a preview of this draft.""" response = self.session.request("method:queuePreview", [ self.data ]) self.data = response return self
python
def send_preview(self): # pragma: no cover """Send a preview of this draft.""" response = self.session.request("method:queuePreview", [ self.data ]) self.data = response return self
[ "def", "send_preview", "(", "self", ")", ":", "# pragma: no cover", "response", "=", "self", ".", "session", ".", "request", "(", "\"method:queuePreview\"", ",", "[", "self", ".", "data", "]", ")", "self", ".", "data", "=", "response", "return", "self" ]
Send a preview of this draft.
[ "Send", "a", "preview", "of", "this", "draft", "." ]
train
https://github.com/jsvine/tinyapi/blob/ac2cf0400b2a9b22bd0b1f43b36be99f5d1a787c/tinyapi/draft.py#L71-L75
jsvine/tinyapi
tinyapi/draft.py
Draft.send
def send(self): # pragma: no cover """Send the draft.""" response = self.session.request("method:queue", [ self.data ]) self.data = response return self
python
def send(self): # pragma: no cover """Send the draft.""" response = self.session.request("method:queue", [ self.data ]) self.data = response return self
[ "def", "send", "(", "self", ")", ":", "# pragma: no cover", "response", "=", "self", ".", "session", ".", "request", "(", "\"method:queue\"", ",", "[", "self", ".", "data", "]", ")", "self", ".", "data", "=", "response", "return", "self" ]
Send the draft.
[ "Send", "the", "draft", "." ]
train
https://github.com/jsvine/tinyapi/blob/ac2cf0400b2a9b22bd0b1f43b36be99f5d1a787c/tinyapi/draft.py#L77-L81
jsvine/tinyapi
tinyapi/draft.py
Draft.delete
def delete(self): """Delete the draft.""" response = self.session.request("delete:Message", [ self.message_id ]) self.data = response return self
python
def delete(self): """Delete the draft.""" response = self.session.request("delete:Message", [ self.message_id ]) self.data = response return self
[ "def", "delete", "(", "self", ")", ":", "response", "=", "self", ".", "session", ".", "request", "(", "\"delete:Message\"", ",", "[", "self", ".", "message_id", "]", ")", "self", ".", "data", "=", "response", "return", "self" ]
Delete the draft.
[ "Delete", "the", "draft", "." ]
train
https://github.com/jsvine/tinyapi/blob/ac2cf0400b2a9b22bd0b1f43b36be99f5d1a787c/tinyapi/draft.py#L83-L87
publysher/rdflib-django
src/rdflib_django/store.py
_get_query_sets_for_object
def _get_query_sets_for_object(o): """ Determines the correct query set based on the object. If the object is a literal, it will return a query set over LiteralStatements. If the object is a URIRef or BNode, it will return a query set over Statements. If the object is unknown, it will return both t...
python
def _get_query_sets_for_object(o): """ Determines the correct query set based on the object. If the object is a literal, it will return a query set over LiteralStatements. If the object is a URIRef or BNode, it will return a query set over Statements. If the object is unknown, it will return both t...
[ "def", "_get_query_sets_for_object", "(", "o", ")", ":", "if", "o", ":", "if", "isinstance", "(", "o", ",", "Literal", ")", ":", "query_sets", "=", "[", "models", ".", "LiteralStatement", ".", "objects", "]", "else", ":", "query_sets", "=", "[", "models"...
Determines the correct query set based on the object. If the object is a literal, it will return a query set over LiteralStatements. If the object is a URIRef or BNode, it will return a query set over Statements. If the object is unknown, it will return both the LiteralStatement and Statement query sets. ...
[ "Determines", "the", "correct", "query", "set", "based", "on", "the", "object", "." ]
train
https://github.com/publysher/rdflib-django/blob/e26992af75f96ef27a6ceaf820574e3bca645953/src/rdflib_django/store.py#L21-L38
publysher/rdflib-django
src/rdflib_django/store.py
_get_named_graph
def _get_named_graph(context): """ Returns the named graph for this context. """ if context is None: return None return models.NamedGraph.objects.get_or_create(identifier=context.identifier)[0]
python
def _get_named_graph(context): """ Returns the named graph for this context. """ if context is None: return None return models.NamedGraph.objects.get_or_create(identifier=context.identifier)[0]
[ "def", "_get_named_graph", "(", "context", ")", ":", "if", "context", "is", "None", ":", "return", "None", "return", "models", ".", "NamedGraph", ".", "objects", ".", "get_or_create", "(", "identifier", "=", "context", ".", "identifier", ")", "[", "0", "]"...
Returns the named graph for this context.
[ "Returns", "the", "named", "graph", "for", "this", "context", "." ]
train
https://github.com/publysher/rdflib-django/blob/e26992af75f96ef27a6ceaf820574e3bca645953/src/rdflib_django/store.py#L41-L48
publysher/rdflib-django
src/rdflib_django/store.py
DjangoStore.destroy
def destroy(self, configuration=None): """ Completely destroys a store and all the contexts and triples in the store. >>> store = DjangoStore() >>> g = rdflib.Graph(store=store) >>> g.open(configuration=None, create=True) == rdflib.store.VALID_STORE True >>> g.op...
python
def destroy(self, configuration=None): """ Completely destroys a store and all the contexts and triples in the store. >>> store = DjangoStore() >>> g = rdflib.Graph(store=store) >>> g.open(configuration=None, create=True) == rdflib.store.VALID_STORE True >>> g.op...
[ "def", "destroy", "(", "self", ",", "configuration", "=", "None", ")", ":", "models", ".", "NamedGraph", ".", "objects", ".", "all", "(", ")", ".", "delete", "(", ")", "models", ".", "URIStatement", ".", "objects", ".", "all", "(", ")", ".", "delete"...
Completely destroys a store and all the contexts and triples in the store. >>> store = DjangoStore() >>> g = rdflib.Graph(store=store) >>> g.open(configuration=None, create=True) == rdflib.store.VALID_STORE True >>> g.open(configuration=None, create=False) == rdflib.store.VALID_...
[ "Completely", "destroys", "a", "store", "and", "all", "the", "contexts", "and", "triples", "in", "the", "store", "." ]
train
https://github.com/publysher/rdflib-django/blob/e26992af75f96ef27a6ceaf820574e3bca645953/src/rdflib_django/store.py#L108-L124
publysher/rdflib-django
src/rdflib_django/store.py
DjangoStore.add
def add(self, (s, p, o), context, quoted=False): """ Adds a triple to the store. >>> from rdflib.term import URIRef >>> from rdflib.namespace import RDF >>> subject = URIRef('http://zoowizard.org/resource/Artis') >>> object = URIRef('http://schema.org/Zoo') >>> ...
python
def add(self, (s, p, o), context, quoted=False): """ Adds a triple to the store. >>> from rdflib.term import URIRef >>> from rdflib.namespace import RDF >>> subject = URIRef('http://zoowizard.org/resource/Artis') >>> object = URIRef('http://schema.org/Zoo') >>> ...
[ "def", "add", "(", "self", ",", "(", "s", ",", "p", ",", "o", ")", ",", "context", ",", "quoted", "=", "False", ")", ":", "assert", "isinstance", "(", "s", ",", "Identifier", ")", "assert", "isinstance", "(", "p", ",", "Identifier", ")", "assert", ...
Adds a triple to the store. >>> from rdflib.term import URIRef >>> from rdflib.namespace import RDF >>> subject = URIRef('http://zoowizard.org/resource/Artis') >>> object = URIRef('http://schema.org/Zoo') >>> g = rdflib.Graph('Django') >>> g.add((subject, RDF.type, obje...
[ "Adds", "a", "triple", "to", "the", "store", "." ]
train
https://github.com/publysher/rdflib-django/blob/e26992af75f96ef27a6ceaf820574e3bca645953/src/rdflib_django/store.py#L126-L154
publysher/rdflib-django
src/rdflib_django/store.py
DjangoStore.remove
def remove(self, (s, p, o), context=None): """ Removes a triple from the store. """ named_graph = _get_named_graph(context) query_sets = _get_query_sets_for_object(o) filter_parameters = dict() if named_graph is not None: filter_parameters['context_id...
python
def remove(self, (s, p, o), context=None): """ Removes a triple from the store. """ named_graph = _get_named_graph(context) query_sets = _get_query_sets_for_object(o) filter_parameters = dict() if named_graph is not None: filter_parameters['context_id...
[ "def", "remove", "(", "self", ",", "(", "s", ",", "p", ",", "o", ")", ",", "context", "=", "None", ")", ":", "named_graph", "=", "_get_named_graph", "(", "context", ")", "query_sets", "=", "_get_query_sets_for_object", "(", "o", ")", "filter_parameters", ...
Removes a triple from the store.
[ "Removes", "a", "triple", "from", "the", "store", "." ]
train
https://github.com/publysher/rdflib-django/blob/e26992af75f96ef27a6ceaf820574e3bca645953/src/rdflib_django/store.py#L156-L176
publysher/rdflib-django
src/rdflib_django/store.py
DjangoStore.triples
def triples(self, (s, p, o), context=None): """ Returns all triples in the current store. """ named_graph = _get_named_graph(context) query_sets = _get_query_sets_for_object(o) filter_parameters = dict() if named_graph is not None: filter_parameters['...
python
def triples(self, (s, p, o), context=None): """ Returns all triples in the current store. """ named_graph = _get_named_graph(context) query_sets = _get_query_sets_for_object(o) filter_parameters = dict() if named_graph is not None: filter_parameters['...
[ "def", "triples", "(", "self", ",", "(", "s", ",", "p", ",", "o", ")", ",", "context", "=", "None", ")", ":", "named_graph", "=", "_get_named_graph", "(", "context", ")", "query_sets", "=", "_get_query_sets_for_object", "(", "o", ")", "filter_parameters", ...
Returns all triples in the current store.
[ "Returns", "all", "triples", "in", "the", "current", "store", "." ]
train
https://github.com/publysher/rdflib-django/blob/e26992af75f96ef27a6ceaf820574e3bca645953/src/rdflib_django/store.py#L178-L200
ttinies/sc2gameLobby
sc2gameLobby/versions.py
addNew
def addNew(label, version, baseVersion, dataHash="", fixedHash="", replayHash=""): """ Add a new version record to the database to be tracked VERSION RECORD EXAMPLE: "base-version": 55505, "data-hash": "60718A7CA50D0DF42987A30CF87BCB80", "fixed-hash": "0189B2804E2F6BA4C4591222089E6...
python
def addNew(label, version, baseVersion, dataHash="", fixedHash="", replayHash=""): """ Add a new version record to the database to be tracked VERSION RECORD EXAMPLE: "base-version": 55505, "data-hash": "60718A7CA50D0DF42987A30CF87BCB80", "fixed-hash": "0189B2804E2F6BA4C4591222089E6...
[ "def", "addNew", "(", "label", ",", "version", ",", "baseVersion", ",", "dataHash", "=", "\"\"", ",", "fixedHash", "=", "\"\"", ",", "replayHash", "=", "\"\"", ")", ":", "baseVersion", "=", "int", "(", "baseVersion", ")", "version", "=", "int", "(", "v...
Add a new version record to the database to be tracked VERSION RECORD EXAMPLE: "base-version": 55505, "data-hash": "60718A7CA50D0DF42987A30CF87BCB80", "fixed-hash": "0189B2804E2F6BA4C4591222089E63B2", "label": "3.16", "replay-hash": "B11811B13F0C85C29C5D4597BD4BA5A4", ...
[ "Add", "a", "new", "version", "record", "to", "the", "database", "to", "be", "tracked", "VERSION", "RECORD", "EXAMPLE", ":", "base", "-", "version", ":", "55505", "data", "-", "hash", ":", "60718A7CA50D0DF42987A30CF87BCB80", "fixed", "-", "hash", ":", "0189B...
train
https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/versions.py#L25-L58
ttinies/sc2gameLobby
sc2gameLobby/versions.py
Handler.load
def load(self): """load ALL_VERS_DATA from disk""" basepath = os.path.dirname(os.path.abspath(__file__)) filename = os.sep.join([basepath, c.FOLDER_JSON, c.FILE_GAME_VERSIONS]) Handler.ALL_VERS_DATA = {} # reset known data; do not retain defunct information with open(filename, "r...
python
def load(self): """load ALL_VERS_DATA from disk""" basepath = os.path.dirname(os.path.abspath(__file__)) filename = os.sep.join([basepath, c.FOLDER_JSON, c.FILE_GAME_VERSIONS]) Handler.ALL_VERS_DATA = {} # reset known data; do not retain defunct information with open(filename, "r...
[ "def", "load", "(", "self", ")", ":", "basepath", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "filename", "=", "os", ".", "sep", ".", "join", "(", "[", "basepath", ",", "c", ".", "F...
load ALL_VERS_DATA from disk
[ "load", "ALL_VERS_DATA", "from", "disk" ]
train
https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/versions.py#L112-L120
ttinies/sc2gameLobby
sc2gameLobby/versions.py
Handler.save
def save(self, new=None, timeout=2): """write ALL_VERS_DATA to disk in 'pretty' format""" if new: self.update(new) # allow two operations (update + save) with a single command if not self._updated: return # nothing to do thisPkg = os.path.dirname(__file__) filename = os.path.join...
python
def save(self, new=None, timeout=2): """write ALL_VERS_DATA to disk in 'pretty' format""" if new: self.update(new) # allow two operations (update + save) with a single command if not self._updated: return # nothing to do thisPkg = os.path.dirname(__file__) filename = os.path.join...
[ "def", "save", "(", "self", ",", "new", "=", "None", ",", "timeout", "=", "2", ")", ":", "if", "new", ":", "self", ".", "update", "(", "new", ")", "# allow two operations (update + save) with a single command", "if", "not", "self", ".", "_updated", ":", "r...
write ALL_VERS_DATA to disk in 'pretty' format
[ "write", "ALL_VERS_DATA", "to", "disk", "in", "pretty", "format" ]
train
https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/versions.py#L125-L150
ttinies/sc2gameLobby
sc2gameLobby/versions.py
Handler.search
def search(self, *args, **kwargs): """match all records that have any args in any key/field that also match key/value requirements specified in kwargs""" ret = [] for record in Handler.ALL_VERS_DATA.values(): matchArgs = list(kwargs.keys()) for k,v in iteritems(kw...
python
def search(self, *args, **kwargs): """match all records that have any args in any key/field that also match key/value requirements specified in kwargs""" ret = [] for record in Handler.ALL_VERS_DATA.values(): matchArgs = list(kwargs.keys()) for k,v in iteritems(kw...
[ "def", "search", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "[", "]", "for", "record", "in", "Handler", ".", "ALL_VERS_DATA", ".", "values", "(", ")", ":", "matchArgs", "=", "list", "(", "kwargs", ".", "keys", "...
match all records that have any args in any key/field that also match key/value requirements specified in kwargs
[ "match", "all", "records", "that", "have", "any", "args", "in", "any", "key", "/", "field", "that", "also", "match", "key", "/", "value", "requirements", "specified", "in", "kwargs" ]
train
https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/versions.py#L152-L170
ttinies/sc2gameLobby
sc2gameLobby/versions.py
Handler.update
def update(self, data): """update known data with with newly provided data""" if not isinstance(data, list): data = [data] # otherwise no conversion is necessary master = Handler.ALL_VERS_DATA for record in data: #print(record) for k,v in iteritems(record): # ensu...
python
def update(self, data): """update known data with with newly provided data""" if not isinstance(data, list): data = [data] # otherwise no conversion is necessary master = Handler.ALL_VERS_DATA for record in data: #print(record) for k,v in iteritems(record): # ensu...
[ "def", "update", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "list", ")", ":", "data", "=", "[", "data", "]", "# otherwise no conversion is necessary", "master", "=", "Handler", ".", "ALL_VERS_DATA", "for", "record", "i...
update known data with with newly provided data
[ "update", "known", "data", "with", "with", "newly", "provided", "data" ]
train
https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/versions.py#L195-L221
ttinies/sc2gameLobby
sc2gameLobby/ipAddresses.py
getLocalIPaddress
def getLocalIPaddress(): """visible to other machines on LAN""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('google.com', 0)) my_local_ip = s.getsockname()[0] # takes ~0.005s #from netifaces import interfaces, ifaddresses, AF_INET #full solution i...
python
def getLocalIPaddress(): """visible to other machines on LAN""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('google.com', 0)) my_local_ip = s.getsockname()[0] # takes ~0.005s #from netifaces import interfaces, ifaddresses, AF_INET #full solution i...
[ "def", "getLocalIPaddress", "(", ")", ":", "try", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "s", ".", "connect", "(", "(", "'google.com'", ",", "0", ")", ")", "my_local_ip", "=", "s"...
visible to other machines on LAN
[ "visible", "to", "other", "machines", "on", "LAN" ]
train
https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/ipAddresses.py#L32-L48
ttinies/sc2gameLobby
sc2gameLobby/ipAddresses.py
getPublicIPaddress
def getPublicIPaddress(timeout=c.DEFAULT_TIMEOUT): """visible on public internet""" start = time.time() my_public_ip = None e = Exception while my_public_ip == None: if time.time() - start > timeout: break try: #httpbin.org -- site is useful to test scripts / applications...
python
def getPublicIPaddress(timeout=c.DEFAULT_TIMEOUT): """visible on public internet""" start = time.time() my_public_ip = None e = Exception while my_public_ip == None: if time.time() - start > timeout: break try: #httpbin.org -- site is useful to test scripts / applications...
[ "def", "getPublicIPaddress", "(", "timeout", "=", "c", ".", "DEFAULT_TIMEOUT", ")", ":", "start", "=", "time", ".", "time", "(", ")", "my_public_ip", "=", "None", "e", "=", "Exception", "while", "my_public_ip", "==", "None", ":", "if", "time", ".", "time...
visible on public internet
[ "visible", "on", "public", "internet" ]
train
https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/ipAddresses.py#L52-L82
richardcornish/django-pygmentify
pygmentify/utils/pygmentify.py
bits_to_dict
def bits_to_dict(bits): """Convert a Django template tag's kwargs into a dictionary of Python types. The only necessary types are number, boolean, list, and string. http://pygments.org/docs/formatters/#HtmlFormatter from: ["style='monokai'", "cssclass='cssclass',", "boolean='true',", 'num=0,', "list='...
python
def bits_to_dict(bits): """Convert a Django template tag's kwargs into a dictionary of Python types. The only necessary types are number, boolean, list, and string. http://pygments.org/docs/formatters/#HtmlFormatter from: ["style='monokai'", "cssclass='cssclass',", "boolean='true',", 'num=0,', "list='...
[ "def", "bits_to_dict", "(", "bits", ")", ":", "# Strip any trailing commas", "cleaned_bits", "=", "[", "bit", "[", ":", "-", "1", "]", "if", "bit", ".", "endswith", "(", "','", ")", "else", "bit", "for", "bit", "in", "bits", "]", "# Create dictionary by sp...
Convert a Django template tag's kwargs into a dictionary of Python types. The only necessary types are number, boolean, list, and string. http://pygments.org/docs/formatters/#HtmlFormatter from: ["style='monokai'", "cssclass='cssclass',", "boolean='true',", 'num=0,', "list='[]'"] to: {'style': 'mono...
[ "Convert", "a", "Django", "template", "tag", "s", "kwargs", "into", "a", "dictionary", "of", "Python", "types", "." ]
train
https://github.com/richardcornish/django-pygmentify/blob/a2d3f6b3c3019d810d46f6ff6beb4e9f53190e7b/pygmentify/utils/pygmentify.py#L12-L33
richardcornish/django-pygmentify
pygmentify/utils/pygmentify.py
pygmentify
def pygmentify(value, **kwargs): """Return a highlighted code block with Pygments.""" soup = BeautifulSoup(value, 'html.parser') for pre in soup.find_all('pre'): # Get code code = ''.join([to_string(item) for item in pre.contents]) code = code.replace('&lt;', '<') code = cod...
python
def pygmentify(value, **kwargs): """Return a highlighted code block with Pygments.""" soup = BeautifulSoup(value, 'html.parser') for pre in soup.find_all('pre'): # Get code code = ''.join([to_string(item) for item in pre.contents]) code = code.replace('&lt;', '<') code = cod...
[ "def", "pygmentify", "(", "value", ",", "*", "*", "kwargs", ")", ":", "soup", "=", "BeautifulSoup", "(", "value", ",", "'html.parser'", ")", "for", "pre", "in", "soup", ".", "find_all", "(", "'pre'", ")", ":", "# Get code", "code", "=", "''", ".", "j...
Return a highlighted code block with Pygments.
[ "Return", "a", "highlighted", "code", "block", "with", "Pygments", "." ]
train
https://github.com/richardcornish/django-pygmentify/blob/a2d3f6b3c3019d810d46f6ff6beb4e9f53190e7b/pygmentify/utils/pygmentify.py#L44-L99
sbaechler/django-multilingual-search
multilingual/utils.py
get_analyzer_for
def get_analyzer_for(language_code, default='snowball'): """ Get the available language analyzer for the given language code or else the default. :param language_code: Django language code :param default: The analyzer to return if no language analyzer has been found. Defaults to 'sno...
python
def get_analyzer_for(language_code, default='snowball'): """ Get the available language analyzer for the given language code or else the default. :param language_code: Django language code :param default: The analyzer to return if no language analyzer has been found. Defaults to 'sno...
[ "def", "get_analyzer_for", "(", "language_code", ",", "default", "=", "'snowball'", ")", ":", "languages", "=", "{", "'ar'", ":", "'arabic'", ",", "# '': 'armenian',", "'eu'", ":", "'basque'", ",", "'pt-br'", ":", "'brazilian'", ",", "'bg'", ":", "'bulgarian'"...
Get the available language analyzer for the given language code or else the default. :param language_code: Django language code :param default: The analyzer to return if no language analyzer has been found. Defaults to 'snowball'. :return: The Haystack language name. E.g. 'german' or the...
[ "Get", "the", "available", "language", "analyzer", "for", "the", "given", "language", "code", "or", "else", "the", "default", ".", ":", "param", "language_code", ":", "Django", "language", "code", ":", "param", "default", ":", "The", "analyzer", "to", "retur...
train
https://github.com/sbaechler/django-multilingual-search/blob/485c690d865da3267b19e073e28d3e2290f36611/multilingual/utils.py#L5-L53
Captricity/captools
captools/api/client.py
_encode_multipart_formdata
def _encode_multipart_formdata(fields, files): """ Create a multipart encoded form for use in PUTing and POSTing. 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, bo...
python
def _encode_multipart_formdata(fields, files): """ Create a multipart encoded form for use in PUTing and POSTing. 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, bo...
[ "def", "_encode_multipart_formdata", "(", "fields", ",", "files", ")", ":", "BOUNDARY", "=", "'----------A_vEry_UnlikelY_bouNdary_$'", "CRLF", "=", "'\\r\\n'", "L", "=", "[", "]", "for", "(", "key", ",", "value", ")", "in", "fields", ":", "L", ".", "append",...
Create a multipart encoded form for use in PUTing and POSTing. 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
[ "Create", "a", "multipart", "encoded", "form", "for", "use", "in", "PUTing", "and", "POSTing", "." ]
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L280-L306
Captricity/captools
captools/api/client.py
_generate_read_callable
def _generate_read_callable(name, display_name, arguments, regex, doc, supported): """ Returns a callable which conjures the URL for the resource and GETs a response """ def f(self, *args, **kwargs): url = self._generate_url(regex, args) if 'params' in kwargs: url += "?" + ur...
python
def _generate_read_callable(name, display_name, arguments, regex, doc, supported): """ Returns a callable which conjures the URL for the resource and GETs a response """ def f(self, *args, **kwargs): url = self._generate_url(regex, args) if 'params' in kwargs: url += "?" + ur...
[ "def", "_generate_read_callable", "(", "name", ",", "display_name", ",", "arguments", ",", "regex", ",", "doc", ",", "supported", ")", ":", "def", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "url", "=", "self", ".", "_gener...
Returns a callable which conjures the URL for the resource and GETs a response
[ "Returns", "a", "callable", "which", "conjures", "the", "URL", "for", "the", "resource", "and", "GETs", "a", "response" ]
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L316-L333
Captricity/captools
captools/api/client.py
_generate_create_callable
def _generate_create_callable(name, display_name, arguments, regex, doc, supported, post_arguments, is_action): """ Returns a callable which conjures the URL for the resource and POSTs data """ def f(self, *args, **kwargs): for key, value in args[-1].items(): if type(value) == file: ...
python
def _generate_create_callable(name, display_name, arguments, regex, doc, supported, post_arguments, is_action): """ Returns a callable which conjures the URL for the resource and POSTs data """ def f(self, *args, **kwargs): for key, value in args[-1].items(): if type(value) == file: ...
[ "def", "_generate_create_callable", "(", "name", ",", "display_name", ",", "arguments", ",", "regex", ",", "doc", ",", "supported", ",", "post_arguments", ",", "is_action", ")", ":", "def", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")"...
Returns a callable which conjures the URL for the resource and POSTs data
[ "Returns", "a", "callable", "which", "conjures", "the", "URL", "for", "the", "resource", "and", "POSTs", "data" ]
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L356-L376
Captricity/captools
captools/api/client.py
_split_regex
def _split_regex(regex): """ Return an array of the URL split at each regex match like (?P<id>[\d]+) Call with a regex of '^/foo/(?P<id>[\d]+)/bar/$' and you will receive ['/foo/', '/bar/'] """ if regex[0] == '^': regex = regex[1:] if regex[-1] == '$': regex = regex[0:-1] res...
python
def _split_regex(regex): """ Return an array of the URL split at each regex match like (?P<id>[\d]+) Call with a regex of '^/foo/(?P<id>[\d]+)/bar/$' and you will receive ['/foo/', '/bar/'] """ if regex[0] == '^': regex = regex[1:] if regex[-1] == '$': regex = regex[0:-1] res...
[ "def", "_split_regex", "(", "regex", ")", ":", "if", "regex", "[", "0", "]", "==", "'^'", ":", "regex", "=", "regex", "[", "1", ":", "]", "if", "regex", "[", "-", "1", "]", "==", "'$'", ":", "regex", "=", "regex", "[", "0", ":", "-", "1", "...
Return an array of the URL split at each regex match like (?P<id>[\d]+) Call with a regex of '^/foo/(?P<id>[\d]+)/bar/$' and you will receive ['/foo/', '/bar/']
[ "Return", "an", "array", "of", "the", "URL", "split", "at", "each", "regex", "match", "like", "(", "?P<id", ">", "[", "\\", "d", "]", "+", ")", "Call", "with", "a", "regex", "of", "^", "/", "foo", "/", "(", "?P<id", ">", "[", "\\", "d", "]", ...
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L393-L414
Captricity/captools
captools/api/client.py
Client.print_help
def print_help(self): """ Prints the api method info to stdout for debugging. """ keyfunc = lambda x: (x.resource_name, x.__doc__.strip()) resources = groupby(sorted(filter(lambda x: (hasattr(x, 'is_api_call') and x.is_api_call...
python
def print_help(self): """ Prints the api method info to stdout for debugging. """ keyfunc = lambda x: (x.resource_name, x.__doc__.strip()) resources = groupby(sorted(filter(lambda x: (hasattr(x, 'is_api_call') and x.is_api_call...
[ "def", "print_help", "(", "self", ")", ":", "keyfunc", "=", "lambda", "x", ":", "(", "x", ".", "resource_name", ",", "x", ".", "__doc__", ".", "strip", "(", ")", ")", "resources", "=", "groupby", "(", "sorted", "(", "filter", "(", "lambda", "x", ":...
Prints the api method info to stdout for debugging.
[ "Prints", "the", "api", "method", "info", "to", "stdout", "for", "debugging", "." ]
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L88-L122
Captricity/captools
captools/api/client.py
Client._construct_request
def _construct_request(self): """ Utility for constructing the request header and connection """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc) else: conn = httplib.HTTPConnection(self.parsed_endpoint...
python
def _construct_request(self): """ Utility for constructing the request header and connection """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc) else: conn = httplib.HTTPConnection(self.parsed_endpoint...
[ "def", "_construct_request", "(", "self", ")", ":", "if", "self", ".", "parsed_endpoint", ".", "scheme", "==", "'https'", ":", "conn", "=", "httplib", ".", "HTTPSConnection", "(", "self", ".", "parsed_endpoint", ".", "netloc", ")", "else", ":", "conn", "="...
Utility for constructing the request header and connection
[ "Utility", "for", "constructing", "the", "request", "header", "and", "connection" ]
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L124-L139
Captricity/captools
captools/api/client.py
Client._delete_resource
def _delete_resource(self, url): """ DELETEs the resource at url """ conn, head = self._construct_request() conn.request("DELETE", url, "", head) resp = conn.getresponse() self._handle_response_errors('DELETE', url, resp)
python
def _delete_resource(self, url): """ DELETEs the resource at url """ conn, head = self._construct_request() conn.request("DELETE", url, "", head) resp = conn.getresponse() self._handle_response_errors('DELETE', url, resp)
[ "def", "_delete_resource", "(", "self", ",", "url", ")", ":", "conn", ",", "head", "=", "self", ".", "_construct_request", "(", ")", "conn", ".", "request", "(", "\"DELETE\"", ",", "url", ",", "\"\"", ",", "head", ")", "resp", "=", "conn", ".", "getr...
DELETEs the resource at url
[ "DELETEs", "the", "resource", "at", "url" ]
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L141-L148
Captricity/captools
captools/api/client.py
Client._get_data
def _get_data(self, url, accept=None): """ GETs the resource at url and returns the raw response If the accept parameter is not None, the request passes is as the Accept header """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_e...
python
def _get_data(self, url, accept=None): """ GETs the resource at url and returns the raw response If the accept parameter is not None, the request passes is as the Accept header """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_e...
[ "def", "_get_data", "(", "self", ",", "url", ",", "accept", "=", "None", ")", ":", "if", "self", ".", "parsed_endpoint", ".", "scheme", "==", "'https'", ":", "conn", "=", "httplib", ".", "HTTPSConnection", "(", "self", ".", "parsed_endpoint", ".", "netlo...
GETs the resource at url and returns the raw response If the accept parameter is not None, the request passes is as the Accept header
[ "GETs", "the", "resource", "at", "url", "and", "returns", "the", "raw", "response", "If", "the", "accept", "parameter", "is", "not", "None", "the", "request", "passes", "is", "as", "the", "Accept", "header" ]
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L150-L173
Captricity/captools
captools/api/client.py
Client._put_or_post_multipart
def _put_or_post_multipart(self, method, url, data): """ encodes the data as a multipart form and PUTs or POSTs to the url the response is parsed as JSON and the returns the resulting data structure """ fields = [] files = [] for key, value in data.items(): ...
python
def _put_or_post_multipart(self, method, url, data): """ encodes the data as a multipart form and PUTs or POSTs to the url the response is parsed as JSON and the returns the resulting data structure """ fields = [] files = [] for key, value in data.items(): ...
[ "def", "_put_or_post_multipart", "(", "self", ",", "method", ",", "url", ",", "data", ")", ":", "fields", "=", "[", "]", "files", "=", "[", "]", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "if", "type", "(", "value", ")...
encodes the data as a multipart form and PUTs or POSTs to the url the response is parsed as JSON and the returns the resulting data structure
[ "encodes", "the", "data", "as", "a", "multipart", "form", "and", "PUTs", "or", "POSTs", "to", "the", "url", "the", "response", "is", "parsed", "as", "JSON", "and", "the", "returns", "the", "resulting", "data", "structure" ]
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L175-L205
Captricity/captools
captools/api/client.py
Client._put_or_post_json
def _put_or_post_json(self, method, url, data): """ urlencodes the data and PUTs it to the url the response is parsed as JSON and the resulting data type is returned """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.net...
python
def _put_or_post_json(self, method, url, data): """ urlencodes the data and PUTs it to the url the response is parsed as JSON and the resulting data type is returned """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.net...
[ "def", "_put_or_post_json", "(", "self", ",", "method", ",", "url", ",", "data", ")", ":", "if", "self", ".", "parsed_endpoint", ".", "scheme", "==", "'https'", ":", "conn", "=", "httplib", ".", "HTTPSConnection", "(", "self", ".", "parsed_endpoint", ".", ...
urlencodes the data and PUTs it to the url the response is parsed as JSON and the resulting data type is returned
[ "urlencodes", "the", "data", "and", "PUTs", "it", "to", "the", "url", "the", "response", "is", "parsed", "as", "JSON", "and", "the", "resulting", "data", "type", "is", "returned" ]
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L207-L227
Captricity/captools
captools/api/client.py
Client._generate_url
def _generate_url(self, regex, arguments): """ Uses the regex (of the type defined in Django's url patterns) and the arguments to return a relative URL For example, if the regex is '^/api/shreddr/job/(?P<id>[\d]+)$' and arguments is ['23'] then return would be '/api/shreddr/job/23' ...
python
def _generate_url(self, regex, arguments): """ Uses the regex (of the type defined in Django's url patterns) and the arguments to return a relative URL For example, if the regex is '^/api/shreddr/job/(?P<id>[\d]+)$' and arguments is ['23'] then return would be '/api/shreddr/job/23' ...
[ "def", "_generate_url", "(", "self", ",", "regex", ",", "arguments", ")", ":", "regex_tokens", "=", "_split_regex", "(", "regex", ")", "result", "=", "''", "for", "i", "in", "range", "(", "len", "(", "arguments", ")", ")", ":", "result", "=", "result",...
Uses the regex (of the type defined in Django's url patterns) and the arguments to return a relative URL For example, if the regex is '^/api/shreddr/job/(?P<id>[\d]+)$' and arguments is ['23'] then return would be '/api/shreddr/job/23'
[ "Uses", "the", "regex", "(", "of", "the", "type", "defined", "in", "Django", "s", "url", "patterns", ")", "and", "the", "arguments", "to", "return", "a", "relative", "URL", "For", "example", "if", "the", "regex", "is", "^", "/", "api", "/", "shreddr", ...
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L229-L241
Captricity/captools
captools/api/client.py
Client.launch_job
def launch_job(self, job_id): """ Convenience method for launching a job. We use POST for actions outside of HTTP verbs (job launch in this case). """ assert self.api_version.lower() in ['0.01a', '0.1'], \ 'This method is only supported in BETA (0.01) and ALPHA (0.01...
python
def launch_job(self, job_id): """ Convenience method for launching a job. We use POST for actions outside of HTTP verbs (job launch in this case). """ assert self.api_version.lower() in ['0.01a', '0.1'], \ 'This method is only supported in BETA (0.01) and ALPHA (0.01...
[ "def", "launch_job", "(", "self", ",", "job_id", ")", ":", "assert", "self", ".", "api_version", ".", "lower", "(", ")", "in", "[", "'0.01a'", ",", "'0.1'", "]", ",", "'This method is only supported in BETA (0.01) and ALPHA (0.01a) versions'", "try", ":", "self", ...
Convenience method for launching a job. We use POST for actions outside of HTTP verbs (job launch in this case).
[ "Convenience", "method", "for", "launching", "a", "job", ".", "We", "use", "POST", "for", "actions", "outside", "of", "HTTP", "verbs", "(", "job", "launch", "in", "this", "case", ")", "." ]
train
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L258-L269
nya3jp/end
end.py
find_importer_frame
def find_importer_frame(): """Returns the outer frame importing this "end" module. If this module is being imported by other means than import statement, None is returned. Returns: A frame object or None. """ byte = lambda ch: ord(ch) if PY2 else ch frame = inspect.currentframe() ...
python
def find_importer_frame(): """Returns the outer frame importing this "end" module. If this module is being imported by other means than import statement, None is returned. Returns: A frame object or None. """ byte = lambda ch: ord(ch) if PY2 else ch frame = inspect.currentframe() ...
[ "def", "find_importer_frame", "(", ")", ":", "byte", "=", "lambda", "ch", ":", "ord", "(", "ch", ")", "if", "PY2", "else", "ch", "frame", "=", "inspect", ".", "currentframe", "(", ")", "try", ":", "while", "frame", ":", "code", "=", "frame", ".", "...
Returns the outer frame importing this "end" module. If this module is being imported by other means than import statement, None is returned. Returns: A frame object or None.
[ "Returns", "the", "outer", "frame", "importing", "this", "end", "module", "." ]
train
https://github.com/nya3jp/end/blob/c001590604e50ab78402420eba4f26ba3d0ed406/end.py#L55-L85
nya3jp/end
end.py
is_end_node
def is_end_node(node): """Checks if a node is the "end" keyword. Args: node: AST node. Returns: True if the node is the "end" keyword, otherwise False. """ return (isinstance(node, ast.Expr) and isinstance(node.value, ast.Name) and node.value.id == 'end')
python
def is_end_node(node): """Checks if a node is the "end" keyword. Args: node: AST node. Returns: True if the node is the "end" keyword, otherwise False. """ return (isinstance(node, ast.Expr) and isinstance(node.value, ast.Name) and node.value.id == 'end')
[ "def", "is_end_node", "(", "node", ")", ":", "return", "(", "isinstance", "(", "node", ",", "ast", ".", "Expr", ")", "and", "isinstance", "(", "node", ".", "value", ",", "ast", ".", "Name", ")", "and", "node", ".", "value", ".", "id", "==", "'end'"...
Checks if a node is the "end" keyword. Args: node: AST node. Returns: True if the node is the "end" keyword, otherwise False.
[ "Checks", "if", "a", "node", "is", "the", "end", "keyword", "." ]
train
https://github.com/nya3jp/end/blob/c001590604e50ab78402420eba4f26ba3d0ed406/end.py#L89-L100
nya3jp/end
end.py
get_compound_bodies
def get_compound_bodies(node): """Returns a list of bodies of a compound statement node. Args: node: AST node. Returns: A list of bodies of the node. If the given node does not represent a compound statement, an empty list is returned. """ if isinstance(node, (ast.Module, a...
python
def get_compound_bodies(node): """Returns a list of bodies of a compound statement node. Args: node: AST node. Returns: A list of bodies of the node. If the given node does not represent a compound statement, an empty list is returned. """ if isinstance(node, (ast.Module, a...
[ "def", "get_compound_bodies", "(", "node", ")", ":", "if", "isinstance", "(", "node", ",", "(", "ast", ".", "Module", ",", "ast", ".", "FunctionDef", ",", "ast", ".", "ClassDef", ",", "ast", ".", "With", ")", ")", ":", "return", "[", "node", ".", "...
Returns a list of bodies of a compound statement node. Args: node: AST node. Returns: A list of bodies of the node. If the given node does not represent a compound statement, an empty list is returned.
[ "Returns", "a", "list", "of", "bodies", "of", "a", "compound", "statement", "node", "." ]
train
https://github.com/nya3jp/end/blob/c001590604e50ab78402420eba4f26ba3d0ed406/end.py#L104-L126
nya3jp/end
end.py
check_end_blocks
def check_end_blocks(frame): """Performs end-block check. Args: frame: A frame object of the module to be checked. Raises: SyntaxError: If check failed. """ try: try: module_name = frame.f_globals['__name__'] except KeyError: warnings.warn( ...
python
def check_end_blocks(frame): """Performs end-block check. Args: frame: A frame object of the module to be checked. Raises: SyntaxError: If check failed. """ try: try: module_name = frame.f_globals['__name__'] except KeyError: warnings.warn( ...
[ "def", "check_end_blocks", "(", "frame", ")", ":", "try", ":", "try", ":", "module_name", "=", "frame", ".", "f_globals", "[", "'__name__'", "]", "except", "KeyError", ":", "warnings", ".", "warn", "(", "'Can not get the source of an uknown module. '", "'End-of-bl...
Performs end-block check. Args: frame: A frame object of the module to be checked. Raises: SyntaxError: If check failed.
[ "Performs", "end", "-", "block", "check", "." ]
train
https://github.com/nya3jp/end/blob/c001590604e50ab78402420eba4f26ba3d0ed406/end.py#L130-L214
nya3jp/end
end.py
install_import_hook
def install_import_hook(): """Installs __import__ hook.""" saved_import = builtins.__import__ @functools.wraps(saved_import) def import_hook(name, *args, **kwargs): if name == 'end': process_import() end return saved_import(name, *args, **kwargs) end builtins....
python
def install_import_hook(): """Installs __import__ hook.""" saved_import = builtins.__import__ @functools.wraps(saved_import) def import_hook(name, *args, **kwargs): if name == 'end': process_import() end return saved_import(name, *args, **kwargs) end builtins....
[ "def", "install_import_hook", "(", ")", ":", "saved_import", "=", "builtins", ".", "__import__", "@", "functools", ".", "wraps", "(", "saved_import", ")", "def", "import_hook", "(", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "name...
Installs __import__ hook.
[ "Installs", "__import__", "hook", "." ]
train
https://github.com/nya3jp/end/blob/c001590604e50ab78402420eba4f26ba3d0ed406/end.py#L235-L245
ereOn/azmq
azmq/metadata.py
metadata_to_buffers
def metadata_to_buffers(metadata): """ Transform a dict of metadata into a sequence of buffers. :param metadata: The metadata, as a dict. :returns: A list of buffers. """ results = [] for key, value in metadata.items(): assert len(key) < 256 assert len(value) < 2 ** 32 ...
python
def metadata_to_buffers(metadata): """ Transform a dict of metadata into a sequence of buffers. :param metadata: The metadata, as a dict. :returns: A list of buffers. """ results = [] for key, value in metadata.items(): assert len(key) < 256 assert len(value) < 2 ** 32 ...
[ "def", "metadata_to_buffers", "(", "metadata", ")", ":", "results", "=", "[", "]", "for", "key", ",", "value", "in", "metadata", ".", "items", "(", ")", ":", "assert", "len", "(", "key", ")", "<", "256", "assert", "len", "(", "value", ")", "<", "2"...
Transform a dict of metadata into a sequence of buffers. :param metadata: The metadata, as a dict. :returns: A list of buffers.
[ "Transform", "a", "dict", "of", "metadata", "into", "a", "sequence", "of", "buffers", "." ]
train
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/metadata.py#L10-L29
ereOn/azmq
azmq/metadata.py
buffer_to_metadata
def buffer_to_metadata(buffer): """ Transform a buffer to a metadata dictionary. :param buffer: The buffer, as received in a READY command. :returns: A metadata dictionary, with its keys normalized (in lowercase). """ offset = 0 size = len(buffer) metadata = {} while offset...
python
def buffer_to_metadata(buffer): """ Transform a buffer to a metadata dictionary. :param buffer: The buffer, as received in a READY command. :returns: A metadata dictionary, with its keys normalized (in lowercase). """ offset = 0 size = len(buffer) metadata = {} while offset...
[ "def", "buffer_to_metadata", "(", "buffer", ")", ":", "offset", "=", "0", "size", "=", "len", "(", "buffer", ")", "metadata", "=", "{", "}", "while", "offset", "<", "size", ":", "name_size", "=", "struct", ".", "unpack_from", "(", "'B'", ",", "buffer",...
Transform a buffer to a metadata dictionary. :param buffer: The buffer, as received in a READY command. :returns: A metadata dictionary, with its keys normalized (in lowercase).
[ "Transform", "a", "buffer", "to", "a", "metadata", "dictionary", "." ]
train
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/metadata.py#L32-L70
Parsl/libsubmit
libsubmit/providers/torque/torque.py
TorqueProvider._status
def _status(self): ''' Internal: Do not call. Returns the status list for a list of job_ids Args: self Returns: [status...] : Status list of all jobs ''' job_id_list = ' '.join(self.resources.keys()) jobs_missing = list(self.resources.keys(...
python
def _status(self): ''' Internal: Do not call. Returns the status list for a list of job_ids Args: self Returns: [status...] : Status list of all jobs ''' job_id_list = ' '.join(self.resources.keys()) jobs_missing = list(self.resources.keys(...
[ "def", "_status", "(", "self", ")", ":", "job_id_list", "=", "' '", ".", "join", "(", "self", ".", "resources", ".", "keys", "(", ")", ")", "jobs_missing", "=", "list", "(", "self", ".", "resources", ".", "keys", "(", ")", ")", "retcode", ",", "std...
Internal: Do not call. Returns the status list for a list of job_ids Args: self Returns: [status...] : Status list of all jobs
[ "Internal", ":", "Do", "not", "call", ".", "Returns", "the", "status", "list", "for", "a", "list", "of", "job_ids" ]
train
https://github.com/Parsl/libsubmit/blob/27a41c16dd6f1c16d830a9ce1c97804920a59f64/libsubmit/providers/torque/torque.py#L110-L138
Parsl/libsubmit
libsubmit/providers/torque/torque.py
TorqueProvider.submit
def submit(self, command, blocksize, job_name="parsl.auto"): ''' Submits the command onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted. If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be...
python
def submit(self, command, blocksize, job_name="parsl.auto"): ''' Submits the command onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted. If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be...
[ "def", "submit", "(", "self", ",", "command", ",", "blocksize", ",", "job_name", "=", "\"parsl.auto\"", ")", ":", "if", "self", ".", "provisioned_blocks", ">=", "self", ".", "max_blocks", ":", "logger", ".", "warn", "(", "\"[%s] at capacity, cannot add more bloc...
Submits the command onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted. If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be integer If tasks_per_node == 1: A single node is p...
[ "Submits", "the", "command", "onto", "an", "Local", "Resource", "Manager", "job", "of", "blocksize", "parallel", "elements", ".", "Submit", "returns", "an", "ID", "that", "corresponds", "to", "the", "task", "that", "was", "just", "submitted", "." ]
train
https://github.com/Parsl/libsubmit/blob/27a41c16dd6f1c16d830a9ce1c97804920a59f64/libsubmit/providers/torque/torque.py#L140-L226
Parsl/libsubmit
libsubmit/providers/torque/torque.py
TorqueProvider.cancel
def cancel(self, job_ids): ''' Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False. ''' job_id_list = ' '.join(job_ids) retcode, stdout, s...
python
def cancel(self, job_ids): ''' Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False. ''' job_id_list = ' '.join(job_ids) retcode, stdout, s...
[ "def", "cancel", "(", "self", ",", "job_ids", ")", ":", "job_id_list", "=", "' '", ".", "join", "(", "job_ids", ")", "retcode", ",", "stdout", ",", "stderr", "=", "self", ".", "channel", ".", "execute_wait", "(", "\"qdel {0}\"", ".", "format", "(", "jo...
Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False.
[ "Cancels", "the", "jobs", "specified", "by", "a", "list", "of", "job", "ids" ]
train
https://github.com/Parsl/libsubmit/blob/27a41c16dd6f1c16d830a9ce1c97804920a59f64/libsubmit/providers/torque/torque.py#L228-L248
ereOn/azmq
azmq/socket.py
Socket.generate_identity
def generate_identity(self): """ Generate a unique but random identity. """ identity = struct.pack('!BI', 0, self._base_identity) self._base_identity += 1 if self._base_identity >= 2 ** 32: self._base_identity = 0 return identity
python
def generate_identity(self): """ Generate a unique but random identity. """ identity = struct.pack('!BI', 0, self._base_identity) self._base_identity += 1 if self._base_identity >= 2 ** 32: self._base_identity = 0 return identity
[ "def", "generate_identity", "(", "self", ")", ":", "identity", "=", "struct", ".", "pack", "(", "'!BI'", ",", "0", ",", "self", ".", "_base_identity", ")", "self", ".", "_base_identity", "+=", "1", "if", "self", ".", "_base_identity", ">=", "2", "**", ...
Generate a unique but random identity.
[ "Generate", "a", "unique", "but", "random", "identity", "." ]
train
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/socket.py#L375-L385
ereOn/azmq
azmq/socket.py
Socket._wait_peers
async def _wait_peers(self): """ Blocks until at least one non-dead peer is available. """ # Make sure we remove dead peers. for p in self._peers[:]: if p.dead: self._peers.remove(p) while not self._peers: await self._peers.wait_no...
python
async def _wait_peers(self): """ Blocks until at least one non-dead peer is available. """ # Make sure we remove dead peers. for p in self._peers[:]: if p.dead: self._peers.remove(p) while not self._peers: await self._peers.wait_no...
[ "async", "def", "_wait_peers", "(", "self", ")", ":", "# Make sure we remove dead peers.", "for", "p", "in", "self", ".", "_peers", "[", ":", "]", ":", "if", "p", ".", "dead", ":", "self", ".", "_peers", ".", "remove", "(", "p", ")", "while", "not", ...
Blocks until at least one non-dead peer is available.
[ "Blocks", "until", "at", "least", "one", "non", "-", "dead", "peer", "is", "available", "." ]
train
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/socket.py#L387-L397
ereOn/azmq
azmq/socket.py
Socket._fair_get_in_peer
async def _fair_get_in_peer(self): """ Get the first available available inbound peer in a fair manner. :returns: A `Peer` inbox, whose inbox is guaranteed not to be empty (and thus can be read from without blocking). """ peer = None while not peer: ...
python
async def _fair_get_in_peer(self): """ Get the first available available inbound peer in a fair manner. :returns: A `Peer` inbox, whose inbox is guaranteed not to be empty (and thus can be read from without blocking). """ peer = None while not peer: ...
[ "async", "def", "_fair_get_in_peer", "(", "self", ")", ":", "peer", "=", "None", "while", "not", "peer", ":", "await", "self", ".", "_wait_peers", "(", ")", "# This rotates the list, implementing fair-queuing.", "peers", "=", "list", "(", "self", ".", "_in_peers...
Get the first available available inbound peer in a fair manner. :returns: A `Peer` inbox, whose inbox is guaranteed not to be empty (and thus can be read from without blocking).
[ "Get", "the", "first", "available", "available", "inbound", "peer", "in", "a", "fair", "manner", "." ]
train
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/socket.py#L399-L443
ereOn/azmq
azmq/socket.py
Socket._fair_recv
async def _fair_recv(self): """ Receive from all the existing peers, rotating the list of peers every time. :returns: The frames. """ with await self._read_lock: peer = await self._fair_get_in_peer() result = peer.inbox.read_nowait() retu...
python
async def _fair_recv(self): """ Receive from all the existing peers, rotating the list of peers every time. :returns: The frames. """ with await self._read_lock: peer = await self._fair_get_in_peer() result = peer.inbox.read_nowait() retu...
[ "async", "def", "_fair_recv", "(", "self", ")", ":", "with", "await", "self", ".", "_read_lock", ":", "peer", "=", "await", "self", ".", "_fair_get_in_peer", "(", ")", "result", "=", "peer", ".", "inbox", ".", "read_nowait", "(", ")", "return", "result" ...
Receive from all the existing peers, rotating the list of peers every time. :returns: The frames.
[ "Receive", "from", "all", "the", "existing", "peers", "rotating", "the", "list", "of", "peers", "every", "time", "." ]
train
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/socket.py#L445-L456
ereOn/azmq
azmq/socket.py
Socket._fair_get_out_peer
async def _fair_get_out_peer(self): """ Get the first available peer, with non-blocking inbox or wait until one meets the condition. :returns: The peer whose outbox is ready to be written to. """ peer = None while not peer: await self._wait_peers() ...
python
async def _fair_get_out_peer(self): """ Get the first available peer, with non-blocking inbox or wait until one meets the condition. :returns: The peer whose outbox is ready to be written to. """ peer = None while not peer: await self._wait_peers() ...
[ "async", "def", "_fair_get_out_peer", "(", "self", ")", ":", "peer", "=", "None", "while", "not", "peer", ":", "await", "self", ".", "_wait_peers", "(", ")", "# This rotates the list, implementing fair-queuing.", "peers", "=", "list", "(", "self", ".", "_out_pee...
Get the first available peer, with non-blocking inbox or wait until one meets the condition. :returns: The peer whose outbox is ready to be written to.
[ "Get", "the", "first", "available", "peer", "with", "non", "-", "blocking", "inbox", "or", "wait", "until", "one", "meets", "the", "condition", "." ]
train
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/socket.py#L458-L502
ereOn/azmq
azmq/socket.py
Socket._fair_send
async def _fair_send(self, frames): """ Send from the first available, non-blocking peer or wait until one meets the condition. :params frames: The frames to write. :returns: The peer that was used. """ peer = await self._fair_get_out_peer() peer.outbox.w...
python
async def _fair_send(self, frames): """ Send from the first available, non-blocking peer or wait until one meets the condition. :params frames: The frames to write. :returns: The peer that was used. """ peer = await self._fair_get_out_peer() peer.outbox.w...
[ "async", "def", "_fair_send", "(", "self", ",", "frames", ")", ":", "peer", "=", "await", "self", ".", "_fair_get_out_peer", "(", ")", "peer", ".", "outbox", ".", "write_nowait", "(", "frames", ")", "return", "peer" ]
Send from the first available, non-blocking peer or wait until one meets the condition. :params frames: The frames to write. :returns: The peer that was used.
[ "Send", "from", "the", "first", "available", "non", "-", "blocking", "peer", "or", "wait", "until", "one", "meets", "the", "condition", "." ]
train
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/socket.py#L504-L514
ereOn/azmq
azmq/socket.py
Socket.subscribe
async def subscribe(self, topic): """ Subscribe the socket to the specified topic. :param topic: The topic to subscribe to. """ if self.socket_type not in {SUB, XSUB}: raise AssertionError( "A %s socket cannot subscribe." % self.socket_type.decode(), ...
python
async def subscribe(self, topic): """ Subscribe the socket to the specified topic. :param topic: The topic to subscribe to. """ if self.socket_type not in {SUB, XSUB}: raise AssertionError( "A %s socket cannot subscribe." % self.socket_type.decode(), ...
[ "async", "def", "subscribe", "(", "self", ",", "topic", ")", ":", "if", "self", ".", "socket_type", "not", "in", "{", "SUB", ",", "XSUB", "}", ":", "raise", "AssertionError", "(", "\"A %s socket cannot subscribe.\"", "%", "self", ".", "socket_type", ".", "...
Subscribe the socket to the specified topic. :param topic: The topic to subscribe to.
[ "Subscribe", "the", "socket", "to", "the", "specified", "topic", "." ]
train
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/socket.py#L720-L748
ereOn/azmq
azmq/socket.py
Socket.unsubscribe
async def unsubscribe(self, topic): """ Unsubscribe the socket from the specified topic. :param topic: The topic to unsubscribe from. """ if self.socket_type not in {SUB, XSUB}: raise AssertionError( "A %s socket cannot unsubscribe." % self.socket_typ...
python
async def unsubscribe(self, topic): """ Unsubscribe the socket from the specified topic. :param topic: The topic to unsubscribe from. """ if self.socket_type not in {SUB, XSUB}: raise AssertionError( "A %s socket cannot unsubscribe." % self.socket_typ...
[ "async", "def", "unsubscribe", "(", "self", ",", "topic", ")", ":", "if", "self", ".", "socket_type", "not", "in", "{", "SUB", ",", "XSUB", "}", ":", "raise", "AssertionError", "(", "\"A %s socket cannot unsubscribe.\"", "%", "self", ".", "socket_type", ".",...
Unsubscribe the socket from the specified topic. :param topic: The topic to unsubscribe from.
[ "Unsubscribe", "the", "socket", "from", "the", "specified", "topic", "." ]
train
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/socket.py#L751-L779
klen/makesite
makesite/modules/flask/manage.py
migrate
def migrate(action): " Migration utils [create, run, undo, redo]. " from flaskext.evolution import Evolution from flask import current_app evolution = Evolution(current_app) evolution.manager(action)
python
def migrate(action): " Migration utils [create, run, undo, redo]. " from flaskext.evolution import Evolution from flask import current_app evolution = Evolution(current_app) evolution.manager(action)
[ "def", "migrate", "(", "action", ")", ":", "from", "flaskext", ".", "evolution", "import", "Evolution", "from", "flask", "import", "current_app", "evolution", "=", "Evolution", "(", "current_app", ")", "evolution", ".", "manager", "(", "action", ")" ]
Migration utils [create, run, undo, redo].
[ "Migration", "utils", "[", "create", "run", "undo", "redo", "]", "." ]
train
https://github.com/klen/makesite/blob/f6f77a43a04a256189e8fffbeac1ffd63f35a10c/makesite/modules/flask/manage.py#L19-L24