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
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
DatasetWhooshIndex.reset
def reset(self): """ Resets index by removing index directory. """ if os.path.exists(self.index_dir): rmtree(self.index_dir) self.index = None
python
def reset(self): """ Resets index by removing index directory. """ if os.path.exists(self.index_dir): rmtree(self.index_dir) self.index = None
[ "def", "reset", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "index_dir", ")", ":", "rmtree", "(", "self", ".", "index_dir", ")", "self", ".", "index", "=", "None" ]
Resets index by removing index directory.
[ "Resets", "index", "by", "removing", "index", "directory", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L54-L58
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
DatasetWhooshIndex.all
def all(self): """ Returns list with all indexed datasets. """ datasets = [] for dataset in self.index.searcher().documents(): res = DatasetSearchResult() res.vid = dataset['vid'] res.b_score = 1 datasets.append(res) return datasets
python
def all(self): """ Returns list with all indexed datasets. """ datasets = [] for dataset in self.index.searcher().documents(): res = DatasetSearchResult() res.vid = dataset['vid'] res.b_score = 1 datasets.append(res) return datasets
[ "def", "all", "(", "self", ")", ":", "datasets", "=", "[", "]", "for", "dataset", "in", "self", ".", "index", ".", "searcher", "(", ")", ".", "documents", "(", ")", ":", "res", "=", "DatasetSearchResult", "(", ")", "res", ".", "vid", "=", "dataset"...
Returns list with all indexed datasets.
[ "Returns", "list", "with", "all", "indexed", "datasets", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L60-L68
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
DatasetWhooshIndex.search
def search(self, search_phrase, limit=None): """ Finds datasets by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to return. None means without limit. Returns: list of DatasetSearchResult instances. """ query_string = self._make_query_from_terms(search_phrase) self._parsed_query = query_string schema = self._get_generic_schema() parser = QueryParser('doc', schema=schema) query = parser.parse(query_string) datasets = defaultdict(DatasetSearchResult) # collect all datasets logger.debug('Searching datasets using `{}` query.'.format(query)) with self.index.searcher() as searcher: results = searcher.search(query, limit=limit) for hit in results: vid = hit['vid'] datasets[vid].vid = hit['vid'] datasets[vid].b_score += hit.score # extend datasets with partitions logger.debug('Extending datasets with partitions.') for partition in self.backend.partition_index.search(search_phrase): datasets[partition.dataset_vid].p_score += partition.score datasets[partition.dataset_vid].partitions.add(partition) return list(datasets.values())
python
def search(self, search_phrase, limit=None): """ Finds datasets by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to return. None means without limit. Returns: list of DatasetSearchResult instances. """ query_string = self._make_query_from_terms(search_phrase) self._parsed_query = query_string schema = self._get_generic_schema() parser = QueryParser('doc', schema=schema) query = parser.parse(query_string) datasets = defaultdict(DatasetSearchResult) # collect all datasets logger.debug('Searching datasets using `{}` query.'.format(query)) with self.index.searcher() as searcher: results = searcher.search(query, limit=limit) for hit in results: vid = hit['vid'] datasets[vid].vid = hit['vid'] datasets[vid].b_score += hit.score # extend datasets with partitions logger.debug('Extending datasets with partitions.') for partition in self.backend.partition_index.search(search_phrase): datasets[partition.dataset_vid].p_score += partition.score datasets[partition.dataset_vid].partitions.add(partition) return list(datasets.values())
[ "def", "search", "(", "self", ",", "search_phrase", ",", "limit", "=", "None", ")", ":", "query_string", "=", "self", ".", "_make_query_from_terms", "(", "search_phrase", ")", "self", ".", "_parsed_query", "=", "query_string", "schema", "=", "self", ".", "_g...
Finds datasets by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to return. None means without limit. Returns: list of DatasetSearchResult instances.
[ "Finds", "datasets", "by", "search", "phrase", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L70-L105
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
DatasetWhooshIndex._make_query_from_terms
def _make_query_from_terms(self, terms): """ Creates a query for dataset from decomposed search terms. Args: terms (dict or unicode or string): Returns: tuple: First element is str with FTS query, second is parameters of the query. """ expanded_terms = self._expand_terms(terms) cterms = '' if expanded_terms['doc']: cterms = self.backend._and_join(expanded_terms['doc']) if expanded_terms['keywords']: if cterms: cterms = self.backend._and_join( cterms, self.backend._join_keywords(expanded_terms['keywords'])) else: cterms = self.backend._join_keywords(expanded_terms['keywords']) logger.debug('Dataset terms conversion: `{}` terms converted to `{}` query.'.format(terms, cterms)) return cterms
python
def _make_query_from_terms(self, terms): """ Creates a query for dataset from decomposed search terms. Args: terms (dict or unicode or string): Returns: tuple: First element is str with FTS query, second is parameters of the query. """ expanded_terms = self._expand_terms(terms) cterms = '' if expanded_terms['doc']: cterms = self.backend._and_join(expanded_terms['doc']) if expanded_terms['keywords']: if cterms: cterms = self.backend._and_join( cterms, self.backend._join_keywords(expanded_terms['keywords'])) else: cterms = self.backend._join_keywords(expanded_terms['keywords']) logger.debug('Dataset terms conversion: `{}` terms converted to `{}` query.'.format(terms, cterms)) return cterms
[ "def", "_make_query_from_terms", "(", "self", ",", "terms", ")", ":", "expanded_terms", "=", "self", ".", "_expand_terms", "(", "terms", ")", "cterms", "=", "''", "if", "expanded_terms", "[", "'doc'", "]", ":", "cterms", "=", "self", ".", "backend", ".", ...
Creates a query for dataset from decomposed search terms. Args: terms (dict or unicode or string): Returns: tuple: First element is str with FTS query, second is parameters of the query.
[ "Creates", "a", "query", "for", "dataset", "from", "decomposed", "search", "terms", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L107-L133
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
DatasetWhooshIndex._get_generic_schema
def _get_generic_schema(self): """ Returns whoosh's generic schema of the dataset. """ schema = Schema( vid=ID(stored=True, unique=True), # Object id title=NGRAMWORDS(), keywords=KEYWORD, # Lists of coverage identifiers, ISO time values and GVIDs, source names, source abbrev doc=TEXT) # Generated document for the core of the topic search return schema
python
def _get_generic_schema(self): """ Returns whoosh's generic schema of the dataset. """ schema = Schema( vid=ID(stored=True, unique=True), # Object id title=NGRAMWORDS(), keywords=KEYWORD, # Lists of coverage identifiers, ISO time values and GVIDs, source names, source abbrev doc=TEXT) # Generated document for the core of the topic search return schema
[ "def", "_get_generic_schema", "(", "self", ")", ":", "schema", "=", "Schema", "(", "vid", "=", "ID", "(", "stored", "=", "True", ",", "unique", "=", "True", ")", ",", "# Object id", "title", "=", "NGRAMWORDS", "(", ")", ",", "keywords", "=", "KEYWORD",...
Returns whoosh's generic schema of the dataset.
[ "Returns", "whoosh", "s", "generic", "schema", "of", "the", "dataset", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L145-L152
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
DatasetWhooshIndex._delete
def _delete(self, vid=None): """ Deletes given dataset from index. Args: vid (str): dataset vid. """ assert vid is not None, 'vid argument can not be None.' writer = self.index.writer() writer.delete_by_term('vid', vid) writer.commit()
python
def _delete(self, vid=None): """ Deletes given dataset from index. Args: vid (str): dataset vid. """ assert vid is not None, 'vid argument can not be None.' writer = self.index.writer() writer.delete_by_term('vid', vid) writer.commit()
[ "def", "_delete", "(", "self", ",", "vid", "=", "None", ")", ":", "assert", "vid", "is", "not", "None", ",", "'vid argument can not be None.'", "writer", "=", "self", ".", "index", ".", "writer", "(", ")", "writer", ".", "delete_by_term", "(", "'vid'", "...
Deletes given dataset from index. Args: vid (str): dataset vid.
[ "Deletes", "given", "dataset", "from", "index", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L154-L165
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
DatasetWhooshIndex.is_indexed
def is_indexed(self, dataset): """ Returns True if dataset is already indexed. Otherwise returns False. """ with self.index.searcher() as searcher: result = searcher.search(Term('vid', dataset.vid)) return bool(result)
python
def is_indexed(self, dataset): """ Returns True if dataset is already indexed. Otherwise returns False. """ with self.index.searcher() as searcher: result = searcher.search(Term('vid', dataset.vid)) return bool(result)
[ "def", "is_indexed", "(", "self", ",", "dataset", ")", ":", "with", "self", ".", "index", ".", "searcher", "(", ")", "as", "searcher", ":", "result", "=", "searcher", ".", "search", "(", "Term", "(", "'vid'", ",", "dataset", ".", "vid", ")", ")", "...
Returns True if dataset is already indexed. Otherwise returns False.
[ "Returns", "True", "if", "dataset", "is", "already", "indexed", ".", "Otherwise", "returns", "False", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L167-L171
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
IdentifierWhooshIndex.search
def search(self, search_phrase, limit=None): """ Finds identifier by search phrase. """ self._parsed_query = search_phrase schema = self._get_generic_schema() parser = QueryParser('name', schema=schema) query = parser.parse(search_phrase) class PosSizeWeighting(scoring.WeightingModel): def scorer(self, searcher, fieldname, text, qf=1): return self.PosSizeScorer(searcher, fieldname, text, qf=qf) class PosSizeScorer(scoring.BaseScorer): def __init__(self, searcher, fieldname, text, qf=1): self.searcher = searcher self.fieldname = fieldname self.text = text self.qf = qf self.bmf25 = scoring.BM25F() def max_quality(self): return 40 def score(self, matcher): poses = matcher.value_as('positions') return (2.0 / (poses[0] + 1) + 1.0 / (len(self.text) / 4 + 1) + self.bmf25.scorer(searcher, self.fieldname, self.text).score(matcher)) with self.index.searcher(weighting=PosSizeWeighting()) as searcher: results = searcher.search(query, limit=limit) for hit in results: vid = hit['identifier'] yield IdentifierSearchResult( score=hit.score, vid=vid, type=hit.get('type', False), name=hit.get('name', ''))
python
def search(self, search_phrase, limit=None): """ Finds identifier by search phrase. """ self._parsed_query = search_phrase schema = self._get_generic_schema() parser = QueryParser('name', schema=schema) query = parser.parse(search_phrase) class PosSizeWeighting(scoring.WeightingModel): def scorer(self, searcher, fieldname, text, qf=1): return self.PosSizeScorer(searcher, fieldname, text, qf=qf) class PosSizeScorer(scoring.BaseScorer): def __init__(self, searcher, fieldname, text, qf=1): self.searcher = searcher self.fieldname = fieldname self.text = text self.qf = qf self.bmf25 = scoring.BM25F() def max_quality(self): return 40 def score(self, matcher): poses = matcher.value_as('positions') return (2.0 / (poses[0] + 1) + 1.0 / (len(self.text) / 4 + 1) + self.bmf25.scorer(searcher, self.fieldname, self.text).score(matcher)) with self.index.searcher(weighting=PosSizeWeighting()) as searcher: results = searcher.search(query, limit=limit) for hit in results: vid = hit['identifier'] yield IdentifierSearchResult( score=hit.score, vid=vid, type=hit.get('type', False), name=hit.get('name', ''))
[ "def", "search", "(", "self", ",", "search_phrase", ",", "limit", "=", "None", ")", ":", "self", ".", "_parsed_query", "=", "search_phrase", "schema", "=", "self", ".", "_get_generic_schema", "(", ")", "parser", "=", "QueryParser", "(", "'name'", ",", "sch...
Finds identifier by search phrase.
[ "Finds", "identifier", "by", "search", "phrase", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L186-L221
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
IdentifierWhooshIndex._index_document
def _index_document(self, identifier, force=False): """ Adds identifier document to the index. """ writer = self.index.writer() all_names = set([x['name'] for x in self.index.searcher().documents()]) if identifier['name'] not in all_names: writer.add_document(**identifier) writer.commit()
python
def _index_document(self, identifier, force=False): """ Adds identifier document to the index. """ writer = self.index.writer() all_names = set([x['name'] for x in self.index.searcher().documents()]) if identifier['name'] not in all_names: writer.add_document(**identifier) writer.commit()
[ "def", "_index_document", "(", "self", ",", "identifier", ",", "force", "=", "False", ")", ":", "writer", "=", "self", ".", "index", ".", "writer", "(", ")", "all_names", "=", "set", "(", "[", "x", "[", "'name'", "]", "for", "x", "in", "self", ".",...
Adds identifier document to the index.
[ "Adds", "identifier", "document", "to", "the", "index", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L223-L229
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
IdentifierWhooshIndex._get_generic_schema
def _get_generic_schema(self): """ Returns whoosh's generic schema. """ schema = Schema( identifier=ID(stored=True), # Partition versioned id type=ID(stored=True), name=NGRAM(phrase=True, stored=True, minsize=2, maxsize=8)) return schema
python
def _get_generic_schema(self): """ Returns whoosh's generic schema. """ schema = Schema( identifier=ID(stored=True), # Partition versioned id type=ID(stored=True), name=NGRAM(phrase=True, stored=True, minsize=2, maxsize=8)) return schema
[ "def", "_get_generic_schema", "(", "self", ")", ":", "schema", "=", "Schema", "(", "identifier", "=", "ID", "(", "stored", "=", "True", ")", ",", "# Partition versioned id", "type", "=", "ID", "(", "stored", "=", "True", ")", ",", "name", "=", "NGRAM", ...
Returns whoosh's generic schema.
[ "Returns", "whoosh", "s", "generic", "schema", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L231-L237
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
IdentifierWhooshIndex._delete
def _delete(self, identifier=None): """ Deletes given identifier from index. Args: identifier (str): identifier of the document to delete. """ assert identifier is not None, 'identifier argument can not be None.' writer = self.index.writer() writer.delete_by_term('identifier', identifier) writer.commit()
python
def _delete(self, identifier=None): """ Deletes given identifier from index. Args: identifier (str): identifier of the document to delete. """ assert identifier is not None, 'identifier argument can not be None.' writer = self.index.writer() writer.delete_by_term('identifier', identifier) writer.commit()
[ "def", "_delete", "(", "self", ",", "identifier", "=", "None", ")", ":", "assert", "identifier", "is", "not", "None", ",", "'identifier argument can not be None.'", "writer", "=", "self", ".", "index", ".", "writer", "(", ")", "writer", ".", "delete_by_term", ...
Deletes given identifier from index. Args: identifier (str): identifier of the document to delete.
[ "Deletes", "given", "identifier", "from", "index", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L239-L249
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
IdentifierWhooshIndex.is_indexed
def is_indexed(self, identifier): """ Returns True if identifier is already indexed. Otherwise returns False. """ with self.index.searcher() as searcher: result = searcher.search(Term('identifier', identifier['identifier'])) return bool(result)
python
def is_indexed(self, identifier): """ Returns True if identifier is already indexed. Otherwise returns False. """ with self.index.searcher() as searcher: result = searcher.search(Term('identifier', identifier['identifier'])) return bool(result)
[ "def", "is_indexed", "(", "self", ",", "identifier", ")", ":", "with", "self", ".", "index", ".", "searcher", "(", ")", "as", "searcher", ":", "result", "=", "searcher", ".", "search", "(", "Term", "(", "'identifier'", ",", "identifier", "[", "'identifie...
Returns True if identifier is already indexed. Otherwise returns False.
[ "Returns", "True", "if", "identifier", "is", "already", "indexed", ".", "Otherwise", "returns", "False", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L251-L255
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
PartitionWhooshIndex.all
def all(self): """ Returns list with all indexed partitions. """ partitions = [] for partition in self.index.searcher().documents(): partitions.append( PartitionSearchResult(dataset_vid=partition['dataset_vid'], vid=partition['vid'], score=1)) return partitions
python
def all(self): """ Returns list with all indexed partitions. """ partitions = [] for partition in self.index.searcher().documents(): partitions.append( PartitionSearchResult(dataset_vid=partition['dataset_vid'], vid=partition['vid'], score=1)) return partitions
[ "def", "all", "(", "self", ")", ":", "partitions", "=", "[", "]", "for", "partition", "in", "self", ".", "index", ".", "searcher", "(", ")", ".", "documents", "(", ")", ":", "partitions", ".", "append", "(", "PartitionSearchResult", "(", "dataset_vid", ...
Returns list with all indexed partitions.
[ "Returns", "list", "with", "all", "indexed", "partitions", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L270-L276
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
PartitionWhooshIndex.search
def search(self, search_phrase, limit=None): """ Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Yields: PartitionSearchResult instances. """ query_string = self._make_query_from_terms(search_phrase) self._parsed_query = query_string schema = self._get_generic_schema() parser = QueryParser('doc', schema=schema) query = parser.parse(query_string) logger.debug('Searching partitions using `{}` query.'.format(query)) with self.index.searcher() as searcher: results = searcher.search(query, limit=limit) for hit in results: yield PartitionSearchResult( vid=hit['vid'], dataset_vid=hit['dataset_vid'], score=hit.score)
python
def search(self, search_phrase, limit=None): """ Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Yields: PartitionSearchResult instances. """ query_string = self._make_query_from_terms(search_phrase) self._parsed_query = query_string schema = self._get_generic_schema() parser = QueryParser('doc', schema=schema) query = parser.parse(query_string) logger.debug('Searching partitions using `{}` query.'.format(query)) with self.index.searcher() as searcher: results = searcher.search(query, limit=limit) for hit in results: yield PartitionSearchResult( vid=hit['vid'], dataset_vid=hit['dataset_vid'], score=hit.score)
[ "def", "search", "(", "self", ",", "search_phrase", ",", "limit", "=", "None", ")", ":", "query_string", "=", "self", ".", "_make_query_from_terms", "(", "search_phrase", ")", "self", ".", "_parsed_query", "=", "query_string", "schema", "=", "self", ".", "_g...
Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Yields: PartitionSearchResult instances.
[ "Finds", "partitions", "by", "search", "phrase", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L278-L300
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
PartitionWhooshIndex._make_query_from_terms
def _make_query_from_terms(self, terms): """ returns a FTS query for partition created from decomposed search terms. args: terms (dict or str): returns: str containing fts query. """ expanded_terms = self._expand_terms(terms) cterms = '' if expanded_terms['doc']: cterms = self.backend._or_join(expanded_terms['doc']) keywords = expanded_terms['keywords'] frm_to = self._from_to_as_term(expanded_terms['from'], expanded_terms['to']) if frm_to: keywords.append(frm_to) if keywords: if cterms: cterms = self.backend._and_join( [cterms, self.backend._field_term('keywords', expanded_terms['keywords'])]) else: cterms = self.backend._field_term('keywords', expanded_terms['keywords']) logger.debug('partition terms conversion: `{}` terms converted to `{}` query.'.format(terms, cterms)) return cterms
python
def _make_query_from_terms(self, terms): """ returns a FTS query for partition created from decomposed search terms. args: terms (dict or str): returns: str containing fts query. """ expanded_terms = self._expand_terms(terms) cterms = '' if expanded_terms['doc']: cterms = self.backend._or_join(expanded_terms['doc']) keywords = expanded_terms['keywords'] frm_to = self._from_to_as_term(expanded_terms['from'], expanded_terms['to']) if frm_to: keywords.append(frm_to) if keywords: if cterms: cterms = self.backend._and_join( [cterms, self.backend._field_term('keywords', expanded_terms['keywords'])]) else: cterms = self.backend._field_term('keywords', expanded_terms['keywords']) logger.debug('partition terms conversion: `{}` terms converted to `{}` query.'.format(terms, cterms)) return cterms
[ "def", "_make_query_from_terms", "(", "self", ",", "terms", ")", ":", "expanded_terms", "=", "self", ".", "_expand_terms", "(", "terms", ")", "cterms", "=", "''", "if", "expanded_terms", "[", "'doc'", "]", ":", "cterms", "=", "self", ".", "backend", ".", ...
returns a FTS query for partition created from decomposed search terms. args: terms (dict or str): returns: str containing fts query.
[ "returns", "a", "FTS", "query", "for", "partition", "created", "from", "decomposed", "search", "terms", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L308-L341
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
PartitionWhooshIndex._from_to_as_term
def _from_to_as_term(self, frm, to): """ Turns from and to into the query format. Args: frm (str): from year to (str): to year Returns: FTS query str with years range. """ # The wackiness with the conversion to int and str, and adding ' ', is because there # can't be a space between the 'TO' and the brackets in the time range # when one end is open from_year = '' to_year = '' def year_or_empty(prefix, year, suffix): try: return prefix + str(int(year)) + suffix except (ValueError, TypeError): return '' if frm: from_year = year_or_empty('', frm, ' ') if to: to_year = year_or_empty(' ', to, '') if bool(from_year) or bool(to_year): return '[{}TO{}]'.format(from_year, to_year) else: return None
python
def _from_to_as_term(self, frm, to): """ Turns from and to into the query format. Args: frm (str): from year to (str): to year Returns: FTS query str with years range. """ # The wackiness with the conversion to int and str, and adding ' ', is because there # can't be a space between the 'TO' and the brackets in the time range # when one end is open from_year = '' to_year = '' def year_or_empty(prefix, year, suffix): try: return prefix + str(int(year)) + suffix except (ValueError, TypeError): return '' if frm: from_year = year_or_empty('', frm, ' ') if to: to_year = year_or_empty(' ', to, '') if bool(from_year) or bool(to_year): return '[{}TO{}]'.format(from_year, to_year) else: return None
[ "def", "_from_to_as_term", "(", "self", ",", "frm", ",", "to", ")", ":", "# The wackiness with the conversion to int and str, and adding ' ', is because there", "# can't be a space between the 'TO' and the brackets in the time range", "# when one end is open", "from_year", "=", "''", ...
Turns from and to into the query format. Args: frm (str): from year to (str): to year Returns: FTS query str with years range.
[ "Turns", "from", "and", "to", "into", "the", "query", "format", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L343-L376
CivicSpleen/ambry
ambry/library/search_backends/whoosh_backend.py
PartitionWhooshIndex._index_document
def _index_document(self, document, force=False): """ Adds parition document to the index. """ if force: self._delete(vid=document['vid']) writer = self.index.writer() writer.add_document(**document) writer.commit()
python
def _index_document(self, document, force=False): """ Adds parition document to the index. """ if force: self._delete(vid=document['vid']) writer = self.index.writer() writer.add_document(**document) writer.commit()
[ "def", "_index_document", "(", "self", ",", "document", ",", "force", "=", "False", ")", ":", "if", "force", ":", "self", ".", "_delete", "(", "vid", "=", "document", "[", "'vid'", "]", ")", "writer", "=", "self", ".", "index", ".", "writer", "(", ...
Adds parition document to the index.
[ "Adds", "parition", "document", "to", "the", "index", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L378-L385
andreafioraldi/angrdbg
angrdbg/memory_8.py
SimSymbolicDbgMemory.copy
def copy(self, _): """ Return a copy of the SimMemory. """ #l.debug("Copying %d bytes of memory with id %s." % (len(self.mem), self.id)) c = SimSymbolicDbgMemory( mem=self.mem.branch(), memory_id=self.id, endness=self.endness, abstract_backer=self._abstract_backer, read_strategies=[ s.copy() for s in self.read_strategies ], write_strategies=[ s.copy() for s in self.write_strategies ], stack_region_map=self._stack_region_map, generic_region_map=self._generic_region_map ) return c
python
def copy(self, _): """ Return a copy of the SimMemory. """ #l.debug("Copying %d bytes of memory with id %s." % (len(self.mem), self.id)) c = SimSymbolicDbgMemory( mem=self.mem.branch(), memory_id=self.id, endness=self.endness, abstract_backer=self._abstract_backer, read_strategies=[ s.copy() for s in self.read_strategies ], write_strategies=[ s.copy() for s in self.write_strategies ], stack_region_map=self._stack_region_map, generic_region_map=self._generic_region_map ) return c
[ "def", "copy", "(", "self", ",", "_", ")", ":", "#l.debug(\"Copying %d bytes of memory with id %s.\" % (len(self.mem), self.id))", "c", "=", "SimSymbolicDbgMemory", "(", "mem", "=", "self", ".", "mem", ".", "branch", "(", ")", ",", "memory_id", "=", "self", ".", ...
Return a copy of the SimMemory.
[ "Return", "a", "copy", "of", "the", "SimMemory", "." ]
train
https://github.com/andreafioraldi/angrdbg/blob/939b20fb9b341aee695d2db12142b1eddc5b555a/angrdbg/memory_8.py#L74-L90
CivicSpleen/ambry
ambry/pands.py
AmbrySeries.column
def column(self): """Return the ambry column""" from ambry.orm.exc import NotFoundError if not hasattr(self, 'partition'): return None if not self.name: return None try: try: return self.partition.column(self.name) except AttributeError: return self.partition.table.column(self.name) except NotFoundError: return None
python
def column(self): """Return the ambry column""" from ambry.orm.exc import NotFoundError if not hasattr(self, 'partition'): return None if not self.name: return None try: try: return self.partition.column(self.name) except AttributeError: return self.partition.table.column(self.name) except NotFoundError: return None
[ "def", "column", "(", "self", ")", ":", "from", "ambry", ".", "orm", ".", "exc", "import", "NotFoundError", "if", "not", "hasattr", "(", "self", ",", "'partition'", ")", ":", "return", "None", "if", "not", "self", ".", "name", ":", "return", "None", ...
Return the ambry column
[ "Return", "the", "ambry", "column" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/pands.py#L27-L43
spotify/ulogger
ulogger/syslog.py
get_handler
def get_handler(progname, address=None, proto=None, facility=None, fmt=None, datefmt=None, **_): """Helper function to create a Syslog handler. See `ulogger.syslog.SyslogHandlerBuilder` for arguments and supported keyword arguments. Returns: (obj): Instance of `logging.SysLogHandler` """ builder = SyslogHandlerBuilder( progname, address=address, proto=proto, facility=facility, fmt=fmt, datefmt=datefmt) return builder.get_handler()
python
def get_handler(progname, address=None, proto=None, facility=None, fmt=None, datefmt=None, **_): """Helper function to create a Syslog handler. See `ulogger.syslog.SyslogHandlerBuilder` for arguments and supported keyword arguments. Returns: (obj): Instance of `logging.SysLogHandler` """ builder = SyslogHandlerBuilder( progname, address=address, proto=proto, facility=facility, fmt=fmt, datefmt=datefmt) return builder.get_handler()
[ "def", "get_handler", "(", "progname", ",", "address", "=", "None", ",", "proto", "=", "None", ",", "facility", "=", "None", ",", "fmt", "=", "None", ",", "datefmt", "=", "None", ",", "*", "*", "_", ")", ":", "builder", "=", "SyslogHandlerBuilder", "...
Helper function to create a Syslog handler. See `ulogger.syslog.SyslogHandlerBuilder` for arguments and supported keyword arguments. Returns: (obj): Instance of `logging.SysLogHandler`
[ "Helper", "function", "to", "create", "a", "Syslog", "handler", "." ]
train
https://github.com/spotify/ulogger/blob/c59ced69e55b400e9c7a3688145fe3e8cb89db13/ulogger/syslog.py#L141-L154
project-ncl/pnc-cli
pnc_cli/swagger_client/models/target_repository_rest.py
TargetRepositoryRest.repository_type
def repository_type(self, repository_type): """ Sets the repository_type of this TargetRepositoryRest. :param repository_type: The repository_type of this TargetRepositoryRest. :type: str """ allowed_values = ["MAVEN", "NPM", "COCOA_POD", "GENERIC_PROXY"] if repository_type not in allowed_values: raise ValueError( "Invalid value for `repository_type` ({0}), must be one of {1}" .format(repository_type, allowed_values) ) self._repository_type = repository_type
python
def repository_type(self, repository_type): """ Sets the repository_type of this TargetRepositoryRest. :param repository_type: The repository_type of this TargetRepositoryRest. :type: str """ allowed_values = ["MAVEN", "NPM", "COCOA_POD", "GENERIC_PROXY"] if repository_type not in allowed_values: raise ValueError( "Invalid value for `repository_type` ({0}), must be one of {1}" .format(repository_type, allowed_values) ) self._repository_type = repository_type
[ "def", "repository_type", "(", "self", ",", "repository_type", ")", ":", "allowed_values", "=", "[", "\"MAVEN\"", ",", "\"NPM\"", ",", "\"COCOA_POD\"", ",", "\"GENERIC_PROXY\"", "]", "if", "repository_type", "not", "in", "allowed_values", ":", "raise", "ValueError...
Sets the repository_type of this TargetRepositoryRest. :param repository_type: The repository_type of this TargetRepositoryRest. :type: str
[ "Sets", "the", "repository_type", "of", "this", "TargetRepositoryRest", "." ]
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/models/target_repository_rest.py#L150-L164
CivicSpleen/ambry
ambry/bundle/concurrent.py
worker
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None): """ Custom worker for bundle operations :param inqueue: :param outqueue: :param initializer: :param initargs: :param maxtasks: :return: """ from ambry.library import new_library from ambry.run import get_runconfig import traceback assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) put = outqueue.put get = inqueue.get if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader.close() if initializer is not None: initializer(*initargs) try: task = get() except (EOFError, IOError): debug('worker got EOFError or IOError -- exiting') return if task is None: debug('worker got sentinel -- exiting') return job, i, func, args, kwds = task # func = mapstar = map(*args) # Since there is only one source build per process, we know the structure # of the args beforehand. mp_func = args[0][0] mp_args = list(args[0][1][0]) library = new_library(get_runconfig()) library.database.close() # Maybe it is still open after the fork. library.init_debug() bundle_vid = mp_args[0] try: b = library.bundle(bundle_vid) library.logger = b.logger # So library logs to the same file as the bundle. b = b.cast_to_subclass() b.multi = True # In parent it is a number, in child, just needs to be true to get the right logger template b.is_subprocess = True b.limited_run = bool(int(os.getenv('AMBRY_LIMITED_RUN', 0))) assert b._progress == None # Don't want to share connections across processes mp_args[0] = b result = (True, [mp_func(*mp_args)]) except Exception as e: import traceback tb = traceback.format_exc() b.error('Subprocess {} raised an exception: {}'.format(os.getpid(), e.message), False) b.error(tb, False) result = (False, e) assert result b.progress.close() library.close() try: put((job, i, result)) except Exception as e: wrapped = MaybeEncodingError(e, result[1]) debug("Possible encoding error while sending result: %s" % (wrapped)) put((job, i, (False, wrapped)))
python
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None): """ Custom worker for bundle operations :param inqueue: :param outqueue: :param initializer: :param initargs: :param maxtasks: :return: """ from ambry.library import new_library from ambry.run import get_runconfig import traceback assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) put = outqueue.put get = inqueue.get if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader.close() if initializer is not None: initializer(*initargs) try: task = get() except (EOFError, IOError): debug('worker got EOFError or IOError -- exiting') return if task is None: debug('worker got sentinel -- exiting') return job, i, func, args, kwds = task # func = mapstar = map(*args) # Since there is only one source build per process, we know the structure # of the args beforehand. mp_func = args[0][0] mp_args = list(args[0][1][0]) library = new_library(get_runconfig()) library.database.close() # Maybe it is still open after the fork. library.init_debug() bundle_vid = mp_args[0] try: b = library.bundle(bundle_vid) library.logger = b.logger # So library logs to the same file as the bundle. b = b.cast_to_subclass() b.multi = True # In parent it is a number, in child, just needs to be true to get the right logger template b.is_subprocess = True b.limited_run = bool(int(os.getenv('AMBRY_LIMITED_RUN', 0))) assert b._progress == None # Don't want to share connections across processes mp_args[0] = b result = (True, [mp_func(*mp_args)]) except Exception as e: import traceback tb = traceback.format_exc() b.error('Subprocess {} raised an exception: {}'.format(os.getpid(), e.message), False) b.error(tb, False) result = (False, e) assert result b.progress.close() library.close() try: put((job, i, result)) except Exception as e: wrapped = MaybeEncodingError(e, result[1]) debug("Possible encoding error while sending result: %s" % (wrapped)) put((job, i, (False, wrapped)))
[ "def", "worker", "(", "inqueue", ",", "outqueue", ",", "initializer", "=", "None", ",", "initargs", "=", "(", ")", ",", "maxtasks", "=", "None", ")", ":", "from", "ambry", ".", "library", "import", "new_library", "from", "ambry", ".", "run", "import", ...
Custom worker for bundle operations :param inqueue: :param outqueue: :param initializer: :param initargs: :param maxtasks: :return:
[ "Custom", "worker", "for", "bundle", "operations" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/concurrent.py#L19-L102
CivicSpleen/ambry
ambry/bundle/concurrent.py
init_library
def init_library(database_dsn, accounts_password, limited_run = False): """Child initializer, setup in Library.process_pool""" import os import signal # Have the child processes ignore the keyboard interrupt, and other signals. Instead, the parent will # catch these, and clean up the children. signal.signal(signal.SIGINT, signal.SIG_IGN) #signal.signal(signal.SIGTERM, sigterm_handler) os.environ['AMBRY_DB'] = database_dsn if accounts_password: os.environ['AMBRY_PASSWORD'] = accounts_password os.environ['AMBRY_LIMITED_RUN'] = '1' if limited_run else '0'
python
def init_library(database_dsn, accounts_password, limited_run = False): """Child initializer, setup in Library.process_pool""" import os import signal # Have the child processes ignore the keyboard interrupt, and other signals. Instead, the parent will # catch these, and clean up the children. signal.signal(signal.SIGINT, signal.SIG_IGN) #signal.signal(signal.SIGTERM, sigterm_handler) os.environ['AMBRY_DB'] = database_dsn if accounts_password: os.environ['AMBRY_PASSWORD'] = accounts_password os.environ['AMBRY_LIMITED_RUN'] = '1' if limited_run else '0'
[ "def", "init_library", "(", "database_dsn", ",", "accounts_password", ",", "limited_run", "=", "False", ")", ":", "import", "os", "import", "signal", "# Have the child processes ignore the keyboard interrupt, and other signals. Instead, the parent will", "# catch these, and clean u...
Child initializer, setup in Library.process_pool
[ "Child", "initializer", "setup", "in", "Library", ".", "process_pool" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/concurrent.py#L137-L151
CivicSpleen/ambry
ambry/bundle/concurrent.py
build_mp
def build_mp(b, stage, source_name, force): """Ingest a source, using only arguments that can be pickled, for multiprocessing access""" source = b.source(source_name) with b.progress.start('build_mp',stage,message="MP build", source=source) as ps: ps.add(message='Running source {}'.format(source.name), source=source, state='running') r = b.build_source(stage, source, ps, force) return r
python
def build_mp(b, stage, source_name, force): """Ingest a source, using only arguments that can be pickled, for multiprocessing access""" source = b.source(source_name) with b.progress.start('build_mp',stage,message="MP build", source=source) as ps: ps.add(message='Running source {}'.format(source.name), source=source, state='running') r = b.build_source(stage, source, ps, force) return r
[ "def", "build_mp", "(", "b", ",", "stage", ",", "source_name", ",", "force", ")", ":", "source", "=", "b", ".", "source", "(", "source_name", ")", "with", "b", ".", "progress", ".", "start", "(", "'build_mp'", ",", "stage", ",", "message", "=", "\"MP...
Ingest a source, using only arguments that can be pickled, for multiprocessing access
[ "Ingest", "a", "source", "using", "only", "arguments", "that", "can", "be", "pickled", "for", "multiprocessing", "access" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/concurrent.py#L154-L163
CivicSpleen/ambry
ambry/bundle/concurrent.py
unify_mp
def unify_mp(b, partition_name): """Unify all of the segment partitions for a parent partition, then run stats on the MPR file""" with b.progress.start('coalesce_mp',0,message="MP coalesce {}".format(partition_name)) as ps: r = b.unify_partition(partition_name, None, ps) return r
python
def unify_mp(b, partition_name): """Unify all of the segment partitions for a parent partition, then run stats on the MPR file""" with b.progress.start('coalesce_mp',0,message="MP coalesce {}".format(partition_name)) as ps: r = b.unify_partition(partition_name, None, ps) return r
[ "def", "unify_mp", "(", "b", ",", "partition_name", ")", ":", "with", "b", ".", "progress", ".", "start", "(", "'coalesce_mp'", ",", "0", ",", "message", "=", "\"MP coalesce {}\"", ".", "format", "(", "partition_name", ")", ")", "as", "ps", ":", "r", "...
Unify all of the segment partitions for a parent partition, then run stats on the MPR file
[ "Unify", "all", "of", "the", "segment", "partitions", "for", "a", "parent", "partition", "then", "run", "stats", "on", "the", "MPR", "file" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/concurrent.py#L166-L172
CivicSpleen/ambry
ambry/bundle/concurrent.py
ingest_mp
def ingest_mp(b, stage, source_name, clean_files): """Ingest a source, using only arguments that can be pickled, for multiprocessing access""" source = b.source(source_name) with b.progress.start('ingest_mp',0,message="MP ingestion", source=source) as ps: r = b._ingest_source(source, ps, clean_files) return r
python
def ingest_mp(b, stage, source_name, clean_files): """Ingest a source, using only arguments that can be pickled, for multiprocessing access""" source = b.source(source_name) with b.progress.start('ingest_mp',0,message="MP ingestion", source=source) as ps: r = b._ingest_source(source, ps, clean_files) return r
[ "def", "ingest_mp", "(", "b", ",", "stage", ",", "source_name", ",", "clean_files", ")", ":", "source", "=", "b", ".", "source", "(", "source_name", ")", "with", "b", ".", "progress", ".", "start", "(", "'ingest_mp'", ",", "0", ",", "message", "=", "...
Ingest a source, using only arguments that can be pickled, for multiprocessing access
[ "Ingest", "a", "source", "using", "only", "arguments", "that", "can", "be", "pickled", "for", "multiprocessing", "access" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/concurrent.py#L175-L183
CivicSpleen/ambry
ambry/bundle/concurrent.py
Pool._repopulate_pool
def _repopulate_pool(self): """Bring the number of pool processes up to the specified number, for use after reaping workers which have exited. """ for i in range(self._processes - len(self._pool)): w = self.Process(target=self._worker_f, args=(self._inqueue, self._outqueue, self._initializer, self._initargs, self._maxtasksperchild)) self._pool.append(w) w.name = w.name.replace('Process', 'PoolWorker') w.daemon = True w.start() debug('added worker')
python
def _repopulate_pool(self): """Bring the number of pool processes up to the specified number, for use after reaping workers which have exited. """ for i in range(self._processes - len(self._pool)): w = self.Process(target=self._worker_f, args=(self._inqueue, self._outqueue, self._initializer, self._initargs, self._maxtasksperchild)) self._pool.append(w) w.name = w.name.replace('Process', 'PoolWorker') w.daemon = True w.start() debug('added worker')
[ "def", "_repopulate_pool", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "_processes", "-", "len", "(", "self", ".", "_pool", ")", ")", ":", "w", "=", "self", ".", "Process", "(", "target", "=", "self", ".", "_worker_f", ",", ...
Bring the number of pool processes up to the specified number, for use after reaping workers which have exited.
[ "Bring", "the", "number", "of", "pool", "processes", "up", "to", "the", "specified", "number", "for", "use", "after", "reaping", "workers", "which", "have", "exited", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/concurrent.py#L118-L131
CivicSpleen/ambry
ambry/library/filesystem.py
LibraryFilesystem._compose
def _compose(self, name, args, mkdir=True): """Get a named filesystem entry, and extend it into a path with additional path arguments""" from os.path import normpath from ambry.dbexceptions import ConfigurationError root = p = self._config.filesystem[name].format(root=self._root) if args: args = [e.strip() for e in args] p = join(p, *args) if not isdir(p) and mkdir: makedirs(p) p = normpath(p) if not p.startswith(root): raise ConfigurationError("Path for name='{}', args={} resolved outside of define filesystem root" .format(name, args)) return p
python
def _compose(self, name, args, mkdir=True): """Get a named filesystem entry, and extend it into a path with additional path arguments""" from os.path import normpath from ambry.dbexceptions import ConfigurationError root = p = self._config.filesystem[name].format(root=self._root) if args: args = [e.strip() for e in args] p = join(p, *args) if not isdir(p) and mkdir: makedirs(p) p = normpath(p) if not p.startswith(root): raise ConfigurationError("Path for name='{}', args={} resolved outside of define filesystem root" .format(name, args)) return p
[ "def", "_compose", "(", "self", ",", "name", ",", "args", ",", "mkdir", "=", "True", ")", ":", "from", "os", ".", "path", "import", "normpath", "from", "ambry", ".", "dbexceptions", "import", "ConfigurationError", "root", "=", "p", "=", "self", ".", "_...
Get a named filesystem entry, and extend it into a path with additional path arguments
[ "Get", "a", "named", "filesystem", "entry", "and", "extend", "it", "into", "a", "path", "with", "additional", "path", "arguments" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/filesystem.py#L23-L44
CivicSpleen/ambry
ambry/library/filesystem.py
LibraryFilesystem.compose
def compose(self, name, *args): """Compose, but don't create base directory""" return self._compose(name, args, mkdir=False)
python
def compose(self, name, *args): """Compose, but don't create base directory""" return self._compose(name, args, mkdir=False)
[ "def", "compose", "(", "self", ",", "name", ",", "*", "args", ")", ":", "return", "self", ".", "_compose", "(", "name", ",", "args", ",", "mkdir", "=", "False", ")" ]
Compose, but don't create base directory
[ "Compose", "but", "don", "t", "create", "base", "directory" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/filesystem.py#L46-L49
CivicSpleen/ambry
ambry/library/filesystem.py
LibraryFilesystem.database_dsn
def database_dsn(self): """Substitute the root dir into the database DSN, for Sqlite""" if not self._config.library.database: return 'sqlite:///{root}/library.db'.format(root=self._root) return self._config.library.database.format(root=self._root)
python
def database_dsn(self): """Substitute the root dir into the database DSN, for Sqlite""" if not self._config.library.database: return 'sqlite:///{root}/library.db'.format(root=self._root) return self._config.library.database.format(root=self._root)
[ "def", "database_dsn", "(", "self", ")", ":", "if", "not", "self", ".", "_config", ".", "library", ".", "database", ":", "return", "'sqlite:///{root}/library.db'", ".", "format", "(", "root", "=", "self", ".", "_root", ")", "return", "self", ".", "_config"...
Substitute the root dir into the database DSN, for Sqlite
[ "Substitute", "the", "root", "dir", "into", "the", "database", "DSN", "for", "Sqlite" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/filesystem.py#L86-L92
CivicSpleen/ambry
ambry/etl/pipeline.py
make_table_map
def make_table_map(table, headers): """Create a function to map from rows with the structure of the headers to the structure of the table.""" header_parts = {} for i, h in enumerate(headers): header_parts[h] = 'row[{}]'.format(i) body_code = 'lambda row: [{}]'.format(','.join(header_parts.get(c.name, 'None') for c in table.columns)) header_code = 'lambda row: [{}]'.format( ','.join(header_parts.get(c.name, "'{}'".format(c.name)) for c in table.columns)) return eval(header_code), eval(body_code)
python
def make_table_map(table, headers): """Create a function to map from rows with the structure of the headers to the structure of the table.""" header_parts = {} for i, h in enumerate(headers): header_parts[h] = 'row[{}]'.format(i) body_code = 'lambda row: [{}]'.format(','.join(header_parts.get(c.name, 'None') for c in table.columns)) header_code = 'lambda row: [{}]'.format( ','.join(header_parts.get(c.name, "'{}'".format(c.name)) for c in table.columns)) return eval(header_code), eval(body_code)
[ "def", "make_table_map", "(", "table", ",", "headers", ")", ":", "header_parts", "=", "{", "}", "for", "i", ",", "h", "in", "enumerate", "(", "headers", ")", ":", "header_parts", "[", "h", "]", "=", "'row[{}]'", ".", "format", "(", "i", ")", "body_co...
Create a function to map from rows with the structure of the headers to the structure of the table.
[ "Create", "a", "function", "to", "map", "from", "rows", "with", "the", "structure", "of", "the", "headers", "to", "the", "structure", "of", "the", "table", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L1718-L1729
CivicSpleen/ambry
ambry/etl/pipeline.py
augment_pipeline
def augment_pipeline(pl, head_pipe=None, tail_pipe=None): """ Augment the pipeline by adding a new pipe section to each stage that has one or more pipes. Can be used for debugging :param pl: :param DebugPipe: :return: """ for k, v in iteritems(pl): if v and len(v) > 0: if head_pipe and k != 'source': # Can't put anything before the source. v.insert(0, head_pipe) if tail_pipe: v.append(tail_pipe)
python
def augment_pipeline(pl, head_pipe=None, tail_pipe=None): """ Augment the pipeline by adding a new pipe section to each stage that has one or more pipes. Can be used for debugging :param pl: :param DebugPipe: :return: """ for k, v in iteritems(pl): if v and len(v) > 0: if head_pipe and k != 'source': # Can't put anything before the source. v.insert(0, head_pipe) if tail_pipe: v.append(tail_pipe)
[ "def", "augment_pipeline", "(", "pl", ",", "head_pipe", "=", "None", ",", "tail_pipe", "=", "None", ")", ":", "for", "k", ",", "v", "in", "iteritems", "(", "pl", ")", ":", "if", "v", "and", "len", "(", "v", ")", ">", "0", ":", "if", "head_pipe", ...
Augment the pipeline by adding a new pipe section to each stage that has one or more pipes. Can be used for debugging :param pl: :param DebugPipe: :return:
[ "Augment", "the", "pipeline", "by", "adding", "a", "new", "pipe", "section", "to", "each", "stage", "that", "has", "one", "or", "more", "pipes", ".", "Can", "be", "used", "for", "debugging" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L2386-L2401
CivicSpleen/ambry
ambry/etl/pipeline.py
_to_ascii
def _to_ascii(s): """ Converts given string to ascii ignoring non ascii. Args: s (text or binary): Returns: str: """ # TODO: Always use unicode within ambry. from six import text_type, binary_type if isinstance(s, text_type): ascii_ = s.encode('ascii', 'ignore') elif isinstance(s, binary_type): ascii_ = s.decode('utf-8').encode('ascii', 'ignore') else: raise Exception('Unknown text type - {}'.format(type(s))) return ascii_
python
def _to_ascii(s): """ Converts given string to ascii ignoring non ascii. Args: s (text or binary): Returns: str: """ # TODO: Always use unicode within ambry. from six import text_type, binary_type if isinstance(s, text_type): ascii_ = s.encode('ascii', 'ignore') elif isinstance(s, binary_type): ascii_ = s.decode('utf-8').encode('ascii', 'ignore') else: raise Exception('Unknown text type - {}'.format(type(s))) return ascii_
[ "def", "_to_ascii", "(", "s", ")", ":", "# TODO: Always use unicode within ambry.", "from", "six", "import", "text_type", ",", "binary_type", "if", "isinstance", "(", "s", ",", "text_type", ")", ":", "ascii_", "=", "s", ".", "encode", "(", "'ascii'", ",", "'...
Converts given string to ascii ignoring non ascii. Args: s (text or binary): Returns: str:
[ "Converts", "given", "string", "to", "ascii", "ignoring", "non", "ascii", ".", "Args", ":", "s", "(", "text", "or", "binary", ")", ":" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L2404-L2420
CivicSpleen/ambry
ambry/etl/pipeline.py
Sink.report_progress
def report_progress(self): """ This function can be called from a higher level to report progress. It is usually called from an alarm signal handler which is installed just before starting an operation: :return: Tuple: (process description, #records, #total records, #rate) """ from time import time # rows, rate = pl.sink.report_progress() return (self.i, round(float(self.i) / float(time() - self._start_time), 2))
python
def report_progress(self): """ This function can be called from a higher level to report progress. It is usually called from an alarm signal handler which is installed just before starting an operation: :return: Tuple: (process description, #records, #total records, #rate) """ from time import time # rows, rate = pl.sink.report_progress() return (self.i, round(float(self.i) / float(time() - self._start_time), 2))
[ "def", "report_progress", "(", "self", ")", ":", "from", "time", "import", "time", "# rows, rate = pl.sink.report_progress()", "return", "(", "self", ".", "i", ",", "round", "(", "float", "(", "self", ".", "i", ")", "/", "float", "(", "time", "(", ")", "...
This function can be called from a higher level to report progress. It is usually called from an alarm signal handler which is installed just before starting an operation: :return: Tuple: (process description, #records, #total records, #rate)
[ "This", "function", "can", "be", "called", "from", "a", "higher", "level", "to", "report", "progress", ".", "It", "is", "usually", "called", "from", "an", "alarm", "signal", "handler", "which", "is", "installed", "just", "before", "starting", "an", "operatio...
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L486-L496
CivicSpleen/ambry
ambry/etl/pipeline.py
Slice.parse
def parse(v): """ Parse a slice string, of the same form as used by __getitem__ >>> Slice.parse("2:3,7,10:12") :param v: Input string :return: A list of tuples, one for each element of the slice string """ parts = v.split(',') slices = [] for part in parts: p = part.split(':') if len(p) == 1: slices.append(int(p[0])) elif len(p) == 2: slices.append(tuple(p)) else: raise ValueError("Too many ':': {}".format(part)) return slices
python
def parse(v): """ Parse a slice string, of the same form as used by __getitem__ >>> Slice.parse("2:3,7,10:12") :param v: Input string :return: A list of tuples, one for each element of the slice string """ parts = v.split(',') slices = [] for part in parts: p = part.split(':') if len(p) == 1: slices.append(int(p[0])) elif len(p) == 2: slices.append(tuple(p)) else: raise ValueError("Too many ':': {}".format(part)) return slices
[ "def", "parse", "(", "v", ")", ":", "parts", "=", "v", ".", "split", "(", "','", ")", "slices", "=", "[", "]", "for", "part", "in", "parts", ":", "p", "=", "part", ".", "split", "(", "':'", ")", "if", "len", "(", "p", ")", "==", "1", ":", ...
Parse a slice string, of the same form as used by __getitem__ >>> Slice.parse("2:3,7,10:12") :param v: Input string :return: A list of tuples, one for each element of the slice string
[ "Parse", "a", "slice", "string", "of", "the", "same", "form", "as", "used", "by", "__getitem__" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L596-L620
CivicSpleen/ambry
ambry/etl/pipeline.py
ReplaceWithDestHeader.process_header
def process_header(self, headers): """Ignore the incomming header and replace it with the destination header""" return [c.name for c in self.source.dest_table.columns][1:]
python
def process_header(self, headers): """Ignore the incomming header and replace it with the destination header""" return [c.name for c in self.source.dest_table.columns][1:]
[ "def", "process_header", "(", "self", ",", "headers", ")", ":", "return", "[", "c", ".", "name", "for", "c", "in", "self", ".", "source", ".", "dest_table", ".", "columns", "]", "[", "1", ":", "]" ]
Ignore the incomming header and replace it with the destination header
[ "Ignore", "the", "incomming", "header", "and", "replace", "it", "with", "the", "destination", "header" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L858-L861
CivicSpleen/ambry
ambry/etl/pipeline.py
MangleHeader.mangle_column_name
def mangle_column_name(self, i, n): """ Override this method to change the way that column names from the source are altered to become column names in the schema. This method is called from :py:meth:`mangle_header` for each column in the header, and :py:meth:`mangle_header` is called from the RowGenerator, so it will alter the row both when the schema is being generated and when data are being inserted into the partition. Implement it in your bundle class to change the how columsn are converted from the source into database-friendly names :param i: Column number :param n: Original column name :return: A new column name """ from ambry.orm import Column if not n: return 'column{}'.format(i) mn = Column.mangle_name(str(n).strip()) return mn
python
def mangle_column_name(self, i, n): """ Override this method to change the way that column names from the source are altered to become column names in the schema. This method is called from :py:meth:`mangle_header` for each column in the header, and :py:meth:`mangle_header` is called from the RowGenerator, so it will alter the row both when the schema is being generated and when data are being inserted into the partition. Implement it in your bundle class to change the how columsn are converted from the source into database-friendly names :param i: Column number :param n: Original column name :return: A new column name """ from ambry.orm import Column if not n: return 'column{}'.format(i) mn = Column.mangle_name(str(n).strip()) return mn
[ "def", "mangle_column_name", "(", "self", ",", "i", ",", "n", ")", ":", "from", "ambry", ".", "orm", "import", "Column", "if", "not", "n", ":", "return", "'column{}'", ".", "format", "(", "i", ")", "mn", "=", "Column", ".", "mangle_name", "(", "str",...
Override this method to change the way that column names from the source are altered to become column names in the schema. This method is called from :py:meth:`mangle_header` for each column in the header, and :py:meth:`mangle_header` is called from the RowGenerator, so it will alter the row both when the schema is being generated and when data are being inserted into the partition. Implement it in your bundle class to change the how columsn are converted from the source into database-friendly names :param i: Column number :param n: Original column name :return: A new column name
[ "Override", "this", "method", "to", "change", "the", "way", "that", "column", "names", "from", "the", "source", "are", "altered", "to", "become", "column", "names", "in", "the", "schema", ".", "This", "method", "is", "called", "from", ":", "py", ":", "me...
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L981-L1002
CivicSpleen/ambry
ambry/etl/pipeline.py
MergeHeader.init
def init(self): """Deferred initialization b/c the object con be constructed without a valid source""" from itertools import chain def maybe_int(v): try: return int(v) except ValueError: return None if not self.initialized: self.data_start_line = 1 self.data_end_line = None self.header_lines = [0] if self.source.start_line: self.data_start_line = self.source.start_line if self.source.end_line: self.data_end_line = self.source.end_line if self.source.header_lines: self.header_lines = list(map(maybe_int, self.source.header_lines)) if self.source.comment_lines: self.header_comment_lines = list(map(maybe_int, self.source.comment_lines)) max_header_line = max(chain(self.header_comment_lines, self.header_lines)) if self.data_start_line <= max_header_line: self.data_start_line = max_header_line + 1 if not self.header_comment_lines: min_header_line = min(chain(self.header_lines)) if min_header_line: self.header_comment_lines = list(range(0, min_header_line)) self.headers = [] self.header_comments = [] self.footers = [] self.initialized = True self.i = 0
python
def init(self): """Deferred initialization b/c the object con be constructed without a valid source""" from itertools import chain def maybe_int(v): try: return int(v) except ValueError: return None if not self.initialized: self.data_start_line = 1 self.data_end_line = None self.header_lines = [0] if self.source.start_line: self.data_start_line = self.source.start_line if self.source.end_line: self.data_end_line = self.source.end_line if self.source.header_lines: self.header_lines = list(map(maybe_int, self.source.header_lines)) if self.source.comment_lines: self.header_comment_lines = list(map(maybe_int, self.source.comment_lines)) max_header_line = max(chain(self.header_comment_lines, self.header_lines)) if self.data_start_line <= max_header_line: self.data_start_line = max_header_line + 1 if not self.header_comment_lines: min_header_line = min(chain(self.header_lines)) if min_header_line: self.header_comment_lines = list(range(0, min_header_line)) self.headers = [] self.header_comments = [] self.footers = [] self.initialized = True self.i = 0
[ "def", "init", "(", "self", ")", ":", "from", "itertools", "import", "chain", "def", "maybe_int", "(", "v", ")", ":", "try", ":", "return", "int", "(", "v", ")", "except", "ValueError", ":", "return", "None", "if", "not", "self", ".", "initialized", ...
Deferred initialization b/c the object con be constructed without a valid source
[ "Deferred", "initialization", "b", "/", "c", "the", "object", "con", "be", "constructed", "without", "a", "valid", "source" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L1038-L1078
CivicSpleen/ambry
ambry/etl/pipeline.py
WriteToPartition.rate
def rate(self): """Report the insertion rate in records per second""" end = self._end_time if self._end_time else time.time() return self._count / (end - self._start_time)
python
def rate(self): """Report the insertion rate in records per second""" end = self._end_time if self._end_time else time.time() return self._count / (end - self._start_time)
[ "def", "rate", "(", "self", ")", ":", "end", "=", "self", ".", "_end_time", "if", "self", ".", "_end_time", "else", "time", ".", "time", "(", ")", "return", "self", ".", "_count", "/", "(", "end", "-", "self", ".", "_start_time", ")" ]
Report the insertion rate in records per second
[ "Report", "the", "insertion", "rate", "in", "records", "per", "second" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L1980-L1985
CivicSpleen/ambry
ambry/etl/pipeline.py
Pipeline._subset
def _subset(self, subset): """Return a new pipeline with a subset of the sections""" pl = Pipeline(bundle=self.bundle) for group_name, pl_segment in iteritems(self): if group_name not in subset: continue pl[group_name] = pl_segment return pl
python
def _subset(self, subset): """Return a new pipeline with a subset of the sections""" pl = Pipeline(bundle=self.bundle) for group_name, pl_segment in iteritems(self): if group_name not in subset: continue pl[group_name] = pl_segment return pl
[ "def", "_subset", "(", "self", ",", "subset", ")", ":", "pl", "=", "Pipeline", "(", "bundle", "=", "self", ".", "bundle", ")", "for", "group_name", ",", "pl_segment", "in", "iteritems", "(", "self", ")", ":", "if", "group_name", "not", "in", "subset", ...
Return a new pipeline with a subset of the sections
[ "Return", "a", "new", "pipeline", "with", "a", "subset", "of", "the", "sections" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L2097-L2104
CivicSpleen/ambry
ambry/etl/pipeline.py
Pipeline.configure
def configure(self, pipe_config): """Configure from a dict""" # Create a context for evaluating the code for each pipeline. This removes the need # to qualify the class names with the module import ambry.etl import sys # ambry.build comes from ambry.bundle.files.PythonSourceFile#import_bundle eval_locals = dict(list(locals().items()) + list(ambry.etl.__dict__.items()) + list(sys.modules['ambry.build'].__dict__.items())) replacements = {} def eval_pipe(pipe): if isinstance(pipe, string_types): try: return eval(pipe, {}, eval_locals) except SyntaxError as e: raise SyntaxError("SyntaxError while parsing pipe '{}' from metadata: {}" .format(pipe, e)) else: return pipe def pipe_location(pipe): """Return a location prefix from a pipe, or None if there isn't one """ if not isinstance(pipe, string_types): return None elif pipe[0] in '+-$!': return pipe[0] else: return None for segment_name, pipes in list(pipe_config.items()): if segment_name == 'final': # The 'final' segment is actually a list of names of Bundle methods to call afer the pipeline # completes super(Pipeline, self).__setattr__('final', pipes) elif segment_name == 'replace': for frm, to in iteritems(pipes): self.replace(eval_pipe(frm), eval_pipe(to)) else: # Check if any of the pipes have a location command. If not, the pipe # is cleared and the set of pipes replaces the ones that are there. if not any(bool(pipe_location(pipe)) for pipe in pipes): # Nope, they are all clean self[segment_name] = [eval_pipe(pipe) for pipe in pipes] else: for i, pipe in enumerate(pipes): if pipe_location(pipe): # The pipe is prefixed with a location command location = pipe_location(pipe) pipe = pipe[1:] else: raise PipelineError( 'If any pipes in a section have a location command, they all must' ' Segment: {} pipes: {}'.format(segment_name, pipes)) ep = eval_pipe(pipe) if location == '+': # append to the segment self[segment_name].append(ep) elif location == '-': # Prepend to the segment self[segment_name].prepend(ep) elif location == '!': # Replace a pipe of the same class if isinstance(ep, type): repl_class = ep else: repl_class = ep.__class__ self.replace(repl_class, ep, segment_name)
python
def configure(self, pipe_config): """Configure from a dict""" # Create a context for evaluating the code for each pipeline. This removes the need # to qualify the class names with the module import ambry.etl import sys # ambry.build comes from ambry.bundle.files.PythonSourceFile#import_bundle eval_locals = dict(list(locals().items()) + list(ambry.etl.__dict__.items()) + list(sys.modules['ambry.build'].__dict__.items())) replacements = {} def eval_pipe(pipe): if isinstance(pipe, string_types): try: return eval(pipe, {}, eval_locals) except SyntaxError as e: raise SyntaxError("SyntaxError while parsing pipe '{}' from metadata: {}" .format(pipe, e)) else: return pipe def pipe_location(pipe): """Return a location prefix from a pipe, or None if there isn't one """ if not isinstance(pipe, string_types): return None elif pipe[0] in '+-$!': return pipe[0] else: return None for segment_name, pipes in list(pipe_config.items()): if segment_name == 'final': # The 'final' segment is actually a list of names of Bundle methods to call afer the pipeline # completes super(Pipeline, self).__setattr__('final', pipes) elif segment_name == 'replace': for frm, to in iteritems(pipes): self.replace(eval_pipe(frm), eval_pipe(to)) else: # Check if any of the pipes have a location command. If not, the pipe # is cleared and the set of pipes replaces the ones that are there. if not any(bool(pipe_location(pipe)) for pipe in pipes): # Nope, they are all clean self[segment_name] = [eval_pipe(pipe) for pipe in pipes] else: for i, pipe in enumerate(pipes): if pipe_location(pipe): # The pipe is prefixed with a location command location = pipe_location(pipe) pipe = pipe[1:] else: raise PipelineError( 'If any pipes in a section have a location command, they all must' ' Segment: {} pipes: {}'.format(segment_name, pipes)) ep = eval_pipe(pipe) if location == '+': # append to the segment self[segment_name].append(ep) elif location == '-': # Prepend to the segment self[segment_name].prepend(ep) elif location == '!': # Replace a pipe of the same class if isinstance(ep, type): repl_class = ep else: repl_class = ep.__class__ self.replace(repl_class, ep, segment_name)
[ "def", "configure", "(", "self", ",", "pipe_config", ")", ":", "# Create a context for evaluating the code for each pipeline. This removes the need", "# to qualify the class names with the module", "import", "ambry", ".", "etl", "import", "sys", "# ambry.build comes from ambry.bundle...
Configure from a dict
[ "Configure", "from", "a", "dict" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L2106-L2179
CivicSpleen/ambry
ambry/etl/pipeline.py
Pipeline.replace
def replace(self, repl_class, replacement, target_segment_name=None): """Replace a pipe segment, specified by its class, with another segment""" for segment_name, pipes in iteritems(self): if target_segment_name and segment_name != target_segment_name: raise Exception() repl_pipes = [] found = False for pipe in pipes: if isinstance(pipe, repl_class): pipe = replacement found = True repl_pipes.append(pipe) if found: found = False self[segment_name] = repl_pipes
python
def replace(self, repl_class, replacement, target_segment_name=None): """Replace a pipe segment, specified by its class, with another segment""" for segment_name, pipes in iteritems(self): if target_segment_name and segment_name != target_segment_name: raise Exception() repl_pipes = [] found = False for pipe in pipes: if isinstance(pipe, repl_class): pipe = replacement found = True repl_pipes.append(pipe) if found: found = False self[segment_name] = repl_pipes
[ "def", "replace", "(", "self", ",", "repl_class", ",", "replacement", ",", "target_segment_name", "=", "None", ")", ":", "for", "segment_name", ",", "pipes", "in", "iteritems", "(", "self", ")", ":", "if", "target_segment_name", "and", "segment_name", "!=", ...
Replace a pipe segment, specified by its class, with another segment
[ "Replace", "a", "pipe", "segment", "specified", "by", "its", "class", "with", "another", "segment" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L2181-L2200
CivicSpleen/ambry
ambry/mprlib/backends/postgresql.py
PostgreSQLBackend.install
def install(self, connection, partition, table_name=None, columns=None, materialize=False, logger=None): """ Creates FDW or materialize view for given partition. Args: connection: connection to postgresql partition (orm.Partition): materialize (boolean): if True, create read-only table. If False create virtual table. Returns: str: name of the created table. """ partition.localize() self._add_partition(connection, partition) fdw_table = partition.vid view_table = '{}_v'.format(fdw_table) if materialize: with connection.cursor() as cursor: view_exists = self._relation_exists(connection, view_table) if view_exists: logger.debug( 'Materialized view of the partition already exists.\n partition: {}, view: {}' .format(partition.name, view_table)) else: query = 'CREATE MATERIALIZED VIEW {} AS SELECT * FROM {};'\ .format(view_table, fdw_table) logger.debug( 'Creating new materialized view of the partition.' '\n partition: {}, view: {}, query: {}' .format(partition.name, view_table, query)) cursor.execute(query) cursor.execute('COMMIT;') final_table = view_table if materialize else fdw_table with connection.cursor() as cursor: view_q = "CREATE VIEW IF NOT EXISTS {} AS SELECT * FROM {} ".format(partition.vid, final_table) cursor.execute(view_q) cursor.execute('COMMIT;') return partition.vid
python
def install(self, connection, partition, table_name=None, columns=None, materialize=False, logger=None): """ Creates FDW or materialize view for given partition. Args: connection: connection to postgresql partition (orm.Partition): materialize (boolean): if True, create read-only table. If False create virtual table. Returns: str: name of the created table. """ partition.localize() self._add_partition(connection, partition) fdw_table = partition.vid view_table = '{}_v'.format(fdw_table) if materialize: with connection.cursor() as cursor: view_exists = self._relation_exists(connection, view_table) if view_exists: logger.debug( 'Materialized view of the partition already exists.\n partition: {}, view: {}' .format(partition.name, view_table)) else: query = 'CREATE MATERIALIZED VIEW {} AS SELECT * FROM {};'\ .format(view_table, fdw_table) logger.debug( 'Creating new materialized view of the partition.' '\n partition: {}, view: {}, query: {}' .format(partition.name, view_table, query)) cursor.execute(query) cursor.execute('COMMIT;') final_table = view_table if materialize else fdw_table with connection.cursor() as cursor: view_q = "CREATE VIEW IF NOT EXISTS {} AS SELECT * FROM {} ".format(partition.vid, final_table) cursor.execute(view_q) cursor.execute('COMMIT;') return partition.vid
[ "def", "install", "(", "self", ",", "connection", ",", "partition", ",", "table_name", "=", "None", ",", "columns", "=", "None", ",", "materialize", "=", "False", ",", "logger", "=", "None", ")", ":", "partition", ".", "localize", "(", ")", "self", "."...
Creates FDW or materialize view for given partition. Args: connection: connection to postgresql partition (orm.Partition): materialize (boolean): if True, create read-only table. If False create virtual table. Returns: str: name of the created table.
[ "Creates", "FDW", "or", "materialize", "view", "for", "given", "partition", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/postgresql.py#L26-L70
CivicSpleen/ambry
ambry/mprlib/backends/postgresql.py
PostgreSQLBackend.index
def index(self, connection, partition, columns): """ Create an index on the columns. Args: connection: partition (orm.Partition): columns (list of str): """ query_tmpl = 'CREATE INDEX ON {table_name} ({column});' table_name = '{}_v'.format(partition.vid) for column in columns: query = query_tmpl.format(table_name=table_name, column=column) logger.debug('Creating postgres index.\n column: {}, query: {}'.format(column, query)) with connection.cursor() as cursor: cursor.execute(query) cursor.execute('COMMIT;')
python
def index(self, connection, partition, columns): """ Create an index on the columns. Args: connection: partition (orm.Partition): columns (list of str): """ query_tmpl = 'CREATE INDEX ON {table_name} ({column});' table_name = '{}_v'.format(partition.vid) for column in columns: query = query_tmpl.format(table_name=table_name, column=column) logger.debug('Creating postgres index.\n column: {}, query: {}'.format(column, query)) with connection.cursor() as cursor: cursor.execute(query) cursor.execute('COMMIT;')
[ "def", "index", "(", "self", ",", "connection", ",", "partition", ",", "columns", ")", ":", "query_tmpl", "=", "'CREATE INDEX ON {table_name} ({column});'", "table_name", "=", "'{}_v'", ".", "format", "(", "partition", ".", "vid", ")", "for", "column", "in", "...
Create an index on the columns. Args: connection: partition (orm.Partition): columns (list of str):
[ "Create", "an", "index", "on", "the", "columns", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/postgresql.py#L86-L102
CivicSpleen/ambry
ambry/mprlib/backends/postgresql.py
PostgreSQLBackend.close
def close(self): """ Closes connection to database. """ if getattr(self, '_connection', None): logger.debug('Closing postgresql connection.') self._connection.close() self._connection = None if getattr(self, '_engine', None): self._engine.dispose()
python
def close(self): """ Closes connection to database. """ if getattr(self, '_connection', None): logger.debug('Closing postgresql connection.') self._connection.close() self._connection = None if getattr(self, '_engine', None): self._engine.dispose()
[ "def", "close", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_connection'", ",", "None", ")", ":", "logger", ".", "debug", "(", "'Closing postgresql connection.'", ")", "self", ".", "_connection", ".", "close", "(", ")", "self", ".", "_con...
Closes connection to database.
[ "Closes", "connection", "to", "database", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/postgresql.py#L104-L111
CivicSpleen/ambry
ambry/mprlib/backends/postgresql.py
PostgreSQLBackend._get_mpr_table
def _get_mpr_table(self, connection, partition): """ Returns name of the postgres table who stores mpr data. Args: connection: connection to postgres db who stores mpr data. partition (orm.Partition): Returns: str: Raises: MissingTableError: if partition table not found in the db. """ # TODO: This is the first candidate for optimization. Add field to partition # with table name and update it while table creation. # Optimized version. # # return partition.mpr_table or raise exception # Not optimized version. # # first check either partition has materialized view. logger.debug( 'Looking for materialized view of the partition.\n partition: {}'.format(partition.name)) foreign_table = partition.vid view_table = '{}_v'.format(foreign_table) view_exists = self._relation_exists(connection, view_table) if view_exists: logger.debug( 'Materialized view of the partition found.\n partition: {}, view: {}' .format(partition.name, view_table)) return view_table # now check for fdw/virtual table logger.debug( 'Looking for foreign table of the partition.\n partition: {}'.format(partition.name)) foreign_exists = self._relation_exists(connection, foreign_table) if foreign_exists: logger.debug( 'Foreign table of the partition found.\n partition: {}, foreign table: {}' .format(partition.name, foreign_table)) return foreign_table raise MissingTableError('postgres database does not have table for {} partition.' .format(partition.vid))
python
def _get_mpr_table(self, connection, partition): """ Returns name of the postgres table who stores mpr data. Args: connection: connection to postgres db who stores mpr data. partition (orm.Partition): Returns: str: Raises: MissingTableError: if partition table not found in the db. """ # TODO: This is the first candidate for optimization. Add field to partition # with table name and update it while table creation. # Optimized version. # # return partition.mpr_table or raise exception # Not optimized version. # # first check either partition has materialized view. logger.debug( 'Looking for materialized view of the partition.\n partition: {}'.format(partition.name)) foreign_table = partition.vid view_table = '{}_v'.format(foreign_table) view_exists = self._relation_exists(connection, view_table) if view_exists: logger.debug( 'Materialized view of the partition found.\n partition: {}, view: {}' .format(partition.name, view_table)) return view_table # now check for fdw/virtual table logger.debug( 'Looking for foreign table of the partition.\n partition: {}'.format(partition.name)) foreign_exists = self._relation_exists(connection, foreign_table) if foreign_exists: logger.debug( 'Foreign table of the partition found.\n partition: {}, foreign table: {}' .format(partition.name, foreign_table)) return foreign_table raise MissingTableError('postgres database does not have table for {} partition.' .format(partition.vid))
[ "def", "_get_mpr_table", "(", "self", ",", "connection", ",", "partition", ")", ":", "# TODO: This is the first candidate for optimization. Add field to partition", "# with table name and update it while table creation.", "# Optimized version.", "#", "# return partition.mpr_table or rais...
Returns name of the postgres table who stores mpr data. Args: connection: connection to postgres db who stores mpr data. partition (orm.Partition): Returns: str: Raises: MissingTableError: if partition table not found in the db.
[ "Returns", "name", "of", "the", "postgres", "table", "who", "stores", "mpr", "data", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/postgresql.py#L139-L183
CivicSpleen/ambry
ambry/mprlib/backends/postgresql.py
PostgreSQLBackend._add_partition
def _add_partition(self, connection, partition): """ Creates FDW for the partition. Args: connection: partition (orm.Partition): """ logger.debug('Creating foreign table for partition.\n partition: {}'.format(partition.name)) with connection.cursor() as cursor: postgres_med.add_partition(cursor, partition.datafile, partition.vid)
python
def _add_partition(self, connection, partition): """ Creates FDW for the partition. Args: connection: partition (orm.Partition): """ logger.debug('Creating foreign table for partition.\n partition: {}'.format(partition.name)) with connection.cursor() as cursor: postgres_med.add_partition(cursor, partition.datafile, partition.vid)
[ "def", "_add_partition", "(", "self", ",", "connection", ",", "partition", ")", ":", "logger", ".", "debug", "(", "'Creating foreign table for partition.\\n partition: {}'", ".", "format", "(", "partition", ".", "name", ")", ")", "with", "connection", ".", "cur...
Creates FDW for the partition. Args: connection: partition (orm.Partition):
[ "Creates", "FDW", "for", "the", "partition", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/postgresql.py#L185-L195
CivicSpleen/ambry
ambry/mprlib/backends/postgresql.py
PostgreSQLBackend._get_connection
def _get_connection(self): """ Returns connection to the postgres database. Returns: connection to postgres database who stores mpr data. """ if not getattr(self, '_connection', None): logger.debug( 'Creating new connection.\n dsn: {}' .format(self._dsn)) d = parse_url_to_dict(self._dsn) self._connection = psycopg2.connect( database=d['path'].strip('/'), user=d['username'], password=d['password'], port=d['port'], host=d['hostname']) # It takes some time to find the way how to get raw connection from sqlalchemy. So, # I leave the commented code. # # self._engine = create_engine(self._dsn) # self._connection = self._engine.raw_connection() # return self._connection
python
def _get_connection(self): """ Returns connection to the postgres database. Returns: connection to postgres database who stores mpr data. """ if not getattr(self, '_connection', None): logger.debug( 'Creating new connection.\n dsn: {}' .format(self._dsn)) d = parse_url_to_dict(self._dsn) self._connection = psycopg2.connect( database=d['path'].strip('/'), user=d['username'], password=d['password'], port=d['port'], host=d['hostname']) # It takes some time to find the way how to get raw connection from sqlalchemy. So, # I leave the commented code. # # self._engine = create_engine(self._dsn) # self._connection = self._engine.raw_connection() # return self._connection
[ "def", "_get_connection", "(", "self", ")", ":", "if", "not", "getattr", "(", "self", ",", "'_connection'", ",", "None", ")", ":", "logger", ".", "debug", "(", "'Creating new connection.\\n dsn: {}'", ".", "format", "(", "self", ".", "_dsn", ")", ")", "d...
Returns connection to the postgres database. Returns: connection to postgres database who stores mpr data.
[ "Returns", "connection", "to", "the", "postgres", "database", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/postgresql.py#L197-L219
CivicSpleen/ambry
ambry/mprlib/backends/postgresql.py
PostgreSQLBackend._execute
def _execute(self, connection, query, fetch=True): """ Executes given query and returns result. Args: connection: connection to postgres database who stores mpr data. query (str): sql query fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch. Returns: iterable with query result or None if fetch is False. """ # execute query with connection.cursor() as cursor: cursor.execute(query) if fetch: return cursor.fetchall() else: cursor.execute('COMMIT;')
python
def _execute(self, connection, query, fetch=True): """ Executes given query and returns result. Args: connection: connection to postgres database who stores mpr data. query (str): sql query fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch. Returns: iterable with query result or None if fetch is False. """ # execute query with connection.cursor() as cursor: cursor.execute(query) if fetch: return cursor.fetchall() else: cursor.execute('COMMIT;')
[ "def", "_execute", "(", "self", ",", "connection", ",", "query", ",", "fetch", "=", "True", ")", ":", "# execute query", "with", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "query", ")", "if", "fetch", ":"...
Executes given query and returns result. Args: connection: connection to postgres database who stores mpr data. query (str): sql query fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch. Returns: iterable with query result or None if fetch is False.
[ "Executes", "given", "query", "and", "returns", "result", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/postgresql.py#L221-L239
CivicSpleen/ambry
ambry/mprlib/backends/postgresql.py
PostgreSQLBackend._relation_exists
def _relation_exists(cls, connection, relation): """ Returns True if relation exists in the postgres db. Otherwise returns False. Args: connection: connection to postgres database who stores mpr data. relation (str): name of the table, view or materialized view. Note: relation means table, view or materialized view here. Returns: boolean: True if relation exists, False otherwise. """ schema_name, table_name = relation.split('.') exists_query = ''' SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = %s AND c.relname = %s AND (c.relkind = 'r' OR c.relkind = 'v' OR c.relkind = 'm') -- r - table, v - view, m - materialized view. ''' with connection.cursor() as cursor: cursor.execute(exists_query, [schema_name, table_name]) result = cursor.fetchall() return result == [(1,)]
python
def _relation_exists(cls, connection, relation): """ Returns True if relation exists in the postgres db. Otherwise returns False. Args: connection: connection to postgres database who stores mpr data. relation (str): name of the table, view or materialized view. Note: relation means table, view or materialized view here. Returns: boolean: True if relation exists, False otherwise. """ schema_name, table_name = relation.split('.') exists_query = ''' SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = %s AND c.relname = %s AND (c.relkind = 'r' OR c.relkind = 'v' OR c.relkind = 'm') -- r - table, v - view, m - materialized view. ''' with connection.cursor() as cursor: cursor.execute(exists_query, [schema_name, table_name]) result = cursor.fetchall() return result == [(1,)]
[ "def", "_relation_exists", "(", "cls", ",", "connection", ",", "relation", ")", ":", "schema_name", ",", "table_name", "=", "relation", ".", "split", "(", "'.'", ")", "exists_query", "=", "'''\n SELECT 1\n FROM pg_catalog.pg_class c\n JO...
Returns True if relation exists in the postgres db. Otherwise returns False. Args: connection: connection to postgres database who stores mpr data. relation (str): name of the table, view or materialized view. Note: relation means table, view or materialized view here. Returns: boolean: True if relation exists, False otherwise.
[ "Returns", "True", "if", "relation", "exists", "in", "the", "postgres", "db", ".", "Otherwise", "returns", "False", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/postgresql.py#L242-L270
trickvi/economics
economics/cpi.py
CPI.load
def load(self, country="all"): """ Load data """ u = ("https://api.worldbank.org/v2/countries/{}/indicators/CPTOTSAXN" "?format=json&per_page=10000").format(country) r = requests.get(u) j = r.json() cpi_data = j[1] # Loop through the rows of the datapackage with the help of data for row in cpi_data: # Get the code and the name and transform to uppercase # so that it'll match no matter the case iso_3 = row["countryiso3code"].upper() iso_2 = row["country"]["id"].upper() name = row["country"]['value'].upper() # Get the date (which is in the field Year) and the CPI value date = row['date'] cpi = row['value'] for key in [iso_3, iso_2, name]: existing = self.data.get(key, {}) existing[str(date)] = cpi if key: self.data[key] = existing
python
def load(self, country="all"): """ Load data """ u = ("https://api.worldbank.org/v2/countries/{}/indicators/CPTOTSAXN" "?format=json&per_page=10000").format(country) r = requests.get(u) j = r.json() cpi_data = j[1] # Loop through the rows of the datapackage with the help of data for row in cpi_data: # Get the code and the name and transform to uppercase # so that it'll match no matter the case iso_3 = row["countryiso3code"].upper() iso_2 = row["country"]["id"].upper() name = row["country"]['value'].upper() # Get the date (which is in the field Year) and the CPI value date = row['date'] cpi = row['value'] for key in [iso_3, iso_2, name]: existing = self.data.get(key, {}) existing[str(date)] = cpi if key: self.data[key] = existing
[ "def", "load", "(", "self", ",", "country", "=", "\"all\"", ")", ":", "u", "=", "(", "\"https://api.worldbank.org/v2/countries/{}/indicators/CPTOTSAXN\"", "\"?format=json&per_page=10000\"", ")", ".", "format", "(", "country", ")", "r", "=", "requests", ".", "get", ...
Load data
[ "Load", "data" ]
train
https://github.com/trickvi/economics/blob/18da5ce7169472ca1ba6022272a389b933f76edd/economics/cpi.py#L43-L67
trickvi/economics
economics/cpi.py
CPI.get
def get(self, date=datetime.date.today(), country=None): """ Get the CPI value for a specific time. Defaults to today. This uses the closest method internally but sets limit to one day. """ if not country: country = self.country if country == "all": raise ValueError("You need to specify a country") if not isinstance(date, str) and not isinstance(date, int): date = date.year cpi = self.data.get(country.upper(), {}).get(str(date)) if not cpi: raise ValueError("Missing CPI data for {} for {}".format( country, date)) return CPIResult(date=date, value=cpi)
python
def get(self, date=datetime.date.today(), country=None): """ Get the CPI value for a specific time. Defaults to today. This uses the closest method internally but sets limit to one day. """ if not country: country = self.country if country == "all": raise ValueError("You need to specify a country") if not isinstance(date, str) and not isinstance(date, int): date = date.year cpi = self.data.get(country.upper(), {}).get(str(date)) if not cpi: raise ValueError("Missing CPI data for {} for {}".format( country, date)) return CPIResult(date=date, value=cpi)
[ "def", "get", "(", "self", ",", "date", "=", "datetime", ".", "date", ".", "today", "(", ")", ",", "country", "=", "None", ")", ":", "if", "not", "country", ":", "country", "=", "self", ".", "country", "if", "country", "==", "\"all\"", ":", "raise"...
Get the CPI value for a specific time. Defaults to today. This uses the closest method internally but sets limit to one day.
[ "Get", "the", "CPI", "value", "for", "a", "specific", "time", ".", "Defaults", "to", "today", ".", "This", "uses", "the", "closest", "method", "internally", "but", "sets", "limit", "to", "one", "day", "." ]
train
https://github.com/trickvi/economics/blob/18da5ce7169472ca1ba6022272a389b933f76edd/economics/cpi.py#L69-L86
SmartTeleMax/iktomi
iktomi/web/reverse.py
Reverse.build_subreverse
def build_subreverse(self, _name, **kwargs): ''' String-based reverse API. Returns subreverse object:: env.root.build_subreverse('user', user_id=1).profile ''' _, subreverse = self._build_url_silent(_name, **kwargs) return subreverse
python
def build_subreverse(self, _name, **kwargs): ''' String-based reverse API. Returns subreverse object:: env.root.build_subreverse('user', user_id=1).profile ''' _, subreverse = self._build_url_silent(_name, **kwargs) return subreverse
[ "def", "build_subreverse", "(", "self", ",", "_name", ",", "*", "*", "kwargs", ")", ":", "_", ",", "subreverse", "=", "self", ".", "_build_url_silent", "(", "_name", ",", "*", "*", "kwargs", ")", "return", "subreverse" ]
String-based reverse API. Returns subreverse object:: env.root.build_subreverse('user', user_id=1).profile
[ "String", "-", "based", "reverse", "API", ".", "Returns", "subreverse", "object", "::" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/reverse.py#L231-L238
SmartTeleMax/iktomi
iktomi/web/reverse.py
Reverse.build_url
def build_url(self, _name, **kwargs): ''' String-based reverse API. Returns URL object:: env.root.build_url('user.profile', user_id=1) Checks that all necessary arguments are provided and all provided arguments are used. ''' used_args, subreverse = self._build_url_silent(_name, **kwargs) if set(kwargs).difference(used_args): raise UrlBuildingError( 'Not all arguments are used during URL building: {}'\ .format(', '.join(set(kwargs).difference(used_args)))) return subreverse.as_url
python
def build_url(self, _name, **kwargs): ''' String-based reverse API. Returns URL object:: env.root.build_url('user.profile', user_id=1) Checks that all necessary arguments are provided and all provided arguments are used. ''' used_args, subreverse = self._build_url_silent(_name, **kwargs) if set(kwargs).difference(used_args): raise UrlBuildingError( 'Not all arguments are used during URL building: {}'\ .format(', '.join(set(kwargs).difference(used_args)))) return subreverse.as_url
[ "def", "build_url", "(", "self", ",", "_name", ",", "*", "*", "kwargs", ")", ":", "used_args", ",", "subreverse", "=", "self", ".", "_build_url_silent", "(", "_name", ",", "*", "*", "kwargs", ")", "if", "set", "(", "kwargs", ")", ".", "difference", "...
String-based reverse API. Returns URL object:: env.root.build_url('user.profile', user_id=1) Checks that all necessary arguments are provided and all provided arguments are used.
[ "String", "-", "based", "reverse", "API", ".", "Returns", "URL", "object", "::" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/reverse.py#L240-L255
SmartTeleMax/iktomi
iktomi/web/reverse.py
Reverse.as_url
def as_url(self): ''' Reverse object converted to `web.URL`. If Reverse is bound to env: * try to build relative URL, * use current domain name, port and scheme as default ''' if '' in self._scope: return self._finalize().as_url if not self._is_endpoint: raise UrlBuildingError('Not an endpoint {}'.format(repr(self))) if self._ready: path, host = self._path, self._host else: return self().as_url # XXX there is a little mess with `domain` and `host` terms if ':' in host: domain, port = host.split(':') else: domain = host port = None if self._bound_env: request = self._bound_env.request scheme_port = {'http': '80', 'https': '443'}.get(request.scheme, '80') # Domain to compare with the result of build. # If both values are equal, domain part can be hidden from result. # Take it from route_state, not from env.request, because # route_state contains domain values with aliased replaced by their # primary value primary_domain = self._bound_env._route_state.primary_domain host_split = request.host.split(':') request_domain = host_split[0] request_port = host_split[1] if len(host_split) > 1 else scheme_port port = port or request_port return URL(path, host=domain or request_domain, port=port if port != scheme_port else None, scheme=request.scheme, fragment=self._fragment, show_host=host and (domain != primary_domain \ or port != request_port)) return URL(path, host=domain, port=port, fragment=self._fragment, show_host=True)
python
def as_url(self): ''' Reverse object converted to `web.URL`. If Reverse is bound to env: * try to build relative URL, * use current domain name, port and scheme as default ''' if '' in self._scope: return self._finalize().as_url if not self._is_endpoint: raise UrlBuildingError('Not an endpoint {}'.format(repr(self))) if self._ready: path, host = self._path, self._host else: return self().as_url # XXX there is a little mess with `domain` and `host` terms if ':' in host: domain, port = host.split(':') else: domain = host port = None if self._bound_env: request = self._bound_env.request scheme_port = {'http': '80', 'https': '443'}.get(request.scheme, '80') # Domain to compare with the result of build. # If both values are equal, domain part can be hidden from result. # Take it from route_state, not from env.request, because # route_state contains domain values with aliased replaced by their # primary value primary_domain = self._bound_env._route_state.primary_domain host_split = request.host.split(':') request_domain = host_split[0] request_port = host_split[1] if len(host_split) > 1 else scheme_port port = port or request_port return URL(path, host=domain or request_domain, port=port if port != scheme_port else None, scheme=request.scheme, fragment=self._fragment, show_host=host and (domain != primary_domain \ or port != request_port)) return URL(path, host=domain, port=port, fragment=self._fragment, show_host=True)
[ "def", "as_url", "(", "self", ")", ":", "if", "''", "in", "self", ".", "_scope", ":", "return", "self", ".", "_finalize", "(", ")", ".", "as_url", "if", "not", "self", ".", "_is_endpoint", ":", "raise", "UrlBuildingError", "(", "'Not an endpoint {}'", "....
Reverse object converted to `web.URL`. If Reverse is bound to env: * try to build relative URL, * use current domain name, port and scheme as default
[ "Reverse", "object", "converted", "to", "web", ".", "URL", "." ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/reverse.py#L258-L306
SmartTeleMax/iktomi
iktomi/web/reverse.py
Reverse.bind_to_env
def bind_to_env(self, bound_env): ''' Get a copy of the reverse, bound to `env` object. Can be found in env.root attribute:: # done in iktomi.web.app.Application env.root = Reverse.from_handler(app).bind_to_env(env) ''' return self.__class__(self._scope, self._location, path=self._path, host=self._host, fragment=self._fragment, ready=self._ready, need_arguments=self._need_arguments, finalize_params=self._finalize_params, parent=self._parent, bound_env=bound_env)
python
def bind_to_env(self, bound_env): ''' Get a copy of the reverse, bound to `env` object. Can be found in env.root attribute:: # done in iktomi.web.app.Application env.root = Reverse.from_handler(app).bind_to_env(env) ''' return self.__class__(self._scope, self._location, path=self._path, host=self._host, fragment=self._fragment, ready=self._ready, need_arguments=self._need_arguments, finalize_params=self._finalize_params, parent=self._parent, bound_env=bound_env)
[ "def", "bind_to_env", "(", "self", ",", "bound_env", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "_scope", ",", "self", ".", "_location", ",", "path", "=", "self", ".", "_path", ",", "host", "=", "self", ".", "_host", ",", "fragme...
Get a copy of the reverse, bound to `env` object. Can be found in env.root attribute:: # done in iktomi.web.app.Application env.root = Reverse.from_handler(app).bind_to_env(env)
[ "Get", "a", "copy", "of", "the", "reverse", "bound", "to", "env", "object", ".", "Can", "be", "found", "in", "env", ".", "root", "attribute", "::" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/reverse.py#L322-L337
SmartTeleMax/iktomi
iktomi/web/url.py
URL.from_url
def from_url(cls, url, show_host=True): '''Parse string and get URL instance''' # url must be idna-encoded and url-quotted if six.PY2: if isinstance(url, six.text_type): url = url.encode('utf-8') parsed = urlparse(url) netloc = parsed.netloc.decode('utf-8') # XXX HACK else:# pragma: no cover if isinstance(url, six.binary_type): url = url.decode('utf-8', errors='replace') # XXX parsed = urlparse(url) netloc = parsed.netloc query = _parse_qs(parsed.query) host = netloc.split(':', 1)[0] if ':' in netloc else netloc port = netloc.split(':')[1] if ':' in netloc else '' path = unquote(parsed.path) fragment = unquote(parsed.fragment) if not fragment and not url.endswith('#'): fragment = None return cls(path, query, host, port, parsed.scheme, fragment, show_host)
python
def from_url(cls, url, show_host=True): '''Parse string and get URL instance''' # url must be idna-encoded and url-quotted if six.PY2: if isinstance(url, six.text_type): url = url.encode('utf-8') parsed = urlparse(url) netloc = parsed.netloc.decode('utf-8') # XXX HACK else:# pragma: no cover if isinstance(url, six.binary_type): url = url.decode('utf-8', errors='replace') # XXX parsed = urlparse(url) netloc = parsed.netloc query = _parse_qs(parsed.query) host = netloc.split(':', 1)[0] if ':' in netloc else netloc port = netloc.split(':')[1] if ':' in netloc else '' path = unquote(parsed.path) fragment = unquote(parsed.fragment) if not fragment and not url.endswith('#'): fragment = None return cls(path, query, host, port, parsed.scheme, fragment, show_host)
[ "def", "from_url", "(", "cls", ",", "url", ",", "show_host", "=", "True", ")", ":", "# url must be idna-encoded and url-quotted", "if", "six", ".", "PY2", ":", "if", "isinstance", "(", "url", ",", "six", ".", "text_type", ")", ":", "url", "=", "url", "."...
Parse string and get URL instance
[ "Parse", "string", "and", "get", "URL", "instance" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/url.py#L123-L148
SmartTeleMax/iktomi
iktomi/web/url.py
URL.qs_set
def qs_set(self, *args, **kwargs): '''Set values in QuerySet MultiDict''' if args and kwargs: raise TypeError('Use positional args or keyword args not both') query = self.query.copy() if args: mdict = MultiDict(args[0]) for k in mdict.keys(): if k in query: del query[k] for k, v in mdict.items(): query.add(k, v) else: for k, v in kwargs.items(): query[k] = v return self._copy(query=query)
python
def qs_set(self, *args, **kwargs): '''Set values in QuerySet MultiDict''' if args and kwargs: raise TypeError('Use positional args or keyword args not both') query = self.query.copy() if args: mdict = MultiDict(args[0]) for k in mdict.keys(): if k in query: del query[k] for k, v in mdict.items(): query.add(k, v) else: for k, v in kwargs.items(): query[k] = v return self._copy(query=query)
[ "def", "qs_set", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "kwargs", ":", "raise", "TypeError", "(", "'Use positional args or keyword args not both'", ")", "query", "=", "self", ".", "query", ".", "copy", "(", ...
Set values in QuerySet MultiDict
[ "Set", "values", "in", "QuerySet", "MultiDict" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/url.py#L164-L179
SmartTeleMax/iktomi
iktomi/web/url.py
URL.qs_add
def qs_add(self, *args, **kwargs): '''Add value to QuerySet MultiDict''' query = self.query.copy() if args: mdict = MultiDict(args[0]) for k, v in mdict.items(): query.add(k, v) for k, v in kwargs.items(): query.add(k, v) return self._copy(query=query)
python
def qs_add(self, *args, **kwargs): '''Add value to QuerySet MultiDict''' query = self.query.copy() if args: mdict = MultiDict(args[0]) for k, v in mdict.items(): query.add(k, v) for k, v in kwargs.items(): query.add(k, v) return self._copy(query=query)
[ "def", "qs_add", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "query", ".", "copy", "(", ")", "if", "args", ":", "mdict", "=", "MultiDict", "(", "args", "[", "0", "]", ")", "for", "k", ",", "v",...
Add value to QuerySet MultiDict
[ "Add", "value", "to", "QuerySet", "MultiDict" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/url.py#L181-L190
SmartTeleMax/iktomi
iktomi/web/url.py
URL.qs_delete
def qs_delete(self, *keys): '''Delete value from QuerySet MultiDict''' query = self.query.copy() for key in set(keys): try: del query[key] except KeyError: pass return self._copy(query=query)
python
def qs_delete(self, *keys): '''Delete value from QuerySet MultiDict''' query = self.query.copy() for key in set(keys): try: del query[key] except KeyError: pass return self._copy(query=query)
[ "def", "qs_delete", "(", "self", ",", "*", "keys", ")", ":", "query", "=", "self", ".", "query", ".", "copy", "(", ")", "for", "key", "in", "set", "(", "keys", ")", ":", "try", ":", "del", "query", "[", "key", "]", "except", "KeyError", ":", "p...
Delete value from QuerySet MultiDict
[ "Delete", "value", "from", "QuerySet", "MultiDict" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/url.py#L196-L204
SmartTeleMax/iktomi
iktomi/web/url.py
URL.qs_get
def qs_get(self, key, default=None): '''Get a value from QuerySet MultiDict''' return self.query.get(key, default=default)
python
def qs_get(self, key, default=None): '''Get a value from QuerySet MultiDict''' return self.query.get(key, default=default)
[ "def", "qs_get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "return", "self", ".", "query", ".", "get", "(", "key", ",", "default", "=", "default", ")" ]
Get a value from QuerySet MultiDict
[ "Get", "a", "value", "from", "QuerySet", "MultiDict" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/url.py#L206-L208
SmartTeleMax/iktomi
iktomi/web/url.py
URL.get_readable
def get_readable(self): ''' Gets human-readable representation of the url (as unicode string, IRI according RFC3987) ''' query = (u'?' + u'&'.join(u'{}={}'.format(urlquote(k), urlquote(v)) for k, v in six.iteritems(self.query)) if self.query else '') hash_part = (u'#' + self.fragment) if self.fragment is not None else u'' path, query, hash_part = uri_to_iri_parts(self.path, query, hash_part) if self.host: port = u':' + self.port if self.port else u'' return u''.join((self.scheme, '://', self.host, port, path, query, hash_part)) else: return path + query + hash_part
python
def get_readable(self): ''' Gets human-readable representation of the url (as unicode string, IRI according RFC3987) ''' query = (u'?' + u'&'.join(u'{}={}'.format(urlquote(k), urlquote(v)) for k, v in six.iteritems(self.query)) if self.query else '') hash_part = (u'#' + self.fragment) if self.fragment is not None else u'' path, query, hash_part = uri_to_iri_parts(self.path, query, hash_part) if self.host: port = u':' + self.port if self.port else u'' return u''.join((self.scheme, '://', self.host, port, path, query, hash_part)) else: return path + query + hash_part
[ "def", "get_readable", "(", "self", ")", ":", "query", "=", "(", "u'?'", "+", "u'&'", ".", "join", "(", "u'{}={}'", ".", "format", "(", "urlquote", "(", "k", ")", ",", "urlquote", "(", "v", ")", ")", "for", "k", ",", "v", "in", "six", ".", "ite...
Gets human-readable representation of the url (as unicode string, IRI according RFC3987)
[ "Gets", "human", "-", "readable", "representation", "of", "the", "url", "(", "as", "unicode", "string", "IRI", "according", "RFC3987", ")" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/url.py#L210-L226
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/builds_api.py
BuildsApi.cancel
def cancel(self, id, **kwargs): """ Cancel running build. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.cancel(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cancel_with_http_info(id, **kwargs) else: (data) = self.cancel_with_http_info(id, **kwargs) return data
python
def cancel(self, id, **kwargs): """ Cancel running build. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.cancel(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cancel_with_http_info(id, **kwargs) else: (data) = self.cancel_with_http_info(id, **kwargs) return data
[ "def", "cancel", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "cancel_with_http_info", "(", "id", ...
Cancel running build. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.cancel(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: None If the method is called asynchronously, returns the request thread.
[ "Cancel", "running", "build", ".", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", "when", ...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/builds_api.py#L42-L66
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/builds_api.py
BuildsApi.get_ssh_credentials
def get_ssh_credentials(self, id, **kwargs): """ Gets ssh credentials for a build This GET request is for authenticated users only. The path for the endpoint is not restful to be able to authenticate this GET request only. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_ssh_credentials(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: SshCredentialsSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_ssh_credentials_with_http_info(id, **kwargs) else: (data) = self.get_ssh_credentials_with_http_info(id, **kwargs) return data
python
def get_ssh_credentials(self, id, **kwargs): """ Gets ssh credentials for a build This GET request is for authenticated users only. The path for the endpoint is not restful to be able to authenticate this GET request only. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_ssh_credentials(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: SshCredentialsSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_ssh_credentials_with_http_info(id, **kwargs) else: (data) = self.get_ssh_credentials_with_http_info(id, **kwargs) return data
[ "def", "get_ssh_credentials", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_ssh_credentials_with_ht...
Gets ssh credentials for a build This GET request is for authenticated users only. The path for the endpoint is not restful to be able to authenticate this GET request only. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_ssh_credentials(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: SshCredentialsSingleton If the method is called asynchronously, returns the request thread.
[ "Gets", "ssh", "credentials", "for", "a", "build", "This", "GET", "request", "is", "for", "authenticated", "users", "only", ".", "The", "path", "for", "the", "endpoint", "is", "not", "restful", "to", "be", "able", "to", "authenticate", "this", "GET", "requ...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/builds_api.py#L377-L401
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/productreleases_api.py
ProductreleasesApi.get_all_builds_in_distributed_recordset_of_product_release
def get_all_builds_in_distributed_recordset_of_product_release(self, id, **kwargs): """ Gets all BuildRecords distributed for Product Version This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_builds_in_distributed_recordset_of_product_release(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product Release id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: BuildRecordIds If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_builds_in_distributed_recordset_of_product_release_with_http_info(id, **kwargs) else: (data) = self.get_all_builds_in_distributed_recordset_of_product_release_with_http_info(id, **kwargs) return data
python
def get_all_builds_in_distributed_recordset_of_product_release(self, id, **kwargs): """ Gets all BuildRecords distributed for Product Version This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_builds_in_distributed_recordset_of_product_release(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product Release id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: BuildRecordIds If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_builds_in_distributed_recordset_of_product_release_with_http_info(id, **kwargs) else: (data) = self.get_all_builds_in_distributed_recordset_of_product_release_with_http_info(id, **kwargs) return data
[ "def", "get_all_builds_in_distributed_recordset_of_product_release", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self"...
Gets all BuildRecords distributed for Product Version This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_builds_in_distributed_recordset_of_product_release(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product Release id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: BuildRecordIds If the method is called asynchronously, returns the request thread.
[ "Gets", "all", "BuildRecords", "distributed", "for", "Product", "Version", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "functi...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/productreleases_api.py#L260-L288
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/productreleases_api.py
ProductreleasesApi.get_all_by_product_version_id
def get_all_by_product_version_id(self, version_id, **kwargs): """ Gets all Product Releases of the Specified Product Version This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_by_product_version_id(version_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int version_id: Product Version id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ProductReleasePage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_by_product_version_id_with_http_info(version_id, **kwargs) else: (data) = self.get_all_by_product_version_id_with_http_info(version_id, **kwargs) return data
python
def get_all_by_product_version_id(self, version_id, **kwargs): """ Gets all Product Releases of the Specified Product Version This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_by_product_version_id(version_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int version_id: Product Version id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ProductReleasePage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_by_product_version_id_with_http_info(version_id, **kwargs) else: (data) = self.get_all_by_product_version_id_with_http_info(version_id, **kwargs) return data
[ "def", "get_all_by_product_version_id", "(", "self", ",", "version_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_all_b...
Gets all Product Releases of the Specified Product Version This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_by_product_version_id(version_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int version_id: Product Version id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ProductReleasePage If the method is called asynchronously, returns the request thread.
[ "Gets", "all", "Product", "Releases", "of", "the", "Specified", "Product", "Version", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callb...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/productreleases_api.py#L382-L410
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/productreleases_api.py
ProductreleasesApi.get_all_support_level
def get_all_support_level(self, **kwargs): """ Gets all Product Releases Support Level This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_support_level(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :return: SupportLevelPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_support_level_with_http_info(**kwargs) else: (data) = self.get_all_support_level_with_http_info(**kwargs) return data
python
def get_all_support_level(self, **kwargs): """ Gets all Product Releases Support Level This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_support_level(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :return: SupportLevelPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_support_level_with_http_info(**kwargs) else: (data) = self.get_all_support_level_with_http_info(**kwargs) return data
[ "def", "get_all_support_level", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_all_support_level_with_http_info", ...
Gets all Product Releases Support Level This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_support_level(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :return: SupportLevelPage If the method is called asynchronously, returns the request thread.
[ "Gets", "all", "Product", "Releases", "Support", "Level", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be"...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/productreleases_api.py#L504-L527
SmartTeleMax/iktomi
iktomi/db/sqla/declarative.py
TableArgsMeta
def TableArgsMeta(table_args): '''Declarative metaclass automatically adding (merging) __table_args__ to mapped classes. Example: Meta = TableArgsMeta({ 'mysql_engine': 'InnoDB', 'mysql_default charset': 'utf8', } Base = declarative_base(name='Base', metaclass=Meta) class MyClass(Base): … is equivalent to Base = declarative_base(name='Base') class MyClass(Base): __table_args__ = { 'mysql_engine': 'InnoDB', 'mysql_default charset': 'utf8', } … ''' class _TableArgsMeta(declarative.DeclarativeMeta): def __init__(cls, name, bases, dict_): if ( # Do not extend base class '_decl_class_registry' not in cls.__dict__ and # Missing __tablename_ or equal to None means single table # inheritance — no table for it (columns go to table of # base class) cls.__dict__.get('__tablename__') and # Abstract class — no table for it (columns go to table[s] # of subclass[es] not cls.__dict__.get('__abstract__', False)): ta = getattr(cls, '__table_args__', {}) if isinstance(ta, dict): ta = dict(table_args, **ta) cls.__table_args__ = ta else: assert isinstance(ta, tuple) if ta and isinstance(ta[-1], dict): tad = dict(table_args, **ta[-1]) ta = ta[:-1] else: tad = dict(table_args) cls.__table_args__ = ta + (tad,) super(_TableArgsMeta, cls).__init__(name, bases, dict_) return _TableArgsMeta
python
def TableArgsMeta(table_args): '''Declarative metaclass automatically adding (merging) __table_args__ to mapped classes. Example: Meta = TableArgsMeta({ 'mysql_engine': 'InnoDB', 'mysql_default charset': 'utf8', } Base = declarative_base(name='Base', metaclass=Meta) class MyClass(Base): … is equivalent to Base = declarative_base(name='Base') class MyClass(Base): __table_args__ = { 'mysql_engine': 'InnoDB', 'mysql_default charset': 'utf8', } … ''' class _TableArgsMeta(declarative.DeclarativeMeta): def __init__(cls, name, bases, dict_): if ( # Do not extend base class '_decl_class_registry' not in cls.__dict__ and # Missing __tablename_ or equal to None means single table # inheritance — no table for it (columns go to table of # base class) cls.__dict__.get('__tablename__') and # Abstract class — no table for it (columns go to table[s] # of subclass[es] not cls.__dict__.get('__abstract__', False)): ta = getattr(cls, '__table_args__', {}) if isinstance(ta, dict): ta = dict(table_args, **ta) cls.__table_args__ = ta else: assert isinstance(ta, tuple) if ta and isinstance(ta[-1], dict): tad = dict(table_args, **ta[-1]) ta = ta[:-1] else: tad = dict(table_args) cls.__table_args__ = ta + (tad,) super(_TableArgsMeta, cls).__init__(name, bases, dict_) return _TableArgsMeta
[ "def", "TableArgsMeta", "(", "table_args", ")", ":", "class", "_TableArgsMeta", "(", "declarative", ".", "DeclarativeMeta", ")", ":", "def", "__init__", "(", "cls", ",", "name", ",", "bases", ",", "dict_", ")", ":", "if", "(", "# Do not extend base class", "...
Declarative metaclass automatically adding (merging) __table_args__ to mapped classes. Example: Meta = TableArgsMeta({ 'mysql_engine': 'InnoDB', 'mysql_default charset': 'utf8', } Base = declarative_base(name='Base', metaclass=Meta) class MyClass(Base): … is equivalent to Base = declarative_base(name='Base') class MyClass(Base): __table_args__ = { 'mysql_engine': 'InnoDB', 'mysql_default charset': 'utf8', } …
[ "Declarative", "metaclass", "automatically", "adding", "(", "merging", ")", "__table_args__", "to", "mapped", "classes", ".", "Example", ":" ]
train
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/db/sqla/declarative.py#L66-L118
CivicSpleen/ambry
ambry/jupyter.py
warehouse_query
def warehouse_query(line, cell): "my cell magic" from IPython import get_ipython parts = line.split() w_var_name = parts.pop(0) w = get_ipython().ev(w_var_name) w.query(cell).close()
python
def warehouse_query(line, cell): "my cell magic" from IPython import get_ipython parts = line.split() w_var_name = parts.pop(0) w = get_ipython().ev(w_var_name) w.query(cell).close()
[ "def", "warehouse_query", "(", "line", ",", "cell", ")", ":", "from", "IPython", "import", "get_ipython", "parts", "=", "line", ".", "split", "(", ")", "w_var_name", "=", "parts", ".", "pop", "(", "0", ")", "w", "=", "get_ipython", "(", ")", ".", "ev...
my cell magic
[ "my", "cell", "magic" ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/jupyter.py#L12-L20
project-ncl/pnc-cli
pnc_cli/productreleases.py
list_product_releases
def list_product_releases(page_size=200, page_index=0, sort="", q=""): """ List all ProductReleases """ data = list_product_releases_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
python
def list_product_releases(page_size=200, page_index=0, sort="", q=""): """ List all ProductReleases """ data = list_product_releases_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
[ "def", "list_product_releases", "(", "page_size", "=", "200", ",", "page_index", "=", "0", ",", "sort", "=", "\"\"", ",", "q", "=", "\"\"", ")", ":", "data", "=", "list_product_releases_raw", "(", "page_size", ",", "page_index", ",", "sort", ",", "q", ")...
List all ProductReleases
[ "List", "all", "ProductReleases" ]
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/productreleases.py#L22-L28
project-ncl/pnc-cli
pnc_cli/productreleases.py
update_release
def update_release(id, **kwargs): """ Update an existing ProductRelease with new information """ data = update_release_raw(id, **kwargs) if data: return utils.format_json(data)
python
def update_release(id, **kwargs): """ Update an existing ProductRelease with new information """ data = update_release_raw(id, **kwargs) if data: return utils.format_json(data)
[ "def", "update_release", "(", "id", ",", "*", "*", "kwargs", ")", ":", "data", "=", "update_release_raw", "(", "id", ",", "*", "*", "kwargs", ")", "if", "data", ":", "return", "utils", ".", "format_json", "(", "data", ")" ]
Update an existing ProductRelease with new information
[ "Update", "an", "existing", "ProductRelease", "with", "new", "information" ]
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/productreleases.py#L118-L124
cosven/feeluown-core
fuocore/library.py
Library.get
def get(self, identifier): """get provider by id""" for provider in self._providers: if provider.identifier == identifier: return provider return None
python
def get(self, identifier): """get provider by id""" for provider in self._providers: if provider.identifier == identifier: return provider return None
[ "def", "get", "(", "self", ",", "identifier", ")", ":", "for", "provider", "in", "self", ".", "_providers", ":", "if", "provider", ".", "identifier", "==", "identifier", ":", "return", "provider", "return", "None" ]
get provider by id
[ "get", "provider", "by", "id" ]
train
https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/library.py#L29-L34
cosven/feeluown-core
fuocore/library.py
Library.search
def search(self, keyword, source_in=None, **kwargs): """search song/artist/album by keyword TODO: search album or artist """ for provider in self._providers: if source_in is not None: if provider.identifier not in source_in: continue try: result = provider.search(keyword=keyword) except Exception as e: logger.exception(str(e)) logger.error('Search %s in %s failed.' % (keyword, provider)) else: yield result
python
def search(self, keyword, source_in=None, **kwargs): """search song/artist/album by keyword TODO: search album or artist """ for provider in self._providers: if source_in is not None: if provider.identifier not in source_in: continue try: result = provider.search(keyword=keyword) except Exception as e: logger.exception(str(e)) logger.error('Search %s in %s failed.' % (keyword, provider)) else: yield result
[ "def", "search", "(", "self", ",", "keyword", ",", "source_in", "=", "None", ",", "*", "*", "kwargs", ")", ":", "for", "provider", "in", "self", ".", "_providers", ":", "if", "source_in", "is", "not", "None", ":", "if", "provider", ".", "identifier", ...
search song/artist/album by keyword TODO: search album or artist
[ "search", "song", "/", "artist", "/", "album", "by", "keyword" ]
train
https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/library.py#L40-L56
cosven/feeluown-core
fuocore/library.py
Library.list_song_standby
def list_song_standby(self, song, onlyone=True): """try to list all valid standby Search a song in all providers. The typical usage scenario is when a song is not available in one provider, we can try to acquire it from other providers. Standby choosing strategy: search from all providers, select two song from each provide. Those standby song should have same title and artist name. TODO: maybe we should read a strategy from user config, user knows which provider owns copyright about an artist. FIXME: this method will send several network requests, which may block the caller. :param song: song model :param exclude: exclude providers list :return: list of songs (maximum count: 2) """ def get_score(standby): score = 1 # 分数占比关系: # title + album > artist # artist > title > album if song.artists_name != standby.artists_name: score -= 0.4 if song.title != standby.title: score -= 0.3 if song.album_name != standby.album_name: score -= 0.2 return score valid_sources = [p.identifier for p in self.list() if p.identifier != song.source] q = '{} {}'.format(song.title, song.artists_name) standby_list = [] for result in self.search(q, source_in=valid_sources, limit=10): for standby in result.songs[:2]: standby_list.append(standby) standby_list = sorted( standby_list, key=lambda standby: get_score(standby), reverse=True ) valid_standby_list = [] for standby in standby_list: if standby.url: valid_standby_list.append(standby) if get_score(standby) == 1 or onlyone: break if len(valid_standby_list) >= 2: break return valid_standby_list
python
def list_song_standby(self, song, onlyone=True): """try to list all valid standby Search a song in all providers. The typical usage scenario is when a song is not available in one provider, we can try to acquire it from other providers. Standby choosing strategy: search from all providers, select two song from each provide. Those standby song should have same title and artist name. TODO: maybe we should read a strategy from user config, user knows which provider owns copyright about an artist. FIXME: this method will send several network requests, which may block the caller. :param song: song model :param exclude: exclude providers list :return: list of songs (maximum count: 2) """ def get_score(standby): score = 1 # 分数占比关系: # title + album > artist # artist > title > album if song.artists_name != standby.artists_name: score -= 0.4 if song.title != standby.title: score -= 0.3 if song.album_name != standby.album_name: score -= 0.2 return score valid_sources = [p.identifier for p in self.list() if p.identifier != song.source] q = '{} {}'.format(song.title, song.artists_name) standby_list = [] for result in self.search(q, source_in=valid_sources, limit=10): for standby in result.songs[:2]: standby_list.append(standby) standby_list = sorted( standby_list, key=lambda standby: get_score(standby), reverse=True ) valid_standby_list = [] for standby in standby_list: if standby.url: valid_standby_list.append(standby) if get_score(standby) == 1 or onlyone: break if len(valid_standby_list) >= 2: break return valid_standby_list
[ "def", "list_song_standby", "(", "self", ",", "song", ",", "onlyone", "=", "True", ")", ":", "def", "get_score", "(", "standby", ")", ":", "score", "=", "1", "# 分数占比关系:", "# title + album > artist", "# artist > title > album", "if", "song", ".", "artists_name", ...
try to list all valid standby Search a song in all providers. The typical usage scenario is when a song is not available in one provider, we can try to acquire it from other providers. Standby choosing strategy: search from all providers, select two song from each provide. Those standby song should have same title and artist name. TODO: maybe we should read a strategy from user config, user knows which provider owns copyright about an artist. FIXME: this method will send several network requests, which may block the caller. :param song: song model :param exclude: exclude providers list :return: list of songs (maximum count: 2)
[ "try", "to", "list", "all", "valid", "standby" ]
train
https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/library.py#L59-L112
CivicSpleen/ambry
ambry/util/packages.py
import_class_by_string
def import_class_by_string(name): """Return a class by importing its module from a fully qualified string.""" components = name.split('.') clazz = components.pop() mod = __import__('.'.join(components)) components += [clazz] for comp in components[1:]: mod = getattr(mod, comp) return mod
python
def import_class_by_string(name): """Return a class by importing its module from a fully qualified string.""" components = name.split('.') clazz = components.pop() mod = __import__('.'.join(components)) components += [clazz] for comp in components[1:]: mod = getattr(mod, comp) return mod
[ "def", "import_class_by_string", "(", "name", ")", ":", "components", "=", "name", ".", "split", "(", "'.'", ")", "clazz", "=", "components", ".", "pop", "(", ")", "mod", "=", "__import__", "(", "'.'", ".", "join", "(", "components", ")", ")", "compone...
Return a class by importing its module from a fully qualified string.
[ "Return", "a", "class", "by", "importing", "its", "module", "from", "a", "fully", "qualified", "string", "." ]
train
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/packages.py#L43-L53
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_all_for_build_configuration
def get_all_for_build_configuration(self, configuration_id, **kwargs): """ Gets the Build Records linked to a specific Build Configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_for_build_configuration(configuration_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int configuration_id: Build Configuration id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: BuildRecordPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_build_configuration_with_http_info(configuration_id, **kwargs) else: (data) = self.get_all_for_build_configuration_with_http_info(configuration_id, **kwargs) return data
python
def get_all_for_build_configuration(self, configuration_id, **kwargs): """ Gets the Build Records linked to a specific Build Configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_for_build_configuration(configuration_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int configuration_id: Build Configuration id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: BuildRecordPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_build_configuration_with_http_info(configuration_id, **kwargs) else: (data) = self.get_all_for_build_configuration_with_http_info(configuration_id, **kwargs) return data
[ "def", "get_all_for_build_configuration", "(", "self", ",", "configuration_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "g...
Gets the Build Records linked to a specific Build Configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_for_build_configuration(configuration_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int configuration_id: Build Configuration id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: BuildRecordPage If the method is called asynchronously, returns the request thread.
[ "Gets", "the", "Build", "Records", "linked", "to", "a", "specific", "Build", "Configuration", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a"...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L263-L291
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_all_for_project
def get_all_for_project(self, name, **kwargs): """ Gets the Build Records produced from the BuildConfiguration by name. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_for_project(name, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str name: BuildConfiguration name (required) :param int page_index: Page index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL query :return: BuildRecordPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_project_with_http_info(name, **kwargs) else: (data) = self.get_all_for_project_with_http_info(name, **kwargs) return data
python
def get_all_for_project(self, name, **kwargs): """ Gets the Build Records produced from the BuildConfiguration by name. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_for_project(name, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str name: BuildConfiguration name (required) :param int page_index: Page index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL query :return: BuildRecordPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_project_with_http_info(name, **kwargs) else: (data) = self.get_all_for_project_with_http_info(name, **kwargs) return data
[ "def", "get_all_for_project", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_all_for_project_with_...
Gets the Build Records produced from the BuildConfiguration by name. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_for_project(name, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str name: BuildConfiguration name (required) :param int page_index: Page index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL query :return: BuildRecordPage If the method is called asynchronously, returns the request thread.
[ "Gets", "the", "Build", "Records", "produced", "from", "the", "BuildConfiguration", "by", "name", ".", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "def...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L385-L413
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_all_for_project_0
def get_all_for_project_0(self, project_id, **kwargs): """ Gets the Build Records linked to a specific Project This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_for_project_0(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int project_id: Project id (required) :param int page_index: Page index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL query :return: BuildRecordPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_project_0_with_http_info(project_id, **kwargs) else: (data) = self.get_all_for_project_0_with_http_info(project_id, **kwargs) return data
python
def get_all_for_project_0(self, project_id, **kwargs): """ Gets the Build Records linked to a specific Project This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_for_project_0(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int project_id: Project id (required) :param int page_index: Page index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL query :return: BuildRecordPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_project_0_with_http_info(project_id, **kwargs) else: (data) = self.get_all_for_project_0_with_http_info(project_id, **kwargs) return data
[ "def", "get_all_for_project_0", "(", "self", ",", "project_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_all_for_proje...
Gets the Build Records linked to a specific Project This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_all_for_project_0(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int project_id: Project id (required) :param int page_index: Page index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL query :return: BuildRecordPage If the method is called asynchronously, returns the request thread.
[ "Gets", "the", "Build", "Records", "linked", "to", "a", "specific", "Project", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", ...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L507-L535
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_attributes
def get_attributes(self, id, **kwargs): """ Get Build Record attributes. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_attributes(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: AttributeSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_attributes_with_http_info(id, **kwargs) else: (data) = self.get_attributes_with_http_info(id, **kwargs) return data
python
def get_attributes(self, id, **kwargs): """ Get Build Record attributes. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_attributes(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: AttributeSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_attributes_with_http_info(id, **kwargs) else: (data) = self.get_attributes_with_http_info(id, **kwargs) return data
[ "def", "get_attributes", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_attributes_with_http_info", ...
Get Build Record attributes. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_attributes(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: AttributeSingleton If the method is called asynchronously, returns the request thread.
[ "Get", "Build", "Record", "attributes", ".", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", ...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L629-L653
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_build_configuration_audited
def get_build_configuration_audited(self, id, **kwargs): """ Gets the audited build configuration for specific build record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_build_configuration_audited(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: BuildConfigurationAuditedSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_build_configuration_audited_with_http_info(id, **kwargs) else: (data) = self.get_build_configuration_audited_with_http_info(id, **kwargs) return data
python
def get_build_configuration_audited(self, id, **kwargs): """ Gets the audited build configuration for specific build record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_build_configuration_audited(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: BuildConfigurationAuditedSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_build_configuration_audited_with_http_info(id, **kwargs) else: (data) = self.get_build_configuration_audited_with_http_info(id, **kwargs) return data
[ "def", "get_build_configuration_audited", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_build_confi...
Gets the audited build configuration for specific build record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_build_configuration_audited(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: BuildConfigurationAuditedSingleton If the method is called asynchronously, returns the request thread.
[ "Gets", "the", "audited", "build", "configuration", "for", "specific", "build", "record", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "c...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L735-L759
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_built_artifacts
def get_built_artifacts(self, id, **kwargs): """ Gets artifacts built for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_built_artifacts(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ArtifactPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_built_artifacts_with_http_info(id, **kwargs) else: (data) = self.get_built_artifacts_with_http_info(id, **kwargs) return data
python
def get_built_artifacts(self, id, **kwargs): """ Gets artifacts built for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_built_artifacts(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ArtifactPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_built_artifacts_with_http_info(id, **kwargs) else: (data) = self.get_built_artifacts_with_http_info(id, **kwargs) return data
[ "def", "get_built_artifacts", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_built_artifacts_with_ht...
Gets artifacts built for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_built_artifacts(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ArtifactPage If the method is called asynchronously, returns the request thread.
[ "Gets", "artifacts", "built", "for", "specific", "Build", "Record", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", ...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L841-L869
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_completed_or_runnning
def get_completed_or_runnning(self, id, **kwargs): """ Deprecated, use /builds/{id} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_completed_or_runnning(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: BuildRecordSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_completed_or_runnning_with_http_info(id, **kwargs) else: (data) = self.get_completed_or_runnning_with_http_info(id, **kwargs) return data
python
def get_completed_or_runnning(self, id, **kwargs): """ Deprecated, use /builds/{id} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_completed_or_runnning(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: BuildRecordSingleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_completed_or_runnning_with_http_info(id, **kwargs) else: (data) = self.get_completed_or_runnning_with_http_info(id, **kwargs) return data
[ "def", "get_completed_or_runnning", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_completed_or_runn...
Deprecated, use /builds/{id} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_completed_or_runnning(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: BuildRecordSingleton If the method is called asynchronously, returns the request thread.
[ "Deprecated", "use", "/", "builds", "/", "{", "id", "}", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L963-L987
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_dependency_artifacts
def get_dependency_artifacts(self, id, **kwargs): """ Gets dependency artifacts for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_dependency_artifacts(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ArtifactPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_dependency_artifacts_with_http_info(id, **kwargs) else: (data) = self.get_dependency_artifacts_with_http_info(id, **kwargs) return data
python
def get_dependency_artifacts(self, id, **kwargs): """ Gets dependency artifacts for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_dependency_artifacts(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ArtifactPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_dependency_artifacts_with_http_info(id, **kwargs) else: (data) = self.get_dependency_artifacts_with_http_info(id, **kwargs) return data
[ "def", "get_dependency_artifacts", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_dependency_artifac...
Gets dependency artifacts for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_dependency_artifacts(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ArtifactPage If the method is called asynchronously, returns the request thread.
[ "Gets", "dependency", "artifacts", "for", "specific", "Build", "Record", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L1069-L1097
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_dependency_graph
def get_dependency_graph(self, id, **kwargs): """ Gets dependency graph for a Build Record (running or completed). This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_dependency_graph(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Build id. (required) :return: Singleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_dependency_graph_with_http_info(id, **kwargs) else: (data) = self.get_dependency_graph_with_http_info(id, **kwargs) return data
python
def get_dependency_graph(self, id, **kwargs): """ Gets dependency graph for a Build Record (running or completed). This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_dependency_graph(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Build id. (required) :return: Singleton If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_dependency_graph_with_http_info(id, **kwargs) else: (data) = self.get_dependency_graph_with_http_info(id, **kwargs) return data
[ "def", "get_dependency_graph", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_dependency_graph_with_...
Gets dependency graph for a Build Record (running or completed). This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_dependency_graph(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Build id. (required) :return: Singleton If the method is called asynchronously, returns the request thread.
[ "Gets", "dependency", "graph", "for", "a", "Build", "Record", "(", "running", "or", "completed", ")", ".", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please"...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L1191-L1215
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_logs
def get_logs(self, id, **kwargs): """ Gets logs for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_logs(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_logs_with_http_info(id, **kwargs) else: (data) = self.get_logs_with_http_info(id, **kwargs) return data
python
def get_logs(self, id, **kwargs): """ Gets logs for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_logs(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_logs_with_http_info(id, **kwargs) else: (data) = self.get_logs_with_http_info(id, **kwargs) return data
[ "def", "get_logs", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_logs_with_http_info", "(", "id...
Gets logs for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_logs(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: str If the method is called asynchronously, returns the request thread.
[ "Gets", "logs", "for", "specific", "Build", "Record", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", ...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L1297-L1321
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.get_repour_logs
def get_repour_logs(self, id, **kwargs): """ Gets repour logs for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_repour_logs(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_repour_logs_with_http_info(id, **kwargs) else: (data) = self.get_repour_logs_with_http_info(id, **kwargs) return data
python
def get_repour_logs(self, id, **kwargs): """ Gets repour logs for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_repour_logs(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_repour_logs_with_http_info(id, **kwargs) else: (data) = self.get_repour_logs_with_http_info(id, **kwargs) return data
[ "def", "get_repour_logs", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_repour_logs_with_http_info"...
Gets repour logs for specific Build Record This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_repour_logs(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :return: str If the method is called asynchronously, returns the request thread.
[ "Gets", "repour", "logs", "for", "specific", "Build", "Record", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to"...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L1403-L1427
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.put_attribute
def put_attribute(self, id, key, value, **kwargs): """ Add attribute to the BuildRecord. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.put_attribute(id, key, value, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param str key: Attribute key (required) :param str value: Attribute value (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.put_attribute_with_http_info(id, key, value, **kwargs) else: (data) = self.put_attribute_with_http_info(id, key, value, **kwargs) return data
python
def put_attribute(self, id, key, value, **kwargs): """ Add attribute to the BuildRecord. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.put_attribute(id, key, value, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param str key: Attribute key (required) :param str value: Attribute value (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.put_attribute_with_http_info(id, key, value, **kwargs) else: (data) = self.put_attribute_with_http_info(id, key, value, **kwargs) return data
[ "def", "put_attribute", "(", "self", ",", "id", ",", "key", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", ...
Add attribute to the BuildRecord. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.put_attribute(id, key, value, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param str key: Attribute key (required) :param str value: Attribute value (required) :return: None If the method is called asynchronously, returns the request thread.
[ "Add", "attribute", "to", "the", "BuildRecord", ".", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L1615-L1641
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.query_by_attribute
def query_by_attribute(self, key, value, **kwargs): """ Get Build Records by attribute. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.query_by_attribute(key, value, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str key: Attribute key (required) :param str value: Attribute value (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: BuildRecordPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.query_by_attribute_with_http_info(key, value, **kwargs) else: (data) = self.query_by_attribute_with_http_info(key, value, **kwargs) return data
python
def query_by_attribute(self, key, value, **kwargs): """ Get Build Records by attribute. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.query_by_attribute(key, value, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str key: Attribute key (required) :param str value: Attribute value (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: BuildRecordPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.query_by_attribute_with_http_info(key, value, **kwargs) else: (data) = self.query_by_attribute_with_http_info(key, value, **kwargs) return data
[ "def", "query_by_attribute", "(", "self", ",", "key", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "query_by_...
Get Build Records by attribute. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.query_by_attribute(key, value, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str key: Attribute key (required) :param str value: Attribute value (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: BuildRecordPage If the method is called asynchronously, returns the request thread.
[ "Get", "Build", "Records", "by", "attribute", ".", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "in...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L1735-L1764
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildrecords_api.py
BuildrecordsApi.remove_attribute
def remove_attribute(self, id, key, **kwargs): """ Remove attribute from BuildRecord. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.remove_attribute(id, key, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param str key: Attribute key (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.remove_attribute_with_http_info(id, key, **kwargs) else: (data) = self.remove_attribute_with_http_info(id, key, **kwargs) return data
python
def remove_attribute(self, id, key, **kwargs): """ Remove attribute from BuildRecord. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.remove_attribute(id, key, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param str key: Attribute key (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.remove_attribute_with_http_info(id, key, **kwargs) else: (data) = self.remove_attribute_with_http_info(id, key, **kwargs) return data
[ "def", "remove_attribute", "(", "self", ",", "id", ",", "key", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "remove_attribu...
Remove attribute from BuildRecord. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.remove_attribute(id, key, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: BuildRecord id (required) :param str key: Attribute key (required) :return: None If the method is called asynchronously, returns the request thread.
[ "Remove", "attribute", "from", "BuildRecord", ".", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invo...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildrecords_api.py#L1864-L1889
andreafioraldi/angrdbg
angrdbg/memory_7.py
SimSymbolicDbgMemory.get_unconstrained_bytes
def get_unconstrained_bytes(self, name, bits, source=None, key=None, inspect=True, events=True, **kwargs): """ Get some consecutive unconstrained bytes. :param name: Name of the unconstrained variable :param bits: Size of the unconstrained variable :param source: Where those bytes are read from. Currently it is only used in under-constrained symbolic execution so that we can track the allocation depth. :return: The generated variable """ if (self.category == 'mem' and options.CGC_ZERO_FILL_UNCONSTRAINED_MEMORY in self.state.options): # CGC binaries zero-fill the memory for any allocated region # Reference: (https://github.com/CyberGrandChallenge/libcgc/blob/master/allocate.md) return self.state.solver.BVV(0, bits) elif options.SPECIAL_MEMORY_FILL in self.state.options and self.state._special_memory_filler is not None: return self.state._special_memory_filler(name, bits, self.state) else: if options.UNDER_CONSTRAINED_SYMEXEC in self.state.options: if source is not None and type(source) is int: alloc_depth = self.state.uc_manager.get_alloc_depth(source) kwargs['uc_alloc_depth'] = 0 if alloc_depth is None else alloc_depth + 1 r = self.state.solver.Unconstrained(name, bits, key=key, inspect=inspect, events=events, **kwargs) return r
python
def get_unconstrained_bytes(self, name, bits, source=None, key=None, inspect=True, events=True, **kwargs): """ Get some consecutive unconstrained bytes. :param name: Name of the unconstrained variable :param bits: Size of the unconstrained variable :param source: Where those bytes are read from. Currently it is only used in under-constrained symbolic execution so that we can track the allocation depth. :return: The generated variable """ if (self.category == 'mem' and options.CGC_ZERO_FILL_UNCONSTRAINED_MEMORY in self.state.options): # CGC binaries zero-fill the memory for any allocated region # Reference: (https://github.com/CyberGrandChallenge/libcgc/blob/master/allocate.md) return self.state.solver.BVV(0, bits) elif options.SPECIAL_MEMORY_FILL in self.state.options and self.state._special_memory_filler is not None: return self.state._special_memory_filler(name, bits, self.state) else: if options.UNDER_CONSTRAINED_SYMEXEC in self.state.options: if source is not None and type(source) is int: alloc_depth = self.state.uc_manager.get_alloc_depth(source) kwargs['uc_alloc_depth'] = 0 if alloc_depth is None else alloc_depth + 1 r = self.state.solver.Unconstrained(name, bits, key=key, inspect=inspect, events=events, **kwargs) return r
[ "def", "get_unconstrained_bytes", "(", "self", ",", "name", ",", "bits", ",", "source", "=", "None", ",", "key", "=", "None", ",", "inspect", "=", "True", ",", "events", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "(", "self", ".", "categ...
Get some consecutive unconstrained bytes. :param name: Name of the unconstrained variable :param bits: Size of the unconstrained variable :param source: Where those bytes are read from. Currently it is only used in under-constrained symbolic execution so that we can track the allocation depth. :return: The generated variable
[ "Get", "some", "consecutive", "unconstrained", "bytes", "." ]
train
https://github.com/andreafioraldi/angrdbg/blob/939b20fb9b341aee695d2db12142b1eddc5b555a/angrdbg/memory_7.py#L1019-L1043
project-ncl/pnc-cli
pnc_cli/swagger_client/models/build_configuration_rest.py
BuildConfigurationRest.build_type
def build_type(self, build_type): """ Sets the build_type of this BuildConfigurationRest. :param build_type: The build_type of this BuildConfigurationRest. :type: str """ allowed_values = ["MVN", "NPM"] if build_type not in allowed_values: raise ValueError( "Invalid value for `build_type` ({0}), must be one of {1}" .format(build_type, allowed_values) ) self._build_type = build_type
python
def build_type(self, build_type): """ Sets the build_type of this BuildConfigurationRest. :param build_type: The build_type of this BuildConfigurationRest. :type: str """ allowed_values = ["MVN", "NPM"] if build_type not in allowed_values: raise ValueError( "Invalid value for `build_type` ({0}), must be one of {1}" .format(build_type, allowed_values) ) self._build_type = build_type
[ "def", "build_type", "(", "self", ",", "build_type", ")", ":", "allowed_values", "=", "[", "\"MVN\"", ",", "\"NPM\"", "]", "if", "build_type", "not", "in", "allowed_values", ":", "raise", "ValueError", "(", "\"Invalid value for `build_type` ({0}), must be one of {1}\"...
Sets the build_type of this BuildConfigurationRest. :param build_type: The build_type of this BuildConfigurationRest. :type: str
[ "Sets", "the", "build_type", "of", "this", "BuildConfigurationRest", "." ]
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/models/build_configuration_rest.py#L347-L361
parkouss/rcontrol
rcontrol/ssh.py
ssh_client
def ssh_client(host, username=None, password=None, **kwargs): """ Create a new :class:`paramiko.SSHClient`, connect it and return the instance. This is a simple wrapper around the connect method that add some good defaults when using username/password to connect. """ client = paramiko.SSHClient() # save hostname and username on the instance - this is a ugly hack # but I don't see any other way to do that for now. Note that # this is only used for SshSession.__str__. client.hostname = host client.username = username if username is not None: kwargs['username'] = username if password is not None: kwargs['password'] = password if username is not None and password is not None: client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) kwargs.setdefault('look_for_keys', False) client.connect(host, **kwargs) return client
python
def ssh_client(host, username=None, password=None, **kwargs): """ Create a new :class:`paramiko.SSHClient`, connect it and return the instance. This is a simple wrapper around the connect method that add some good defaults when using username/password to connect. """ client = paramiko.SSHClient() # save hostname and username on the instance - this is a ugly hack # but I don't see any other way to do that for now. Note that # this is only used for SshSession.__str__. client.hostname = host client.username = username if username is not None: kwargs['username'] = username if password is not None: kwargs['password'] = password if username is not None and password is not None: client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) kwargs.setdefault('look_for_keys', False) client.connect(host, **kwargs) return client
[ "def", "ssh_client", "(", "host", ",", "username", "=", "None", ",", "password", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "paramiko", ".", "SSHClient", "(", ")", "# save hostname and username on the instance - this is a ugly hack", "# but I d...
Create a new :class:`paramiko.SSHClient`, connect it and return the instance. This is a simple wrapper around the connect method that add some good defaults when using username/password to connect.
[ "Create", "a", "new", ":", "class", ":", "paramiko", ".", "SSHClient", "connect", "it", "and", "return", "the", "instance", "." ]
train
https://github.com/parkouss/rcontrol/blob/1764c1492f00d3f1a57dabe09983ed369aade828/rcontrol/ssh.py#L73-L95
twisted/epsilon
epsilon/hotfixes/trial_assertwarns.py
failUnlessWarns
def failUnlessWarns(self, category, message, filename, f, *args, **kwargs): """ Fail if the given function doesn't generate the specified warning when called. It calls the function, checks the warning, and forwards the result of the function if everything is fine. @param category: the category of the warning to check. @param message: the output message of the warning to check. @param filename: the filename where the warning should come from. @param f: the function which is supposed to generate the warning. @type f: any callable. @param args: the arguments to C{f}. @param kwargs: the keywords arguments to C{f}. @return: the result of the original function C{f}. """ warningsShown = [] def warnExplicit(*args): warningsShown.append(args) origExplicit = warnings.warn_explicit try: warnings.warn_explicit = warnExplicit result = f(*args, **kwargs) finally: warnings.warn_explicit = origExplicit if not warningsShown: self.fail("No warnings emitted") first = warningsShown[0] for other in warningsShown[1:]: if other[:2] != first[:2]: self.fail("Can't handle different warnings") gotMessage, gotCategory, gotFilename, lineno = first[:4] self.assertEqual(gotMessage, message) self.assertIdentical(gotCategory, category) # Use starts with because of .pyc/.pyo issues. self.failUnless( filename.startswith(gotFilename), 'Warning in %r, expected %r' % (gotFilename, filename)) # It would be nice to be able to check the line number as well, but # different configurations actually end up reporting different line # numbers (generally the variation is only 1 line, but that's enough # to fail the test erroneously...). # self.assertEqual(lineno, xxx) return result
python
def failUnlessWarns(self, category, message, filename, f, *args, **kwargs): """ Fail if the given function doesn't generate the specified warning when called. It calls the function, checks the warning, and forwards the result of the function if everything is fine. @param category: the category of the warning to check. @param message: the output message of the warning to check. @param filename: the filename where the warning should come from. @param f: the function which is supposed to generate the warning. @type f: any callable. @param args: the arguments to C{f}. @param kwargs: the keywords arguments to C{f}. @return: the result of the original function C{f}. """ warningsShown = [] def warnExplicit(*args): warningsShown.append(args) origExplicit = warnings.warn_explicit try: warnings.warn_explicit = warnExplicit result = f(*args, **kwargs) finally: warnings.warn_explicit = origExplicit if not warningsShown: self.fail("No warnings emitted") first = warningsShown[0] for other in warningsShown[1:]: if other[:2] != first[:2]: self.fail("Can't handle different warnings") gotMessage, gotCategory, gotFilename, lineno = first[:4] self.assertEqual(gotMessage, message) self.assertIdentical(gotCategory, category) # Use starts with because of .pyc/.pyo issues. self.failUnless( filename.startswith(gotFilename), 'Warning in %r, expected %r' % (gotFilename, filename)) # It would be nice to be able to check the line number as well, but # different configurations actually end up reporting different line # numbers (generally the variation is only 1 line, but that's enough # to fail the test erroneously...). # self.assertEqual(lineno, xxx) return result
[ "def", "failUnlessWarns", "(", "self", ",", "category", ",", "message", ",", "filename", ",", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warningsShown", "=", "[", "]", "def", "warnExplicit", "(", "*", "args", ")", ":", "warningsShown", ...
Fail if the given function doesn't generate the specified warning when called. It calls the function, checks the warning, and forwards the result of the function if everything is fine. @param category: the category of the warning to check. @param message: the output message of the warning to check. @param filename: the filename where the warning should come from. @param f: the function which is supposed to generate the warning. @type f: any callable. @param args: the arguments to C{f}. @param kwargs: the keywords arguments to C{f}. @return: the result of the original function C{f}.
[ "Fail", "if", "the", "given", "function", "doesn", "t", "generate", "the", "specified", "warning", "when", "called", ".", "It", "calls", "the", "function", "checks", "the", "warning", "and", "forwards", "the", "result", "of", "the", "function", "if", "everyt...
train
https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/hotfixes/trial_assertwarns.py#L8-L57
spotify/ulogger
ulogger/ulogger.py
_setup_default_handler
def _setup_default_handler(progname, fmt=None, datefmt=None, **_): """Create a Stream handler (default handler). Args: progname (str): Name of program. fmt (:obj:`str`, optional): Desired log format if different than the default; uses the same formatting string options supported in the stdlib's `logging` module. datefmt (:obj:`str`, optional): Desired date format if different than the default; uses the same formatting string options supported in the stdlib's `logging` module. Returns: (obj): Instance of `logging.StreamHandler` """ handler = logging.StreamHandler() if not fmt: # ex: 2017-08-26T14:47:44.968+00:00 <progname> (<PID>) INFO: <msg> fmt_prefix = '%(asctime)s.%(msecs)03dZ ' fmt_suffix = ' (%(process)d) %(levelname)s: ' + '%(message)s' fmt = fmt_prefix + progname + fmt_suffix if not datefmt: datefmt = '%Y-%m-%dT%H:%M:%S' formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) handler.setFormatter(formatter) return handler
python
def _setup_default_handler(progname, fmt=None, datefmt=None, **_): """Create a Stream handler (default handler). Args: progname (str): Name of program. fmt (:obj:`str`, optional): Desired log format if different than the default; uses the same formatting string options supported in the stdlib's `logging` module. datefmt (:obj:`str`, optional): Desired date format if different than the default; uses the same formatting string options supported in the stdlib's `logging` module. Returns: (obj): Instance of `logging.StreamHandler` """ handler = logging.StreamHandler() if not fmt: # ex: 2017-08-26T14:47:44.968+00:00 <progname> (<PID>) INFO: <msg> fmt_prefix = '%(asctime)s.%(msecs)03dZ ' fmt_suffix = ' (%(process)d) %(levelname)s: ' + '%(message)s' fmt = fmt_prefix + progname + fmt_suffix if not datefmt: datefmt = '%Y-%m-%dT%H:%M:%S' formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) handler.setFormatter(formatter) return handler
[ "def", "_setup_default_handler", "(", "progname", ",", "fmt", "=", "None", ",", "datefmt", "=", "None", ",", "*", "*", "_", ")", ":", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "if", "not", "fmt", ":", "# ex: 2017-08-26T14:47:44.968+00:00 <pr...
Create a Stream handler (default handler). Args: progname (str): Name of program. fmt (:obj:`str`, optional): Desired log format if different than the default; uses the same formatting string options supported in the stdlib's `logging` module. datefmt (:obj:`str`, optional): Desired date format if different than the default; uses the same formatting string options supported in the stdlib's `logging` module. Returns: (obj): Instance of `logging.StreamHandler`
[ "Create", "a", "Stream", "handler", "(", "default", "handler", ")", "." ]
train
https://github.com/spotify/ulogger/blob/c59ced69e55b400e9c7a3688145fe3e8cb89db13/ulogger/ulogger.py#L26-L53
spotify/ulogger
ulogger/ulogger.py
setup_logging
def setup_logging(progname, level, handlers, **kwargs): """Setup logging to stdout (stream), syslog, or stackdriver. Attaches handler(s) and sets log level to the root logger. Example usage: import logging from ulogger import setup_logging setup_logging('my_awesome_program', 'INFO', ['stream']) logging.info('ohai') Args: progname (str): Name of program. level (str): Threshold for when to log. handlers (list): Desired handlers, default 'stream', supported: 'syslog', 'stackdriver', 'stream'. **kwargs (optional): Keyword arguments to pass to handlers. See handler documentation for more information on available kwargs. """ for h in handlers: if h == 'stream': handler = _setup_default_handler(progname, **kwargs) else: handler_module_path = 'ulogger.{}'.format(h) try: handler_module = import_module( handler_module_path, package='ulogger') except ImportError: msg = 'Unsupported log handler: "{}".'.format(h) raise exceptions.ULoggerError(msg) try: get_handler = getattr(handler_module, 'get_handler') except AttributeError: msg = '"get_handler" function not implemented for "{}".' raise exceptions.ULoggerError(msg.format(h)) handler = get_handler(progname, **kwargs) logging.getLogger('').addHandler(handler) level = logging.getLevelName(level) logging.getLogger('').setLevel(level)
python
def setup_logging(progname, level, handlers, **kwargs): """Setup logging to stdout (stream), syslog, or stackdriver. Attaches handler(s) and sets log level to the root logger. Example usage: import logging from ulogger import setup_logging setup_logging('my_awesome_program', 'INFO', ['stream']) logging.info('ohai') Args: progname (str): Name of program. level (str): Threshold for when to log. handlers (list): Desired handlers, default 'stream', supported: 'syslog', 'stackdriver', 'stream'. **kwargs (optional): Keyword arguments to pass to handlers. See handler documentation for more information on available kwargs. """ for h in handlers: if h == 'stream': handler = _setup_default_handler(progname, **kwargs) else: handler_module_path = 'ulogger.{}'.format(h) try: handler_module = import_module( handler_module_path, package='ulogger') except ImportError: msg = 'Unsupported log handler: "{}".'.format(h) raise exceptions.ULoggerError(msg) try: get_handler = getattr(handler_module, 'get_handler') except AttributeError: msg = '"get_handler" function not implemented for "{}".' raise exceptions.ULoggerError(msg.format(h)) handler = get_handler(progname, **kwargs) logging.getLogger('').addHandler(handler) level = logging.getLevelName(level) logging.getLogger('').setLevel(level)
[ "def", "setup_logging", "(", "progname", ",", "level", ",", "handlers", ",", "*", "*", "kwargs", ")", ":", "for", "h", "in", "handlers", ":", "if", "h", "==", "'stream'", ":", "handler", "=", "_setup_default_handler", "(", "progname", ",", "*", "*", "k...
Setup logging to stdout (stream), syslog, or stackdriver. Attaches handler(s) and sets log level to the root logger. Example usage: import logging from ulogger import setup_logging setup_logging('my_awesome_program', 'INFO', ['stream']) logging.info('ohai') Args: progname (str): Name of program. level (str): Threshold for when to log. handlers (list): Desired handlers, default 'stream', supported: 'syslog', 'stackdriver', 'stream'. **kwargs (optional): Keyword arguments to pass to handlers. See handler documentation for more information on available kwargs.
[ "Setup", "logging", "to", "stdout", "(", "stream", ")", "syslog", "or", "stackdriver", "." ]
train
https://github.com/spotify/ulogger/blob/c59ced69e55b400e9c7a3688145fe3e8cb89db13/ulogger/ulogger.py#L56-L101
andreafioraldi/angrdbg
angrdbg/core.py
StateManager.sim
def sim(self, key, size=None): ''' key: memory address(int) or register name(str) size: size of object in bytes ''' project = load_project() if key in project.arch.registers: if size is None: size = project.arch.registers[key][1] size *= 8 s = claripy.BVS("angrdbg_reg_" + str(key), size) setattr(self.state.regs, key, s) self.symbolics[key] = (s, size) elif isinstance(key, int) or isinstance(key, long): if size is None: size = project.arch.bits else: size *= 8 s = claripy.BVS("angrdbg_mem_" + hex(key), size) self.state.memory.store(key, s) self.symbolics[key] = (s, size) elif isinstance(key, claripy.ast.bv.BV): key = self.state.solver.eval(key, cast_to=int) self.sim(key, size) else: raise ValueError( "key must be a register name or a memory address, not %s" % str( type(key))) return key
python
def sim(self, key, size=None): ''' key: memory address(int) or register name(str) size: size of object in bytes ''' project = load_project() if key in project.arch.registers: if size is None: size = project.arch.registers[key][1] size *= 8 s = claripy.BVS("angrdbg_reg_" + str(key), size) setattr(self.state.regs, key, s) self.symbolics[key] = (s, size) elif isinstance(key, int) or isinstance(key, long): if size is None: size = project.arch.bits else: size *= 8 s = claripy.BVS("angrdbg_mem_" + hex(key), size) self.state.memory.store(key, s) self.symbolics[key] = (s, size) elif isinstance(key, claripy.ast.bv.BV): key = self.state.solver.eval(key, cast_to=int) self.sim(key, size) else: raise ValueError( "key must be a register name or a memory address, not %s" % str( type(key))) return key
[ "def", "sim", "(", "self", ",", "key", ",", "size", "=", "None", ")", ":", "project", "=", "load_project", "(", ")", "if", "key", "in", "project", ".", "arch", ".", "registers", ":", "if", "size", "is", "None", ":", "size", "=", "project", ".", "...
key: memory address(int) or register name(str) size: size of object in bytes
[ "key", ":", "memory", "address", "(", "int", ")", "or", "register", "name", "(", "str", ")", "size", ":", "size", "of", "object", "in", "bytes" ]
train
https://github.com/andreafioraldi/angrdbg/blob/939b20fb9b341aee695d2db12142b1eddc5b555a/angrdbg/core.py#L115-L143
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/productmilestones_api.py
ProductmilestonesApi.add_distributed_artifact
def add_distributed_artifact(self, id, **kwargs): """ Adds an artifact to the list of distributed artifacts for this product milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.add_distributed_artifact(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product milestone id (required) :param ArtifactRest body: :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.add_distributed_artifact_with_http_info(id, **kwargs) else: (data) = self.add_distributed_artifact_with_http_info(id, **kwargs) return data
python
def add_distributed_artifact(self, id, **kwargs): """ Adds an artifact to the list of distributed artifacts for this product milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.add_distributed_artifact(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product milestone id (required) :param ArtifactRest body: :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.add_distributed_artifact_with_http_info(id, **kwargs) else: (data) = self.add_distributed_artifact_with_http_info(id, **kwargs) return data
[ "def", "add_distributed_artifact", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "add_distributed_artifa...
Adds an artifact to the list of distributed artifacts for this product milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.add_distributed_artifact(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product milestone id (required) :param ArtifactRest body: :return: None If the method is called asynchronously, returns the request thread.
[ "Adds", "an", "artifact", "to", "the", "list", "of", "distributed", "artifacts", "for", "this", "product", "milestone", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/productmilestones_api.py#L42-L67
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/productmilestones_api.py
ProductmilestonesApi.cancel_milestone_close
def cancel_milestone_close(self, id, **kwargs): """ Cancel Product Milestone Release process. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.cancel_milestone_close(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product Milestone id (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cancel_milestone_close_with_http_info(id, **kwargs) else: (data) = self.cancel_milestone_close_with_http_info(id, **kwargs) return data
python
def cancel_milestone_close(self, id, **kwargs): """ Cancel Product Milestone Release process. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.cancel_milestone_close(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product Milestone id (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cancel_milestone_close_with_http_info(id, **kwargs) else: (data) = self.cancel_milestone_close_with_http_info(id, **kwargs) return data
[ "def", "cancel_milestone_close", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "cancel_milestone_close_w...
Cancel Product Milestone Release process. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.cancel_milestone_close(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product Milestone id (required) :return: None If the method is called asynchronously, returns the request thread.
[ "Cancel", "Product", "Milestone", "Release", "process", ".", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/productmilestones_api.py#L152-L176
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/productmilestones_api.py
ProductmilestonesApi.close_milestone
def close_milestone(self, id, **kwargs): """ Close/Release a Product Milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.close_milestone(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product Milestone id (required) :param ProductMilestoneRest body: :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.close_milestone_with_http_info(id, **kwargs) else: (data) = self.close_milestone_with_http_info(id, **kwargs) return data
python
def close_milestone(self, id, **kwargs): """ Close/Release a Product Milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.close_milestone(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product Milestone id (required) :param ProductMilestoneRest body: :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.close_milestone_with_http_info(id, **kwargs) else: (data) = self.close_milestone_with_http_info(id, **kwargs) return data
[ "def", "close_milestone", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "close_milestone_with_http_info"...
Close/Release a Product Milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.close_milestone(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product Milestone id (required) :param ProductMilestoneRest body: :return: None If the method is called asynchronously, returns the request thread.
[ "Close", "/", "Release", "a", "Product", "Milestone", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", ...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/productmilestones_api.py#L258-L283
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/productmilestones_api.py
ProductmilestonesApi.get_distributed_artifacts
def get_distributed_artifacts(self, id, **kwargs): """ Get the artifacts distributed in this milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_distributed_artifacts(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product milestone id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ArtifactPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_distributed_artifacts_with_http_info(id, **kwargs) else: (data) = self.get_distributed_artifacts_with_http_info(id, **kwargs) return data
python
def get_distributed_artifacts(self, id, **kwargs): """ Get the artifacts distributed in this milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_distributed_artifacts(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product milestone id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ArtifactPage If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_distributed_artifacts_with_http_info(id, **kwargs) else: (data) = self.get_distributed_artifacts_with_http_info(id, **kwargs) return data
[ "def", "get_distributed_artifacts", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_distributed_artif...
Get the artifacts distributed in this milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_distributed_artifacts(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param int id: Product milestone id (required) :param int page_index: Page Index :param int page_size: Pagination size :param str sort: Sorting RSQL :param str q: RSQL Query :return: ArtifactPage If the method is called asynchronously, returns the request thread.
[ "Get", "the", "artifacts", "distributed", "in", "this", "milestone", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", ...
train
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/productmilestones_api.py#L708-L736