repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
kcolford/txt2boil
txt2boil/cmi.py
AbstractCMI._getSuperFunc
def _getSuperFunc(self, s, func): """Return the the super function.""" return getattr(super(self.cls(), s), func.__name__)
python
def _getSuperFunc(self, s, func): """Return the the super function.""" return getattr(super(self.cls(), s), func.__name__)
[ "def", "_getSuperFunc", "(", "self", ",", "s", ",", "func", ")", ":", "return", "getattr", "(", "super", "(", "self", ".", "cls", "(", ")", ",", "s", ")", ",", "func", ".", "__name__", ")" ]
Return the the super function.
[ "Return", "the", "the", "super", "function", "." ]
train
https://github.com/kcolford/txt2boil/blob/853a47bb8db27c0224531f24dfd02839c983d027/txt2boil/cmi.py#L72-L75
abalkin/tz
pavement.py
_doc_make
def _doc_make(*make_args): """Run make in sphinx' docs directory. :return: exit code """ if sys.platform == 'win32': # Windows make_cmd = ['make.bat'] else: # Linux, Mac OS X, and others make_cmd = ['make'] make_cmd.extend(make_args) # Account for a stupid P...
python
def _doc_make(*make_args): """Run make in sphinx' docs directory. :return: exit code """ if sys.platform == 'win32': # Windows make_cmd = ['make.bat'] else: # Linux, Mac OS X, and others make_cmd = ['make'] make_cmd.extend(make_args) # Account for a stupid P...
[ "def", "_doc_make", "(", "*", "make_args", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "# Windows", "make_cmd", "=", "[", "'make.bat'", "]", "else", ":", "# Linux, Mac OS X, and others", "make_cmd", "=", "[", "'make'", "]", "make_cmd", ".",...
Run make in sphinx' docs directory. :return: exit code
[ "Run", "make", "in", "sphinx", "docs", "directory", "." ]
train
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/pavement.py#L69-L86
abalkin/tz
pavement.py
coverage
def coverage(): """Run tests and show test coverage report.""" try: import pytest_cov # NOQA except ImportError: print_failure_message( 'Install the pytest coverage plugin to use this task, ' "i.e., `pip install pytest-cov'.") raise SystemExit(1) import p...
python
def coverage(): """Run tests and show test coverage report.""" try: import pytest_cov # NOQA except ImportError: print_failure_message( 'Install the pytest coverage plugin to use this task, ' "i.e., `pip install pytest-cov'.") raise SystemExit(1) import p...
[ "def", "coverage", "(", ")", ":", "try", ":", "import", "pytest_cov", "# NOQA", "except", "ImportError", ":", "print_failure_message", "(", "'Install the pytest coverage plugin to use this task, '", "\"i.e., `pip install pytest-cov'.\"", ")", "raise", "SystemExit", "(", "1"...
Run tests and show test coverage report.
[ "Run", "tests", "and", "show", "test", "coverage", "report", "." ]
train
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/pavement.py#L148-L162
abalkin/tz
pavement.py
doc_watch
def doc_watch(): """Watch for changes in the docs and rebuild HTML docs when changed.""" try: from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer except ImportError: print_failure_message('Install the watchdog package to use this task, ' ...
python
def doc_watch(): """Watch for changes in the docs and rebuild HTML docs when changed.""" try: from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer except ImportError: print_failure_message('Install the watchdog package to use this task, ' ...
[ "def", "doc_watch", "(", ")", ":", "try", ":", "from", "watchdog", ".", "events", "import", "FileSystemEventHandler", "from", "watchdog", ".", "observers", "import", "Observer", "except", "ImportError", ":", "print_failure_message", "(", "'Install the watchdog package...
Watch for changes in the docs and rebuild HTML docs when changed.
[ "Watch", "for", "changes", "in", "the", "docs", "and", "rebuild", "HTML", "docs", "when", "changed", "." ]
train
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/pavement.py#L166-L214
abalkin/tz
pavement.py
doc_open
def doc_open(): """Build the HTML docs and open them in a web browser.""" doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html') if sys.platform == 'darwin': # Mac OS X subprocess.check_call(['open', doc_index]) elif sys.platform == 'win32': # Windows sub...
python
def doc_open(): """Build the HTML docs and open them in a web browser.""" doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html') if sys.platform == 'darwin': # Mac OS X subprocess.check_call(['open', doc_index]) elif sys.platform == 'win32': # Windows sub...
[ "def", "doc_open", "(", ")", ":", "doc_index", "=", "os", ".", "path", ".", "join", "(", "DOCS_DIRECTORY", ",", "'build'", ",", "'html'", ",", "'index.html'", ")", "if", "sys", ".", "platform", "==", "'darwin'", ":", "# Mac OS X", "subprocess", ".", "che...
Build the HTML docs and open them in a web browser.
[ "Build", "the", "HTML", "docs", "and", "open", "them", "in", "a", "web", "browser", "." ]
train
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/pavement.py#L219-L234
abalkin/tz
pavement.py
get_tasks
def get_tasks(): """Get all paver-defined tasks.""" from paver.tasks import environment for tsk in environment.get_tasks(): print(tsk.shortname)
python
def get_tasks(): """Get all paver-defined tasks.""" from paver.tasks import environment for tsk in environment.get_tasks(): print(tsk.shortname)
[ "def", "get_tasks", "(", ")", ":", "from", "paver", ".", "tasks", "import", "environment", "for", "tsk", "in", "environment", ".", "get_tasks", "(", ")", ":", "print", "(", "tsk", ".", "shortname", ")" ]
Get all paver-defined tasks.
[ "Get", "all", "paver", "-", "defined", "tasks", "." ]
train
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/pavement.py#L238-L242
dr4ke616/pinky
twisted/plugins/node.py
NodeServiceMaker.makeService
def makeService(self, options): """ Construct a Node Server """ return NodeService( port=options['port'], host=options['host'], broker_host=options['broker_host'], broker_port=options['broker_port'], debug=options['debug'] )
python
def makeService(self, options): """ Construct a Node Server """ return NodeService( port=options['port'], host=options['host'], broker_host=options['broker_host'], broker_port=options['broker_port'], debug=options['debug'] )
[ "def", "makeService", "(", "self", ",", "options", ")", ":", "return", "NodeService", "(", "port", "=", "options", "[", "'port'", "]", ",", "host", "=", "options", "[", "'host'", "]", ",", "broker_host", "=", "options", "[", "'broker_host'", "]", ",", ...
Construct a Node Server
[ "Construct", "a", "Node", "Server" ]
train
https://github.com/dr4ke616/pinky/blob/35c165f5a1d410be467621f3152df1dbf458622a/twisted/plugins/node.py#L29-L38
josegomezr/pqb
pqb/expressions.py
AliasExpression.result
def result(self): """ Construye la expresion """ field = re.sub(REGEX_CLEANER, '', self.field_name) if self.alias: alias = re.sub(REGEX_CLEANER, '', self.alias) return "%s AS %s" % (field, alias) else: return field
python
def result(self): """ Construye la expresion """ field = re.sub(REGEX_CLEANER, '', self.field_name) if self.alias: alias = re.sub(REGEX_CLEANER, '', self.alias) return "%s AS %s" % (field, alias) else: return field
[ "def", "result", "(", "self", ")", ":", "field", "=", "re", ".", "sub", "(", "REGEX_CLEANER", ",", "''", ",", "self", ".", "field_name", ")", "if", "self", ".", "alias", ":", "alias", "=", "re", ".", "sub", "(", "REGEX_CLEANER", ",", "''", ",", "...
Construye la expresion
[ "Construye", "la", "expresion" ]
train
https://github.com/josegomezr/pqb/blob/a600cc6e4e9acdaaf2cff171d13eb85c9ed1757c/pqb/expressions.py#L18-L28
josegomezr/pqb
pqb/expressions.py
ConditionExpression.result
def result(self): """ Construye la expresion """ field = re.sub(REGEX_CLEANER, '', self.field) try: value = float(self.value) except TypeError: value = "(%s)" % ( "', '".join(self.value) ) except ValueError: value = str(...
python
def result(self): """ Construye la expresion """ field = re.sub(REGEX_CLEANER, '', self.field) try: value = float(self.value) except TypeError: value = "(%s)" % ( "', '".join(self.value) ) except ValueError: value = str(...
[ "def", "result", "(", "self", ")", ":", "field", "=", "re", ".", "sub", "(", "REGEX_CLEANER", ",", "''", ",", "self", ".", "field", ")", "try", ":", "value", "=", "float", "(", "self", ".", "value", ")", "except", "TypeError", ":", "value", "=", ...
Construye la expresion
[ "Construye", "la", "expresion" ]
train
https://github.com/josegomezr/pqb/blob/a600cc6e4e9acdaaf2cff171d13eb85c9ed1757c/pqb/expressions.py#L41-L65
unixorn/haze
haze/cli/commands.py
awsReadInstanceTag
def awsReadInstanceTag(): """Print key from a running instance's metadata""" parser = argparse.ArgumentParser() parser.add_argument("--tag", dest="tag", required=True, help="Which instance tag to read") cli = parser.parse_args() print haze.ec...
python
def awsReadInstanceTag(): """Print key from a running instance's metadata""" parser = argparse.ArgumentParser() parser.add_argument("--tag", dest="tag", required=True, help="Which instance tag to read") cli = parser.parse_args() print haze.ec...
[ "def", "awsReadInstanceTag", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"--tag\"", ",", "dest", "=", "\"tag\"", ",", "required", "=", "True", ",", "help", "=", "\"Which instance tag to read\...
Print key from a running instance's metadata
[ "Print", "key", "from", "a", "running", "instance", "s", "metadata" ]
train
https://github.com/unixorn/haze/blob/77692b18e6574ac356e3e16659b96505c733afff/haze/cli/commands.py#L60-L70
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.add_to_triplestore
def add_to_triplestore(self, output): """Method attempts to add output to Blazegraph RDF Triplestore""" if len(output) > 0: result = self.ext_conn.load_data(data=output.serialize(), datatype='rdf')
python
def add_to_triplestore(self, output): """Method attempts to add output to Blazegraph RDF Triplestore""" if len(output) > 0: result = self.ext_conn.load_data(data=output.serialize(), datatype='rdf')
[ "def", "add_to_triplestore", "(", "self", ",", "output", ")", ":", "if", "len", "(", "output", ")", ">", "0", ":", "result", "=", "self", ".", "ext_conn", ".", "load_data", "(", "data", "=", "output", ".", "serialize", "(", ")", ",", "datatype", "=",...
Method attempts to add output to Blazegraph RDF Triplestore
[ "Method", "attempts", "to", "add", "output", "to", "Blazegraph", "RDF", "Triplestore" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L397-L401
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.generate_term
def generate_term(self, **kwargs): """Method generates a rdflib.Term based on kwargs""" term_map = kwargs.pop('term_map') if hasattr(term_map, "termType") and\ term_map.termType == NS_MGR.rr.BlankNode.rdflib: return rdflib.BNode() if not hasattr(term_map, 'datatyp...
python
def generate_term(self, **kwargs): """Method generates a rdflib.Term based on kwargs""" term_map = kwargs.pop('term_map') if hasattr(term_map, "termType") and\ term_map.termType == NS_MGR.rr.BlankNode.rdflib: return rdflib.BNode() if not hasattr(term_map, 'datatyp...
[ "def", "generate_term", "(", "self", ",", "*", "*", "kwargs", ")", ":", "term_map", "=", "kwargs", ".", "pop", "(", "'term_map'", ")", "if", "hasattr", "(", "term_map", ",", "\"termType\"", ")", "and", "term_map", ".", "termType", "==", "NS_MGR", ".", ...
Method generates a rdflib.Term based on kwargs
[ "Method", "generates", "a", "rdflib", ".", "Term", "based", "on", "kwargs" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L403-L426
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.run
def run(self, **kwargs): """Run method iterates through triple maps and calls the execute method""" if 'timestamp' not in kwargs: kwargs['timestamp'] = datetime.datetime.utcnow().isoformat() if 'version' not in kwargs: kwargs['version'] = "Not Defined" #bibcat.__v...
python
def run(self, **kwargs): """Run method iterates through triple maps and calls the execute method""" if 'timestamp' not in kwargs: kwargs['timestamp'] = datetime.datetime.utcnow().isoformat() if 'version' not in kwargs: kwargs['version'] = "Not Defined" #bibcat.__v...
[ "def", "run", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'timestamp'", "not", "in", "kwargs", ":", "kwargs", "[", "'timestamp'", "]", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", ")", "if", "'version'"...
Run method iterates through triple maps and calls the execute method
[ "Run", "method", "iterates", "through", "triple", "maps", "and", "calls", "the", "execute", "method" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L432-L444
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.set_context
def set_context(self): """ Reads throught the namespaces in the RML and generates a context for json+ld output when compared to the RdfNsManager namespaces """ results = self.rml.query(""" SELECT ?o { { ?s rr:class ?o ...
python
def set_context(self): """ Reads throught the namespaces in the RML and generates a context for json+ld output when compared to the RdfNsManager namespaces """ results = self.rml.query(""" SELECT ?o { { ?s rr:class ?o ...
[ "def", "set_context", "(", "self", ")", ":", "results", "=", "self", ".", "rml", ".", "query", "(", "\"\"\"\n SELECT ?o {\n {\n ?s rr:class ?o\n } UNION {\n ?s rr:predicate ?o\n ...
Reads throught the namespaces in the RML and generates a context for json+ld output when compared to the RdfNsManager namespaces
[ "Reads", "throught", "the", "namespaces", "in", "the", "RML", "and", "generates", "a", "context", "for", "json", "+", "ld", "output", "when", "compared", "to", "the", "RdfNsManager", "namespaces" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L446-L462
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.set_list_predicates
def set_list_predicates(self): """ Reads through the rml mappings and determines all fields that should map to a list/array with a json output """ results = self.rml.query(""" SELECT DISTINCT ?subj_class ?list_field { ?bn rr:dat...
python
def set_list_predicates(self): """ Reads through the rml mappings and determines all fields that should map to a list/array with a json output """ results = self.rml.query(""" SELECT DISTINCT ?subj_class ?list_field { ?bn rr:dat...
[ "def", "set_list_predicates", "(", "self", ")", ":", "results", "=", "self", ".", "rml", ".", "query", "(", "\"\"\"\n SELECT DISTINCT ?subj_class ?list_field\n {\n ?bn rr:datatype rdf:List .\n ?bn rr:predicate ?list_fiel...
Reads through the rml mappings and determines all fields that should map to a list/array with a json output
[ "Reads", "through", "the", "rml", "mappings", "and", "determines", "all", "fields", "that", "should", "map", "to", "a", "list", "/", "array", "with", "a", "json", "output" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L464-L486
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.json_ld
def json_ld(self, output, **kwargs): """ Returns the json-ld formated result """ raw_json_ld = output.serialize(format='json-ld', context=self.context).decode() # if there are fields that should be returned as arrays convert all # no...
python
def json_ld(self, output, **kwargs): """ Returns the json-ld formated result """ raw_json_ld = output.serialize(format='json-ld', context=self.context).decode() # if there are fields that should be returned as arrays convert all # no...
[ "def", "json_ld", "(", "self", ",", "output", ",", "*", "*", "kwargs", ")", ":", "raw_json_ld", "=", "output", ".", "serialize", "(", "format", "=", "'json-ld'", ",", "context", "=", "self", ".", "context", ")", ".", "decode", "(", ")", "# if there are...
Returns the json-ld formated result
[ "Returns", "the", "json", "-", "ld", "formated", "result" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L501-L519
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
CSVRowProcessor.execute
def execute(self, triple_map, output, **kwargs): """Method executes mapping between CSV source and output RDF args: triple_map(SimpleNamespace): Triple Map """ subject = self.generate_term(term_map=triple_map.subjectMap, **kwargs)...
python
def execute(self, triple_map, output, **kwargs): """Method executes mapping between CSV source and output RDF args: triple_map(SimpleNamespace): Triple Map """ subject = self.generate_term(term_map=triple_map.subjectMap, **kwargs)...
[ "def", "execute", "(", "self", ",", "triple_map", ",", "output", ",", "*", "*", "kwargs", ")", ":", "subject", "=", "self", ".", "generate_term", "(", "term_map", "=", "triple_map", ".", "subjectMap", ",", "*", "*", "kwargs", ")", "start_size", "=", "l...
Method executes mapping between CSV source and output RDF args: triple_map(SimpleNamespace): Triple Map
[ "Method", "executes", "mapping", "between", "CSV", "source", "and", "output", "RDF" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L586-L626
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
CSVRowProcessor.run
def run(self, row, **kwargs): """Methods takes a row and depending if a dict or list, runs RML rules. Args: ----- row(Dict, List): Row from CSV Reader """ self.source = row kwargs['output'] = self.__graph__() super(CSVRowProcessor, self).run(*...
python
def run(self, row, **kwargs): """Methods takes a row and depending if a dict or list, runs RML rules. Args: ----- row(Dict, List): Row from CSV Reader """ self.source = row kwargs['output'] = self.__graph__() super(CSVRowProcessor, self).run(*...
[ "def", "run", "(", "self", ",", "row", ",", "*", "*", "kwargs", ")", ":", "self", ".", "source", "=", "row", "kwargs", "[", "'output'", "]", "=", "self", ".", "__graph__", "(", ")", "super", "(", "CSVRowProcessor", ",", "self", ")", ".", "run", "...
Methods takes a row and depending if a dict or list, runs RML rules. Args: ----- row(Dict, List): Row from CSV Reader
[ "Methods", "takes", "a", "row", "and", "depending", "if", "a", "dict", "or", "list", "runs", "RML", "rules", "." ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L630-L641
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
JSONProcessor.execute
def execute(self, triple_map, output, **kwargs): """Method executes mapping between JSON source and output RDF Args: ----- triple_map: SimpleNamespace """ subjects = [] logical_src_iterator = str(triple_map.logicalSource.iterator) json_object...
python
def execute(self, triple_map, output, **kwargs): """Method executes mapping between JSON source and output RDF Args: ----- triple_map: SimpleNamespace """ subjects = [] logical_src_iterator = str(triple_map.logicalSource.iterator) json_object...
[ "def", "execute", "(", "self", ",", "triple_map", ",", "output", ",", "*", "*", "kwargs", ")", ":", "subjects", "=", "[", "]", "logical_src_iterator", "=", "str", "(", "triple_map", ".", "logicalSource", ".", "iterator", ")", "json_object", "=", "kwargs", ...
Method executes mapping between JSON source and output RDF Args: ----- triple_map: SimpleNamespace
[ "Method", "executes", "mapping", "between", "JSON", "source", "and", "output", "RDF" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L685-L736
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
JSONProcessor.run
def run(self, source, **kwargs): """Method takes a JSON source and any keywords and transforms from JSON to Lean BIBFRAME 2.0 triples Args: ---- source: str, dict """ kwargs['output'] = self.__graph__() if isinstance(source, str): import ...
python
def run(self, source, **kwargs): """Method takes a JSON source and any keywords and transforms from JSON to Lean BIBFRAME 2.0 triples Args: ---- source: str, dict """ kwargs['output'] = self.__graph__() if isinstance(source, str): import ...
[ "def", "run", "(", "self", ",", "source", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'output'", "]", "=", "self", ".", "__graph__", "(", ")", "if", "isinstance", "(", "source", ",", "str", ")", ":", "import", "json", "source", "=", "json", ...
Method takes a JSON source and any keywords and transforms from JSON to Lean BIBFRAME 2.0 triples Args: ---- source: str, dict
[ "Method", "takes", "a", "JSON", "source", "and", "any", "keywords", "and", "transforms", "from", "JSON", "to", "Lean", "BIBFRAME", "2", ".", "0", "triples" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L738-L754
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
XMLProcessor.execute
def execute(self, triple_map, output, **kwargs): """Method executes mapping between source Args: ----- triple_map: SimpleNamespace, Triple Map """ subjects = [] found_elements = self.source.xpath( str(triple_map.logicalSource.iterator), ...
python
def execute(self, triple_map, output, **kwargs): """Method executes mapping between source Args: ----- triple_map: SimpleNamespace, Triple Map """ subjects = [] found_elements = self.source.xpath( str(triple_map.logicalSource.iterator), ...
[ "def", "execute", "(", "self", ",", "triple_map", ",", "output", ",", "*", "*", "kwargs", ")", ":", "subjects", "=", "[", "]", "found_elements", "=", "self", ".", "source", ".", "xpath", "(", "str", "(", "triple_map", ".", "logicalSource", ".", "iterat...
Method executes mapping between source Args: ----- triple_map: SimpleNamespace, Triple Map
[ "Method", "executes", "mapping", "between", "source" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L846-L890
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
XMLProcessor.run
def run(self, xml, **kwargs): """Method takes either an etree.ElementTree or raw XML text as the first argument. Args: xml(etree.ElementTree or text """ kwargs['output'] = self.__graph__() if isinstance(xml, str): try: self.source ...
python
def run(self, xml, **kwargs): """Method takes either an etree.ElementTree or raw XML text as the first argument. Args: xml(etree.ElementTree or text """ kwargs['output'] = self.__graph__() if isinstance(xml, str): try: self.source ...
[ "def", "run", "(", "self", ",", "xml", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'output'", "]", "=", "self", ".", "__graph__", "(", ")", "if", "isinstance", "(", "xml", ",", "str", ")", ":", "try", ":", "self", ".", "source", "=", "et...
Method takes either an etree.ElementTree or raw XML text as the first argument. Args: xml(etree.ElementTree or text
[ "Method", "takes", "either", "an", "etree", ".", "ElementTree", "or", "raw", "XML", "text", "as", "the", "first", "argument", "." ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L894-L914
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
SPARQLProcessor.execute
def execute(self, triple_map, output, **kwargs): """Execute """ subjects = [] if NS_MGR.ql.JSON.rdflib in \ triple_map.logicalSource.reference_formulations: output_format = "json" else: output_format = "xml" if 'limit' not in kwargs: ...
python
def execute(self, triple_map, output, **kwargs): """Execute """ subjects = [] if NS_MGR.ql.JSON.rdflib in \ triple_map.logicalSource.reference_formulations: output_format = "json" else: output_format = "xml" if 'limit' not in kwargs: ...
[ "def", "execute", "(", "self", ",", "triple_map", ",", "output", ",", "*", "*", "kwargs", ")", ":", "subjects", "=", "[", "]", "if", "NS_MGR", ".", "ql", ".", "JSON", ".", "rdflib", "in", "triple_map", ".", "logicalSource", ".", "reference_formulations",...
Execute
[ "Execute" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L1010-L1128
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
SPARQLBatchProcessor.execute
def execute(self, triple_map, output, **kwargs): """Method iterates through triple map's predicate object maps and processes query. Args: triple_map(SimpleNamespace): Triple Map """ sparql = PREFIX + triple_map.logicalSource.query.format( **kwargs) ...
python
def execute(self, triple_map, output, **kwargs): """Method iterates through triple map's predicate object maps and processes query. Args: triple_map(SimpleNamespace): Triple Map """ sparql = PREFIX + triple_map.logicalSource.query.format( **kwargs) ...
[ "def", "execute", "(", "self", ",", "triple_map", ",", "output", ",", "*", "*", "kwargs", ")", ":", "sparql", "=", "PREFIX", "+", "triple_map", ".", "logicalSource", ".", "query", ".", "format", "(", "*", "*", "kwargs", ")", "bindings", "=", "self", ...
Method iterates through triple map's predicate object maps and processes query. Args: triple_map(SimpleNamespace): Triple Map
[ "Method", "iterates", "through", "triple", "map", "s", "predicate", "object", "maps", "and", "processes", "query", "." ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L1191-L1236
eallik/spinoff
spinoff/actor/ref.py
Ref.send
def send(self, message, _sender=None): """Sends a message to the actor represented by this `Ref`.""" if not _sender: context = get_context() if context: _sender = context.ref if self._cell: if not self._cell.stopped: self._cell....
python
def send(self, message, _sender=None): """Sends a message to the actor represented by this `Ref`.""" if not _sender: context = get_context() if context: _sender = context.ref if self._cell: if not self._cell.stopped: self._cell....
[ "def", "send", "(", "self", ",", "message", ",", "_sender", "=", "None", ")", ":", "if", "not", "_sender", ":", "context", "=", "get_context", "(", ")", "if", "context", ":", "_sender", "=", "context", ".", "ref", "if", "self", ".", "_cell", ":", "...
Sends a message to the actor represented by this `Ref`.
[ "Sends", "a", "message", "to", "the", "actor", "represented", "by", "this", "Ref", "." ]
train
https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/actor/ref.py#L139-L170
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentSecurityForm.security_errors
def security_errors(self): """Return just those errors associated with security""" errors = ErrorDict() for f in ["honeypot", "timestamp", "security_hash"]: if f in self.errors: errors[f] = self.errors[f] return errors
python
def security_errors(self): """Return just those errors associated with security""" errors = ErrorDict() for f in ["honeypot", "timestamp", "security_hash"]: if f in self.errors: errors[f] = self.errors[f] return errors
[ "def", "security_errors", "(", "self", ")", ":", "errors", "=", "ErrorDict", "(", ")", "for", "f", "in", "[", "\"honeypot\"", ",", "\"timestamp\"", ",", "\"security_hash\"", "]", ":", "if", "f", "in", "self", ".", "errors", ":", "errors", "[", "f", "]"...
Return just those errors associated with security
[ "Return", "just", "those", "errors", "associated", "with", "security" ]
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L34-L40
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentSecurityForm.clean_security_hash
def clean_security_hash(self): """Check the security hash.""" security_hash_dict = { 'content_type': self.data.get("content_type", ""), 'object_pk': self.data.get("object_pk", ""), 'timestamp': self.data.get("timestamp", ""), } expected_hash = self.gen...
python
def clean_security_hash(self): """Check the security hash.""" security_hash_dict = { 'content_type': self.data.get("content_type", ""), 'object_pk': self.data.get("object_pk", ""), 'timestamp': self.data.get("timestamp", ""), } expected_hash = self.gen...
[ "def", "clean_security_hash", "(", "self", ")", ":", "security_hash_dict", "=", "{", "'content_type'", ":", "self", ".", "data", ".", "get", "(", "\"content_type\"", ",", "\"\"", ")", ",", "'object_pk'", ":", "self", ".", "data", ".", "get", "(", "\"object...
Check the security hash.
[ "Check", "the", "security", "hash", "." ]
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L42-L53
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentSecurityForm.clean_timestamp
def clean_timestamp(self): """Make sure the timestamp isn't too far (> 2 hours) in the past.""" ts = self.cleaned_data["timestamp"] if time.time() - ts > (2 * 60 * 60): raise forms.ValidationError("Timestamp check failed") return ts
python
def clean_timestamp(self): """Make sure the timestamp isn't too far (> 2 hours) in the past.""" ts = self.cleaned_data["timestamp"] if time.time() - ts > (2 * 60 * 60): raise forms.ValidationError("Timestamp check failed") return ts
[ "def", "clean_timestamp", "(", "self", ")", ":", "ts", "=", "self", ".", "cleaned_data", "[", "\"timestamp\"", "]", "if", "time", ".", "time", "(", ")", "-", "ts", ">", "(", "2", "*", "60", "*", "60", ")", ":", "raise", "forms", ".", "ValidationErr...
Make sure the timestamp isn't too far (> 2 hours) in the past.
[ "Make", "sure", "the", "timestamp", "isn", "t", "too", "far", "(", ">", "2", "hours", ")", "in", "the", "past", "." ]
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L55-L60
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentSecurityForm.generate_security_data
def generate_security_data(self): """Generate a dict of security data for "initial" data.""" timestamp = int(time.time()) security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(time...
python
def generate_security_data(self): """Generate a dict of security data for "initial" data.""" timestamp = int(time.time()) security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(time...
[ "def", "generate_security_data", "(", "self", ")", ":", "timestamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "security_dict", "=", "{", "'content_type'", ":", "str", "(", "self", ".", "target_object", ".", "_meta", ")", ",", "'object_pk'", "...
Generate a dict of security data for "initial" data.
[ "Generate", "a", "dict", "of", "security", "data", "for", "initial", "data", "." ]
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L62-L71
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentSecurityForm.initial_security_hash
def initial_security_hash(self, timestamp): """ Generate the initial security hash from self.content_object and a (unix) timestamp. """ initial_security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_va...
python
def initial_security_hash(self, timestamp): """ Generate the initial security hash from self.content_object and a (unix) timestamp. """ initial_security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_va...
[ "def", "initial_security_hash", "(", "self", ",", "timestamp", ")", ":", "initial_security_dict", "=", "{", "'content_type'", ":", "str", "(", "self", ".", "target_object", ".", "_meta", ")", ",", "'object_pk'", ":", "str", "(", "self", ".", "target_object", ...
Generate the initial security hash from self.content_object and a (unix) timestamp.
[ "Generate", "the", "initial", "security", "hash", "from", "self", ".", "content_object", "and", "a", "(", "unix", ")", "timestamp", "." ]
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L73-L84
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentSecurityForm.generate_security_hash
def generate_security_hash(self, content_type, object_pk, timestamp): """ Generate a HMAC security hash from the provided info. """ info = (content_type, object_pk, timestamp) key_salt = "django.contrib.forms.CommentSecurityForm" value = "-".join(info) return salt...
python
def generate_security_hash(self, content_type, object_pk, timestamp): """ Generate a HMAC security hash from the provided info. """ info = (content_type, object_pk, timestamp) key_salt = "django.contrib.forms.CommentSecurityForm" value = "-".join(info) return salt...
[ "def", "generate_security_hash", "(", "self", ",", "content_type", ",", "object_pk", ",", "timestamp", ")", ":", "info", "=", "(", "content_type", ",", "object_pk", ",", "timestamp", ")", "key_salt", "=", "\"django.contrib.forms.CommentSecurityForm\"", "value", "=",...
Generate a HMAC security hash from the provided info.
[ "Generate", "a", "HMAC", "security", "hash", "from", "the", "provided", "info", "." ]
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L86-L93
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentDetailsForm.get_comment_object
def get_comment_object(self): """ Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user...
python
def get_comment_object(self): """ Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user...
[ "def", "get_comment_object", "(", "self", ")", ":", "if", "not", "self", ".", "is_valid", "(", ")", ":", "raise", "ValueError", "(", "\"get_comment_object may only be called on valid forms\"", ")", "CommentModel", "=", "self", ".", "get_comment_model", "(", ")", "...
Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``).
[ "Return", "a", "new", "(", "unsaved", ")", "comment", "object", "based", "on", "the", "information", "in", "this", "form", ".", "Assumes", "that", "the", "form", "is", "already", "validated", "and", "will", "throw", "a", "ValueError", "if", "not", "." ]
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L110-L126
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentDetailsForm.get_comment_create_data
def get_comment_create_data(self): """ Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model. """ user_model = get_user_model() ...
python
def get_comment_create_data(self): """ Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model. """ user_model = get_user_model() ...
[ "def", "get_comment_create_data", "(", "self", ")", ":", "user_model", "=", "get_user_model", "(", ")", "return", "dict", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "self", ".", "target_object", ")", ",", "object_pk", "...
Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model.
[ "Returns", "the", "dict", "of", "data", "to", "be", "used", "to", "create", "a", "comment", ".", "Subclasses", "in", "custom", "comment", "apps", "that", "override", "get_comment_model", "can", "override", "this", "method", "to", "add", "extra", "fields", "o...
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L136-L152
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentDetailsForm.check_for_duplicate_comment
def check_for_duplicate_comment(self, new): """ Check that a submitted comment isn't a duplicate. This might be caused by someone posting a comment twice. If it is a dup, silently return the *previous* comment. """ possible_duplicates = self.get_comment_model()._default_manager.u...
python
def check_for_duplicate_comment(self, new): """ Check that a submitted comment isn't a duplicate. This might be caused by someone posting a comment twice. If it is a dup, silently return the *previous* comment. """ possible_duplicates = self.get_comment_model()._default_manager.u...
[ "def", "check_for_duplicate_comment", "(", "self", ",", "new", ")", ":", "possible_duplicates", "=", "self", ".", "get_comment_model", "(", ")", ".", "_default_manager", ".", "using", "(", "self", ".", "target_object", ".", "_state", ".", "db", ")", ".", "fi...
Check that a submitted comment isn't a duplicate. This might be caused by someone posting a comment twice. If it is a dup, silently return the *previous* comment.
[ "Check", "that", "a", "submitted", "comment", "isn", "t", "a", "duplicate", ".", "This", "might", "be", "caused", "by", "someone", "posting", "a", "comment", "twice", ".", "If", "it", "is", "a", "dup", "silently", "return", "the", "*", "previous", "*", ...
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L154-L169
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentDetailsForm.clean_comment
def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ comment = self.cleaned_data["text"] if settings.COMMENTS_ALLOW_PROFANITIES is False: bad_words = [w for w in settings....
python
def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ comment = self.cleaned_data["text"] if settings.COMMENTS_ALLOW_PROFANITIES is False: bad_words = [w for w in settings....
[ "def", "clean_comment", "(", "self", ")", ":", "comment", "=", "self", ".", "cleaned_data", "[", "\"text\"", "]", "if", "settings", ".", "COMMENTS_ALLOW_PROFANITIES", "is", "False", ":", "bad_words", "=", "[", "w", "for", "w", "in", "settings", ".", "PROFA...
If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST.
[ "If", "COMMENTS_ALLOW_PROFANITIES", "is", "False", "check", "that", "the", "comment", "doesn", "t", "contain", "anything", "in", "PROFANITIES_LIST", "." ]
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L171-L186
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentForm.clean_honeypot
def clean_honeypot(self): """Check that nothing's been entered into the honeypot.""" value = self.cleaned_data["honeypot"] if value: raise forms.ValidationError(self.fields["honeypot"].label) return value
python
def clean_honeypot(self): """Check that nothing's been entered into the honeypot.""" value = self.cleaned_data["honeypot"] if value: raise forms.ValidationError(self.fields["honeypot"].label) return value
[ "def", "clean_honeypot", "(", "self", ")", ":", "value", "=", "self", ".", "cleaned_data", "[", "\"honeypot\"", "]", "if", "value", ":", "raise", "forms", ".", "ValidationError", "(", "self", ".", "fields", "[", "\"honeypot\"", "]", ".", "label", ")", "r...
Check that nothing's been entered into the honeypot.
[ "Check", "that", "nothing", "s", "been", "entered", "into", "the", "honeypot", "." ]
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L195-L200
refinery29/chassis
chassis/util/decorators.py
include_original
def include_original(dec): """Decorate decorators so they include a copy of the original function.""" def meta_decorator(method): """Yo dawg, I heard you like decorators...""" # pylint: disable=protected-access decorator = dec(method) decorator._original = method return d...
python
def include_original(dec): """Decorate decorators so they include a copy of the original function.""" def meta_decorator(method): """Yo dawg, I heard you like decorators...""" # pylint: disable=protected-access decorator = dec(method) decorator._original = method return d...
[ "def", "include_original", "(", "dec", ")", ":", "def", "meta_decorator", "(", "method", ")", ":", "\"\"\"Yo dawg, I heard you like decorators...\"\"\"", "# pylint: disable=protected-access", "decorator", "=", "dec", "(", "method", ")", "decorator", ".", "_original", "=...
Decorate decorators so they include a copy of the original function.
[ "Decorate", "decorators", "so", "they", "include", "a", "copy", "of", "the", "original", "function", "." ]
train
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/util/decorators.py#L4-L12
kderynski/blade-netconf-python-client
build/lib/bnclient/bnclient.py
bnclient.sendhello
def sendhello(self): try: # send hello cli_hello_msg = "<hello>\n" +\ " <capabilities>\n" +\ " <capability>urn:ietf:params:netconf:base:1.0</capability>\n" +\ " </capabilities>\n" +\ ...
python
def sendhello(self): try: # send hello cli_hello_msg = "<hello>\n" +\ " <capabilities>\n" +\ " <capability>urn:ietf:params:netconf:base:1.0</capability>\n" +\ " </capabilities>\n" +\ ...
[ "def", "sendhello", "(", "self", ")", ":", "try", ":", "# send hello\r", "cli_hello_msg", "=", "\"<hello>\\n\"", "+", "\" <capabilities>\\n\"", "+", "\" <capability>urn:ietf:params:netconf:base:1.0</capability>\\n\"", "+", "\" </capabilities>\\n\"", "+", "\"</hello>\\n\"",...
end of function exchgcaps
[ "end", "of", "function", "exchgcaps" ]
train
https://github.com/kderynski/blade-netconf-python-client/blob/87396921a1c75f1093adf4bb7b13428ee368b2b7/build/lib/bnclient/bnclient.py#L88-L106
kderynski/blade-netconf-python-client
build/lib/bnclient/bnclient.py
bnclient.sendrpc
def sendrpc(self, argv=[]): self._aArgv += argv _operation = '' try: self._cParams.parser(self._aArgv, self._dOptions) # set rpc operation handler while self._cParams.get('operation') not in rpc.operations.keys(): self._cParams.set('op...
python
def sendrpc(self, argv=[]): self._aArgv += argv _operation = '' try: self._cParams.parser(self._aArgv, self._dOptions) # set rpc operation handler while self._cParams.get('operation') not in rpc.operations.keys(): self._cParams.set('op...
[ "def", "sendrpc", "(", "self", ",", "argv", "=", "[", "]", ")", ":", "self", ".", "_aArgv", "+=", "argv", "_operation", "=", "''", "try", ":", "self", ".", "_cParams", ".", "parser", "(", "self", ".", "_aArgv", ",", "self", ".", "_dOptions", ")", ...
end of function exchgmsg
[ "end", "of", "function", "exchgmsg" ]
train
https://github.com/kderynski/blade-netconf-python-client/blob/87396921a1c75f1093adf4bb7b13428ee368b2b7/build/lib/bnclient/bnclient.py#L109-L141
carlitux/turboengine
src/turboengine/__init__.py
register_templatetags
def register_templatetags(): """ Register templatetags defined in settings as basic templatetags """ from turboengine.conf import settings from google.appengine.ext.webapp import template for python_file in settings.TEMPLATE_PATH: template.register_template_library(python_file)
python
def register_templatetags(): """ Register templatetags defined in settings as basic templatetags """ from turboengine.conf import settings from google.appengine.ext.webapp import template for python_file in settings.TEMPLATE_PATH: template.register_template_library(python_file)
[ "def", "register_templatetags", "(", ")", ":", "from", "turboengine", ".", "conf", "import", "settings", "from", "google", ".", "appengine", ".", "ext", ".", "webapp", "import", "template", "for", "python_file", "in", "settings", ".", "TEMPLATE_PATH", ":", "te...
Register templatetags defined in settings as basic templatetags
[ "Register", "templatetags", "defined", "in", "settings", "as", "basic", "templatetags" ]
train
https://github.com/carlitux/turboengine/blob/627b6dbc400d8c16e2ff7e17afd01915371ea287/src/turboengine/__init__.py#L28-L33
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.get_hosts
def get_hosts(self, pattern="all"): """ find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets. """ # process patterns if isinstance(pattern, list): pattern = ';'.join(pattern) patterns = patt...
python
def get_hosts(self, pattern="all"): """ find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets. """ # process patterns if isinstance(pattern, list): pattern = ';'.join(pattern) patterns = patt...
[ "def", "get_hosts", "(", "self", ",", "pattern", "=", "\"all\"", ")", ":", "# process patterns", "if", "isinstance", "(", "pattern", ",", "list", ")", ":", "pattern", "=", "';'", ".", "join", "(", "pattern", ")", "patterns", "=", "pattern", ".", "replace...
find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets.
[ "find", "all", "host", "names", "matching", "a", "pattern", "string", "taking", "into", "account", "any", "inventory", "restrictions", "or", "applied", "subsets", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L101-L124
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory._get_hosts
def _get_hosts(self, patterns): """ finds hosts that match a list of patterns. Handles negative matches as well as intersection matches. """ hosts = set() for p in patterns: if p.startswith("!"): # Discard excluded hosts hosts....
python
def _get_hosts(self, patterns): """ finds hosts that match a list of patterns. Handles negative matches as well as intersection matches. """ hosts = set() for p in patterns: if p.startswith("!"): # Discard excluded hosts hosts....
[ "def", "_get_hosts", "(", "self", ",", "patterns", ")", ":", "hosts", "=", "set", "(", ")", "for", "p", "in", "patterns", ":", "if", "p", ".", "startswith", "(", "\"!\"", ")", ":", "# Discard excluded hosts", "hosts", ".", "difference_update", "(", "self...
finds hosts that match a list of patterns. Handles negative matches as well as intersection matches.
[ "finds", "hosts", "that", "match", "a", "list", "of", "patterns", ".", "Handles", "negative", "matches", "as", "well", "as", "intersection", "matches", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L126-L143
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.__get_hosts
def __get_hosts(self, pattern): """ finds hosts that postively match a particular pattern. Does not take into account negative matches. """ (name, enumeration_details) = self._enumeration_info(pattern) hpat = self._hosts_in_unenumerated_pattern(name) hpat = sor...
python
def __get_hosts(self, pattern): """ finds hosts that postively match a particular pattern. Does not take into account negative matches. """ (name, enumeration_details) = self._enumeration_info(pattern) hpat = self._hosts_in_unenumerated_pattern(name) hpat = sor...
[ "def", "__get_hosts", "(", "self", ",", "pattern", ")", ":", "(", "name", ",", "enumeration_details", ")", "=", "self", ".", "_enumeration_info", "(", "pattern", ")", "hpat", "=", "self", ".", "_hosts_in_unenumerated_pattern", "(", "name", ")", "hpat", "=", ...
finds hosts that postively match a particular pattern. Does not take into account negative matches.
[ "finds", "hosts", "that", "postively", "match", "a", "particular", "pattern", ".", "Does", "not", "take", "into", "account", "negative", "matches", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L145-L155
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory._enumeration_info
def _enumeration_info(self, pattern): """ returns (pattern, limits) taking a regular pattern and finding out which parts of it correspond to start/stop offsets. limits is a tuple of (start, stop) or None """ if not "[" in pattern or pattern.startswith('~'): ...
python
def _enumeration_info(self, pattern): """ returns (pattern, limits) taking a regular pattern and finding out which parts of it correspond to start/stop offsets. limits is a tuple of (start, stop) or None """ if not "[" in pattern or pattern.startswith('~'): ...
[ "def", "_enumeration_info", "(", "self", ",", "pattern", ")", ":", "if", "not", "\"[\"", "in", "pattern", "or", "pattern", ".", "startswith", "(", "'~'", ")", ":", "return", "(", "pattern", ",", "None", ")", "(", "first", ",", "rest", ")", "=", "patt...
returns (pattern, limits) taking a regular pattern and finding out which parts of it correspond to start/stop offsets. limits is a tuple of (start, stop) or None
[ "returns", "(", "pattern", "limits", ")", "taking", "a", "regular", "pattern", "and", "finding", "out", "which", "parts", "of", "it", "correspond", "to", "start", "/", "stop", "offsets", ".", "limits", "is", "a", "tuple", "of", "(", "start", "stop", ")",...
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L157-L172
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory._apply_ranges
def _apply_ranges(self, pat, hosts): """ given a pattern like foo, that matches hosts, return all of hosts given a pattern like foo[0:5], where foo matches hosts, return the first 6 hosts """ (loose_pattern, limits) = self._enumeration_info(pat) if not limits: ...
python
def _apply_ranges(self, pat, hosts): """ given a pattern like foo, that matches hosts, return all of hosts given a pattern like foo[0:5], where foo matches hosts, return the first 6 hosts """ (loose_pattern, limits) = self._enumeration_info(pat) if not limits: ...
[ "def", "_apply_ranges", "(", "self", ",", "pat", ",", "hosts", ")", ":", "(", "loose_pattern", ",", "limits", ")", "=", "self", ".", "_enumeration_info", "(", "pat", ")", "if", "not", "limits", ":", "return", "hosts", "(", "left", ",", "right", ")", ...
given a pattern like foo, that matches hosts, return all of hosts given a pattern like foo[0:5], where foo matches hosts, return the first 6 hosts
[ "given", "a", "pattern", "like", "foo", "that", "matches", "hosts", "return", "all", "of", "hosts", "given", "a", "pattern", "like", "foo", "[", "0", ":", "5", "]", "where", "foo", "matches", "hosts", "return", "the", "first", "6", "hosts" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L174-L193
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory._hosts_in_unenumerated_pattern
def _hosts_in_unenumerated_pattern(self, pattern): """ Get all host names matching the pattern """ hosts = {} # ignore any negative checks here, this is handled elsewhere pattern = pattern.replace("!","").replace("&", "") groups = self.get_groups() for group in groups: ...
python
def _hosts_in_unenumerated_pattern(self, pattern): """ Get all host names matching the pattern """ hosts = {} # ignore any negative checks here, this is handled elsewhere pattern = pattern.replace("!","").replace("&", "") groups = self.get_groups() for group in groups: ...
[ "def", "_hosts_in_unenumerated_pattern", "(", "self", ",", "pattern", ")", ":", "hosts", "=", "{", "}", "# ignore any negative checks here, this is handled elsewhere", "pattern", "=", "pattern", ".", "replace", "(", "\"!\"", ",", "\"\"", ")", ".", "replace", "(", ...
Get all host names matching the pattern
[ "Get", "all", "host", "names", "matching", "the", "pattern" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L196-L208
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.restrict_to
def restrict_to(self, restriction): """ Restrict list operations to the hosts given in restriction. This is used to exclude failed hosts in main playbook code, don't use this for other reasons. """ if type(restriction) != list: restriction = [ restriction ] ...
python
def restrict_to(self, restriction): """ Restrict list operations to the hosts given in restriction. This is used to exclude failed hosts in main playbook code, don't use this for other reasons. """ if type(restriction) != list: restriction = [ restriction ] ...
[ "def", "restrict_to", "(", "self", ",", "restriction", ")", ":", "if", "type", "(", "restriction", ")", "!=", "list", ":", "restriction", "=", "[", "restriction", "]", "self", ".", "_restriction", "=", "restriction" ]
Restrict list operations to the hosts given in restriction. This is used to exclude failed hosts in main playbook code, don't use this for other reasons.
[ "Restrict", "list", "operations", "to", "the", "hosts", "given", "in", "restriction", ".", "This", "is", "used", "to", "exclude", "failed", "hosts", "in", "main", "playbook", "code", "don", "t", "use", "this", "for", "other", "reasons", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L305-L313
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.also_restrict_to
def also_restrict_to(self, restriction): """ Works like restict_to but offers an additional restriction. Playbooks use this to implement serial behavior. """ if type(restriction) != list: restriction = [ restriction ] self._also_restriction = restriction
python
def also_restrict_to(self, restriction): """ Works like restict_to but offers an additional restriction. Playbooks use this to implement serial behavior. """ if type(restriction) != list: restriction = [ restriction ] self._also_restriction = restriction
[ "def", "also_restrict_to", "(", "self", ",", "restriction", ")", ":", "if", "type", "(", "restriction", ")", "!=", "list", ":", "restriction", "=", "[", "restriction", "]", "self", ".", "_also_restriction", "=", "restriction" ]
Works like restict_to but offers an additional restriction. Playbooks use this to implement serial behavior.
[ "Works", "like", "restict_to", "but", "offers", "an", "additional", "restriction", ".", "Playbooks", "use", "this", "to", "implement", "serial", "behavior", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L315-L322
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.subset
def subset(self, subset_pattern): """ Limits inventory results to a subset of inventory that matches a given pattern, such as to select a given geographic of numeric slice amongst a previous 'hosts' selection that only select roles, or vice versa. Corresponds to --limit parame...
python
def subset(self, subset_pattern): """ Limits inventory results to a subset of inventory that matches a given pattern, such as to select a given geographic of numeric slice amongst a previous 'hosts' selection that only select roles, or vice versa. Corresponds to --limit parame...
[ "def", "subset", "(", "self", ",", "subset_pattern", ")", ":", "if", "subset_pattern", "is", "None", ":", "self", ".", "_subset", "=", "None", "else", ":", "subset_pattern", "=", "subset_pattern", ".", "replace", "(", "','", ",", "':'", ")", "self", ".",...
Limits inventory results to a subset of inventory that matches a given pattern, such as to select a given geographic of numeric slice amongst a previous 'hosts' selection that only select roles, or vice versa. Corresponds to --limit parameter to ansible-playbook
[ "Limits", "inventory", "results", "to", "a", "subset", "of", "inventory", "that", "matches", "a", "given", "pattern", "such", "as", "to", "select", "a", "given", "geographic", "of", "numeric", "slice", "amongst", "a", "previous", "hosts", "selection", "that", ...
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L324-L335
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.is_file
def is_file(self): """ did inventory come from a file? """ if not isinstance(self.host_list, basestring): return False return os.path.exists(self.host_list)
python
def is_file(self): """ did inventory come from a file? """ if not isinstance(self.host_list, basestring): return False return os.path.exists(self.host_list)
[ "def", "is_file", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "host_list", ",", "basestring", ")", ":", "return", "False", "return", "os", ".", "path", ".", "exists", "(", "self", ".", "host_list", ")" ]
did inventory come from a file?
[ "did", "inventory", "come", "from", "a", "file?" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L345-L349
robertdfrench/psychic-disco
psychic_disco/lambda_function.py
LambdaFunction.deploy
def deploy(self, package=None): """ If package is none, use `deployment_package.default()` """ if package is None: package = deployment_package.default() package.deploy() if self.proper_name in installed_functions(): self.update(package) else: ...
python
def deploy(self, package=None): """ If package is none, use `deployment_package.default()` """ if package is None: package = deployment_package.default() package.deploy() if self.proper_name in installed_functions(): self.update(package) else: ...
[ "def", "deploy", "(", "self", ",", "package", "=", "None", ")", ":", "if", "package", "is", "None", ":", "package", "=", "deployment_package", ".", "default", "(", ")", "package", ".", "deploy", "(", ")", "if", "self", ".", "proper_name", "in", "instal...
If package is none, use `deployment_package.default()`
[ "If", "package", "is", "none", "use", "deployment_package", ".", "default", "()" ]
train
https://github.com/robertdfrench/psychic-disco/blob/3cf167b44c64d64606691fc186be7d9ef8e8e938/psychic_disco/lambda_function.py#L58-L66
jkenlooper/chill
src/chill/shortcodes.py
register
def register(tag, end_tag=None): """ Decorator for registering shortcode functions. """ def register_function(function): tagmap[tag] = {'func': function, 'endtag': end_tag} if end_tag: tagmap['endtags'].append(end_tag) return function return register_function
python
def register(tag, end_tag=None): """ Decorator for registering shortcode functions. """ def register_function(function): tagmap[tag] = {'func': function, 'endtag': end_tag} if end_tag: tagmap['endtags'].append(end_tag) return function return register_function
[ "def", "register", "(", "tag", ",", "end_tag", "=", "None", ")", ":", "def", "register_function", "(", "function", ")", ":", "tagmap", "[", "tag", "]", "=", "{", "'func'", ":", "function", ",", "'endtag'", ":", "end_tag", "}", "if", "end_tag", ":", "...
Decorator for registering shortcode functions.
[ "Decorator", "for", "registering", "shortcode", "functions", "." ]
train
https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/shortcodes.py#L63-L72
tempodb/tempodb-python
tempodb/temporal/validate.py
check_time_param
def check_time_param(t): """Check whether a string sent in matches the ISO8601 format. If a Datetime object is passed instead, it will be converted into an ISO8601 compliant string. :param t: the datetime to check :type t: string or Datetime :rtype: string""" if type(t) is str: if...
python
def check_time_param(t): """Check whether a string sent in matches the ISO8601 format. If a Datetime object is passed instead, it will be converted into an ISO8601 compliant string. :param t: the datetime to check :type t: string or Datetime :rtype: string""" if type(t) is str: if...
[ "def", "check_time_param", "(", "t", ")", ":", "if", "type", "(", "t", ")", "is", "str", ":", "if", "not", "ISO", ".", "match", "(", "t", ")", ":", "raise", "ValueError", "(", "'Date string \"%s\" does not match ISO8601 format'", "%", "(", "t", ")", ")",...
Check whether a string sent in matches the ISO8601 format. If a Datetime object is passed instead, it will be converted into an ISO8601 compliant string. :param t: the datetime to check :type t: string or Datetime :rtype: string
[ "Check", "whether", "a", "string", "sent", "in", "matches", "the", "ISO8601", "format", ".", "If", "a", "Datetime", "object", "is", "passed", "instead", "it", "will", "be", "converted", "into", "an", "ISO8601", "compliant", "string", "." ]
train
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/temporal/validate.py#L11-L26
tempodb/tempodb-python
tempodb/temporal/validate.py
convert_iso_stamp
def convert_iso_stamp(t, tz=None): """Convert a string in ISO8601 form into a Datetime object. This is mainly used for converting timestamps sent from the TempoDB API, which are assumed to be correct. :param string t: the timestamp to convert :rtype: Datetime object""" if t is None: r...
python
def convert_iso_stamp(t, tz=None): """Convert a string in ISO8601 form into a Datetime object. This is mainly used for converting timestamps sent from the TempoDB API, which are assumed to be correct. :param string t: the timestamp to convert :rtype: Datetime object""" if t is None: r...
[ "def", "convert_iso_stamp", "(", "t", ",", "tz", "=", "None", ")", ":", "if", "t", "is", "None", ":", "return", "None", "dt", "=", "dateutil", ".", "parser", ".", "parse", "(", "t", ")", "if", "tz", "is", "not", "None", ":", "timezone", "=", "pyt...
Convert a string in ISO8601 form into a Datetime object. This is mainly used for converting timestamps sent from the TempoDB API, which are assumed to be correct. :param string t: the timestamp to convert :rtype: Datetime object
[ "Convert", "a", "string", "in", "ISO8601", "form", "into", "a", "Datetime", "object", ".", "This", "is", "mainly", "used", "for", "converting", "timestamps", "sent", "from", "the", "TempoDB", "API", "which", "are", "assumed", "to", "be", "correct", "." ]
train
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/temporal/validate.py#L29-L45
shaypal5/utilitime
utilitime/weekday/weekday.py
next_weekday
def next_weekday(weekday): """Returns the name of the weekday after the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: return WEEKDAYS[0] return WEEKDAYS[ix+1]
python
def next_weekday(weekday): """Returns the name of the weekday after the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: return WEEKDAYS[0] return WEEKDAYS[ix+1]
[ "def", "next_weekday", "(", "weekday", ")", ":", "ix", "=", "WEEKDAYS", ".", "index", "(", "weekday", ")", "if", "ix", "==", "len", "(", "WEEKDAYS", ")", "-", "1", ":", "return", "WEEKDAYS", "[", "0", "]", "return", "WEEKDAYS", "[", "ix", "+", "1",...
Returns the name of the weekday after the given weekday name.
[ "Returns", "the", "name", "of", "the", "weekday", "after", "the", "given", "weekday", "name", "." ]
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L12-L17
shaypal5/utilitime
utilitime/weekday/weekday.py
prev_weekday
def prev_weekday(weekday): """Returns the name of the weekday before the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == 0: return WEEKDAYS[len(WEEKDAYS)-1] return WEEKDAYS[ix-1]
python
def prev_weekday(weekday): """Returns the name of the weekday before the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == 0: return WEEKDAYS[len(WEEKDAYS)-1] return WEEKDAYS[ix-1]
[ "def", "prev_weekday", "(", "weekday", ")", ":", "ix", "=", "WEEKDAYS", ".", "index", "(", "weekday", ")", "if", "ix", "==", "0", ":", "return", "WEEKDAYS", "[", "len", "(", "WEEKDAYS", ")", "-", "1", "]", "return", "WEEKDAYS", "[", "ix", "-", "1",...
Returns the name of the weekday before the given weekday name.
[ "Returns", "the", "name", "of", "the", "weekday", "before", "the", "given", "weekday", "name", "." ]
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L20-L25
shaypal5/utilitime
utilitime/weekday/weekday.py
workdays
def workdays(first_day=None): """Returns a list of workday names. Arguments --------- first_day : str, default None The first day of the five-day work week. If not given, 'Monday' is used. Returns ------- list A list of workday names. """ if first_day is Non...
python
def workdays(first_day=None): """Returns a list of workday names. Arguments --------- first_day : str, default None The first day of the five-day work week. If not given, 'Monday' is used. Returns ------- list A list of workday names. """ if first_day is Non...
[ "def", "workdays", "(", "first_day", "=", "None", ")", ":", "if", "first_day", "is", "None", ":", "first_day", "=", "'Monday'", "ix", "=", "_lower_weekdays", "(", ")", ".", "index", "(", "first_day", ".", "lower", "(", ")", ")", "return", "_double_weekda...
Returns a list of workday names. Arguments --------- first_day : str, default None The first day of the five-day work week. If not given, 'Monday' is used. Returns ------- list A list of workday names.
[ "Returns", "a", "list", "of", "workday", "names", "." ]
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L38-L55
shaypal5/utilitime
utilitime/weekday/weekday.py
weekdays
def weekdays(first_day=None): """Returns a list of weekday names. Arguments --------- first_day : str, default None The first day of the week. If not given, 'Monday' is used. Returns ------- list A list of weekday names. """ if first_day is None: first_day =...
python
def weekdays(first_day=None): """Returns a list of weekday names. Arguments --------- first_day : str, default None The first day of the week. If not given, 'Monday' is used. Returns ------- list A list of weekday names. """ if first_day is None: first_day =...
[ "def", "weekdays", "(", "first_day", "=", "None", ")", ":", "if", "first_day", "is", "None", ":", "first_day", "=", "'Monday'", "ix", "=", "_lower_weekdays", "(", ")", ".", "index", "(", "first_day", ".", "lower", "(", ")", ")", "return", "_double_weekda...
Returns a list of weekday names. Arguments --------- first_day : str, default None The first day of the week. If not given, 'Monday' is used. Returns ------- list A list of weekday names.
[ "Returns", "a", "list", "of", "weekday", "names", "." ]
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L58-L74
jmgilman/Neolib
neolib/quests/KitchenQuest.py
KitchenQuest.getPrice
def getPrice(self, searches): """ Prices all quest items and returns result Searches the shop wizard x times (x being number given in searches) for each quest item and finds the lowest price for each item. Combines all item prices and sets KitchenQuest.npSpent to the final value...
python
def getPrice(self, searches): """ Prices all quest items and returns result Searches the shop wizard x times (x being number given in searches) for each quest item and finds the lowest price for each item. Combines all item prices and sets KitchenQuest.npSpent to the final value...
[ "def", "getPrice", "(", "self", ",", "searches", ")", ":", "totalPrice", "=", "0", "for", "item", "in", "self", ".", "items", ":", "res", "=", "ShopWizard", ".", "priceItem", "(", "self", ".", "usr", ",", "item", ".", "name", ",", "searches", ",", ...
Prices all quest items and returns result Searches the shop wizard x times (x being number given in searches) for each quest item and finds the lowest price for each item. Combines all item prices and sets KitchenQuest.npSpent to the final value. Returns whether or not this proc...
[ "Prices", "all", "quest", "items", "and", "returns", "result", "Searches", "the", "shop", "wizard", "x", "times", "(", "x", "being", "number", "given", "in", "searches", ")", "for", "each", "quest", "item", "and", "finds", "the", "lowest", "price", "for", ...
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/quests/KitchenQuest.py#L126-L153
jmgilman/Neolib
neolib/quests/KitchenQuest.py
KitchenQuest.buyQuestItems
def buyQuestItems(self): """ Attempts to buy all quest items, returns result Returns bool - True if successful, otherwise False """ for item in self.items: us = UserShopFront(self.usr, item.owner, item.id, str(item.price)) us.loadInventory()...
python
def buyQuestItems(self): """ Attempts to buy all quest items, returns result Returns bool - True if successful, otherwise False """ for item in self.items: us = UserShopFront(self.usr, item.owner, item.id, str(item.price)) us.loadInventory()...
[ "def", "buyQuestItems", "(", "self", ")", ":", "for", "item", "in", "self", ".", "items", ":", "us", "=", "UserShopFront", "(", "self", ".", "usr", ",", "item", ".", "owner", ",", "item", ".", "id", ",", "str", "(", "item", ".", "price", ")", ")"...
Attempts to buy all quest items, returns result Returns bool - True if successful, otherwise False
[ "Attempts", "to", "buy", "all", "quest", "items", "returns", "result", "Returns", "bool", "-", "True", "if", "successful", "otherwise", "False" ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/quests/KitchenQuest.py#L155-L171
jmgilman/Neolib
neolib/quests/KitchenQuest.py
KitchenQuest.submitQuest
def submitQuest(self): """ Submits the active quest, returns result Returns bool - True if successful, otherwise False """ form = pg.form(action="kitchen2.phtml") pg = form.submit() if "Woohoo" in pg.content: try: ...
python
def submitQuest(self): """ Submits the active quest, returns result Returns bool - True if successful, otherwise False """ form = pg.form(action="kitchen2.phtml") pg = form.submit() if "Woohoo" in pg.content: try: ...
[ "def", "submitQuest", "(", "self", ")", ":", "form", "=", "pg", ".", "form", "(", "action", "=", "\"kitchen2.phtml\"", ")", "pg", "=", "form", ".", "submit", "(", ")", "if", "\"Woohoo\"", "in", "pg", ".", "content", ":", "try", ":", "self", ".", "p...
Submits the active quest, returns result Returns bool - True if successful, otherwise False
[ "Submits", "the", "active", "quest", "returns", "result", "Returns", "bool", "-", "True", "if", "successful", "otherwise", "False" ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/quests/KitchenQuest.py#L173-L193
JHowell45/helium-cli
helium/__init__.py
youtube
def youtube(no_controls, no_autoplay, store, store_name, youtube_url): """Convert a Youtube URL so that works correctly with Helium. This command is used for converting the URL for a Youtube video that is part of a playlist so that Helium recognises it as a playlist and when the video ends it correctly...
python
def youtube(no_controls, no_autoplay, store, store_name, youtube_url): """Convert a Youtube URL so that works correctly with Helium. This command is used for converting the URL for a Youtube video that is part of a playlist so that Helium recognises it as a playlist and when the video ends it correctly...
[ "def", "youtube", "(", "no_controls", ",", "no_autoplay", ",", "store", ",", "store_name", ",", "youtube_url", ")", ":", "old_url_colour", "=", "'blue'", "new_url_colour", "=", "'green'", "echo", "(", "'Format --> {0}: {1}'", ".", "format", "(", "style", "(", ...
Convert a Youtube URL so that works correctly with Helium. This command is used for converting the URL for a Youtube video that is part of a playlist so that Helium recognises it as a playlist and when the video ends it correctly moves onto the next video in the playlist. :param youtube_url: the URL o...
[ "Convert", "a", "Youtube", "URL", "so", "that", "works", "correctly", "with", "Helium", "." ]
train
https://github.com/JHowell45/helium-cli/blob/8decc2f410a17314440eeed411a4b19dd4b4e780/helium/__init__.py#L53-L78
JHowell45/helium-cli
helium/__init__.py
list
def list(): """Use this function to display all of the stored URLs. This command is used for displaying all of the URLs and their names from the stored list. """ for name, url in get_all_data().items(): echo('{}: {}'.format( style(name, fg='blue'), style(url, fg='gre...
python
def list(): """Use this function to display all of the stored URLs. This command is used for displaying all of the URLs and their names from the stored list. """ for name, url in get_all_data().items(): echo('{}: {}'.format( style(name, fg='blue'), style(url, fg='gre...
[ "def", "list", "(", ")", ":", "for", "name", ",", "url", "in", "get_all_data", "(", ")", ".", "items", "(", ")", ":", "echo", "(", "'{}: {}'", ".", "format", "(", "style", "(", "name", ",", "fg", "=", "'blue'", ")", ",", "style", "(", "url", ",...
Use this function to display all of the stored URLs. This command is used for displaying all of the URLs and their names from the stored list.
[ "Use", "this", "function", "to", "display", "all", "of", "the", "stored", "URLs", "." ]
train
https://github.com/JHowell45/helium-cli/blob/8decc2f410a17314440eeed411a4b19dd4b4e780/helium/__init__.py#L94-L104
anti1869/sunhead
src/sunhead/utils.py
get_class_by_path
def get_class_by_path(class_path: str, is_module: Optional[bool] = False) -> type: """ Get class by its name within a package structure. :param class_path: E.g. brandt.some.module.ClassName :param is_module: Whether last item is module rather than class name :return: Class ready to be instantiated....
python
def get_class_by_path(class_path: str, is_module: Optional[bool] = False) -> type: """ Get class by its name within a package structure. :param class_path: E.g. brandt.some.module.ClassName :param is_module: Whether last item is module rather than class name :return: Class ready to be instantiated....
[ "def", "get_class_by_path", "(", "class_path", ":", "str", ",", "is_module", ":", "Optional", "[", "bool", "]", "=", "False", ")", "->", "type", ":", "if", "is_module", ":", "try", ":", "backend_module", "=", "importlib", ".", "import_module", "(", "class_...
Get class by its name within a package structure. :param class_path: E.g. brandt.some.module.ClassName :param is_module: Whether last item is module rather than class name :return: Class ready to be instantiated.
[ "Get", "class", "by", "its", "name", "within", "a", "package", "structure", "." ]
train
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L26-L58
anti1869/sunhead
src/sunhead/utils.py
get_submodule_list
def get_submodule_list(package_path: str) -> Tuple[ModuleDescription, ...]: """Get list of submodules for some package by its path. E.g ``pkg.subpackage``""" pkg = importlib.import_module(package_path) subs = ( ModuleDescription( name=modname, path="{}.{}".format(package_pat...
python
def get_submodule_list(package_path: str) -> Tuple[ModuleDescription, ...]: """Get list of submodules for some package by its path. E.g ``pkg.subpackage``""" pkg = importlib.import_module(package_path) subs = ( ModuleDescription( name=modname, path="{}.{}".format(package_pat...
[ "def", "get_submodule_list", "(", "package_path", ":", "str", ")", "->", "Tuple", "[", "ModuleDescription", ",", "...", "]", ":", "pkg", "=", "importlib", ".", "import_module", "(", "package_path", ")", "subs", "=", "(", "ModuleDescription", "(", "name", "="...
Get list of submodules for some package by its path. E.g ``pkg.subpackage``
[ "Get", "list", "of", "submodules", "for", "some", "package", "by", "its", "path", ".", "E", ".", "g", "pkg", ".", "subpackage" ]
train
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L61-L73
anti1869/sunhead
src/sunhead/utils.py
parallel_results
async def parallel_results(future_map: Sequence[Tuple]) -> Dict: """ Run parallel execution of futures and return mapping of their results to the provided keys. Just a neat shortcut around ``asyncio.gather()`` :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_conten...
python
async def parallel_results(future_map: Sequence[Tuple]) -> Dict: """ Run parallel execution of futures and return mapping of their results to the provided keys. Just a neat shortcut around ``asyncio.gather()`` :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_conten...
[ "async", "def", "parallel_results", "(", "future_map", ":", "Sequence", "[", "Tuple", "]", ")", "->", "Dict", ":", "ctx_methods", "=", "OrderedDict", "(", "future_map", ")", "fs", "=", "list", "(", "ctx_methods", ".", "values", "(", ")", ")", "results", ...
Run parallel execution of futures and return mapping of their results to the provided keys. Just a neat shortcut around ``asyncio.gather()`` :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) ) :return: Dict with futures results mapped to keys {'nav': {1:2}, '...
[ "Run", "parallel", "execution", "of", "futures", "and", "return", "mapping", "of", "their", "results", "to", "the", "provided", "keys", ".", "Just", "a", "neat", "shortcut", "around", "asyncio", ".", "gather", "()" ]
train
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L99-L113
anti1869/sunhead
src/sunhead/utils.py
positive_int
def positive_int(integer_string: str, strict: bool = False, cutoff: Optional[int] = None) -> int: """ Cast a string to a strictly positive integer. """ ret = int(integer_string) if ret < 0 or (ret == 0 and strict): raise ValueError() if cutoff: ret = min(ret, cutoff) return r...
python
def positive_int(integer_string: str, strict: bool = False, cutoff: Optional[int] = None) -> int: """ Cast a string to a strictly positive integer. """ ret = int(integer_string) if ret < 0 or (ret == 0 and strict): raise ValueError() if cutoff: ret = min(ret, cutoff) return r...
[ "def", "positive_int", "(", "integer_string", ":", "str", ",", "strict", ":", "bool", "=", "False", ",", "cutoff", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "int", ":", "ret", "=", "int", "(", "integer_string", ")", "if", "ret", "<", ...
Cast a string to a strictly positive integer.
[ "Cast", "a", "string", "to", "a", "strictly", "positive", "integer", "." ]
train
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L116-L125
anti1869/sunhead
src/sunhead/utils.py
choices_from_enum
def choices_from_enum(source: Enum) -> Tuple[Tuple[Any, str], ...]: """ Makes tuple to use in Django's Fields ``choices`` attribute. Enum members names will be titles for the choices. :param source: Enum to process. :return: Tuple to put into ``choices`` """ result = tuple((s.value, s.name....
python
def choices_from_enum(source: Enum) -> Tuple[Tuple[Any, str], ...]: """ Makes tuple to use in Django's Fields ``choices`` attribute. Enum members names will be titles for the choices. :param source: Enum to process. :return: Tuple to put into ``choices`` """ result = tuple((s.value, s.name....
[ "def", "choices_from_enum", "(", "source", ":", "Enum", ")", "->", "Tuple", "[", "Tuple", "[", "Any", ",", "str", "]", ",", "...", "]", ":", "result", "=", "tuple", "(", "(", "s", ".", "value", ",", "s", ".", "name", ".", "title", "(", ")", ")"...
Makes tuple to use in Django's Fields ``choices`` attribute. Enum members names will be titles for the choices. :param source: Enum to process. :return: Tuple to put into ``choices``
[ "Makes", "tuple", "to", "use", "in", "Django", "s", "Fields", "choices", "attribute", ".", "Enum", "members", "names", "will", "be", "titles", "for", "the", "choices", "." ]
train
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L135-L144
EventTeam/beliefs
src/beliefs/cells/dicts.py
DictCell.contains
def contains(self, key_or_keypath): """ Allows the 'in' operator to work for checking if a particular key (or keypath) is inside the dictionary. """ if isinstance(key_or_keypath, list): if len(key_or_keypath) == 0: # empty list is root return False ...
python
def contains(self, key_or_keypath): """ Allows the 'in' operator to work for checking if a particular key (or keypath) is inside the dictionary. """ if isinstance(key_or_keypath, list): if len(key_or_keypath) == 0: # empty list is root return False ...
[ "def", "contains", "(", "self", ",", "key_or_keypath", ")", ":", "if", "isinstance", "(", "key_or_keypath", ",", "list", ")", ":", "if", "len", "(", "key_or_keypath", ")", "==", "0", ":", "# empty list is root", "return", "False", "val", "=", "self", "next...
Allows the 'in' operator to work for checking if a particular key (or keypath) is inside the dictionary.
[ "Allows", "the", "in", "operator", "to", "work", "for", "checking", "if", "a", "particular", "key", "(", "or", "keypath", ")", "is", "inside", "the", "dictionary", "." ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/dicts.py#L78-L94
EventTeam/beliefs
src/beliefs/cells/dicts.py
DictCell.get_value_from_path
def get_value_from_path(self, keypath): """ Returns the value at the end of keypath (or None) keypath is a list of keys, e.g., ["key", "subkey", "subsubkey"] """ if isinstance(keypath, list): if len(keypath) == 0: # empty list is root r...
python
def get_value_from_path(self, keypath): """ Returns the value at the end of keypath (or None) keypath is a list of keys, e.g., ["key", "subkey", "subsubkey"] """ if isinstance(keypath, list): if len(keypath) == 0: # empty list is root r...
[ "def", "get_value_from_path", "(", "self", ",", "keypath", ")", ":", "if", "isinstance", "(", "keypath", ",", "list", ")", ":", "if", "len", "(", "keypath", ")", "==", "0", ":", "# empty list is root", "return", "val", "=", "self", "for", "next_key", "in...
Returns the value at the end of keypath (or None) keypath is a list of keys, e.g., ["key", "subkey", "subsubkey"]
[ "Returns", "the", "value", "at", "the", "end", "of", "keypath", "(", "or", "None", ")", "keypath", "is", "a", "list", "of", "keys", "e", ".", "g", ".", "[", "key", "subkey", "subsubkey", "]" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/dicts.py#L96-L110
EventTeam/beliefs
src/beliefs/cells/dicts.py
DictCell.is_entailed_by
def is_entailed_by(self, other): """ Whether all of self's keys (and values) are in (and within) other's """ for (s_key, s_val) in self: if s_key in other: if not other[s_key].entails(s_val): return False else: r...
python
def is_entailed_by(self, other): """ Whether all of self's keys (and values) are in (and within) other's """ for (s_key, s_val) in self: if s_key in other: if not other[s_key].entails(s_val): return False else: r...
[ "def", "is_entailed_by", "(", "self", ",", "other", ")", ":", "for", "(", "s_key", ",", "s_val", ")", "in", "self", ":", "if", "s_key", "in", "other", ":", "if", "not", "other", "[", "s_key", "]", ".", "entails", "(", "s_val", ")", ":", "return", ...
Whether all of self's keys (and values) are in (and within) other's
[ "Whether", "all", "of", "self", "s", "keys", "(", "and", "values", ")", "are", "in", "(", "and", "within", ")", "other", "s" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/dicts.py#L112-L122
EventTeam/beliefs
src/beliefs/cells/dicts.py
DictCell.is_contradictory
def is_contradictory(self, other): """ Returns True if the two DictCells are unmergeable. """ if not isinstance(other, DictCell): raise Exception("Incomparable") for key, val in self: if key in other.__dict__['p'] \ and val.is_contradictory(other.__di...
python
def is_contradictory(self, other): """ Returns True if the two DictCells are unmergeable. """ if not isinstance(other, DictCell): raise Exception("Incomparable") for key, val in self: if key in other.__dict__['p'] \ and val.is_contradictory(other.__di...
[ "def", "is_contradictory", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "DictCell", ")", ":", "raise", "Exception", "(", "\"Incomparable\"", ")", "for", "key", ",", "val", "in", "self", ":", "if", "key", "in", "oth...
Returns True if the two DictCells are unmergeable.
[ "Returns", "True", "if", "the", "two", "DictCells", "are", "unmergeable", "." ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/dicts.py#L132-L140
EventTeam/beliefs
src/beliefs/cells/dicts.py
DictCell.is_equal
def is_equal(self, other): """ Two DictCells are equal when they share ALL Keys, and all of their is_equal() methods return True. This ensures substructure equality. """ if not isinstance(other, DictCell): return False for (this, that) in itertools.izip_longest(sel...
python
def is_equal(self, other): """ Two DictCells are equal when they share ALL Keys, and all of their is_equal() methods return True. This ensures substructure equality. """ if not isinstance(other, DictCell): return False for (this, that) in itertools.izip_longest(sel...
[ "def", "is_equal", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "DictCell", ")", ":", "return", "False", "for", "(", "this", ",", "that", ")", "in", "itertools", ".", "izip_longest", "(", "self", ",", "other", ")...
Two DictCells are equal when they share ALL Keys, and all of their is_equal() methods return True. This ensures substructure equality.
[ "Two", "DictCells", "are", "equal", "when", "they", "share", "ALL", "Keys", "and", "all", "of", "their", "is_equal", "()", "methods", "return", "True", ".", "This", "ensures", "substructure", "equality", "." ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/dicts.py#L142-L155
EventTeam/beliefs
src/beliefs/cells/dicts.py
DictCell.merge
def merge(self, other): """ Merges two complex structures (by recursively merging their parts). Missing-parts do not trigger contradictions. """ if not isinstance(other, DictCell): raise Exception("Incomparable") if self.is_equal(other): # pick amo...
python
def merge(self, other): """ Merges two complex structures (by recursively merging their parts). Missing-parts do not trigger contradictions. """ if not isinstance(other, DictCell): raise Exception("Incomparable") if self.is_equal(other): # pick amo...
[ "def", "merge", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "DictCell", ")", ":", "raise", "Exception", "(", "\"Incomparable\"", ")", "if", "self", ".", "is_equal", "(", "other", ")", ":", "# pick among dependencies",...
Merges two complex structures (by recursively merging their parts). Missing-parts do not trigger contradictions.
[ "Merges", "two", "complex", "structures", "(", "by", "recursively", "merging", "their", "parts", ")", ".", "Missing", "-", "parts", "do", "not", "trigger", "contradictions", "." ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/dicts.py#L171-L194
EventTeam/beliefs
src/beliefs/cells/dicts.py
DictCell.to_dict
def to_dict(self): """ This method converts the DictCell into a python `dict`. This is useful for JSON serialization. """ output = {} for key, value in self.__dict__['p'].iteritems(): if value is None or isinstance(value, SIMPLE_TYPES): output...
python
def to_dict(self): """ This method converts the DictCell into a python `dict`. This is useful for JSON serialization. """ output = {} for key, value in self.__dict__['p'].iteritems(): if value is None or isinstance(value, SIMPLE_TYPES): output...
[ "def", "to_dict", "(", "self", ")", ":", "output", "=", "{", "}", "for", "key", ",", "value", "in", "self", ".", "__dict__", "[", "'p'", "]", ".", "iteritems", "(", ")", ":", "if", "value", "is", "None", "or", "isinstance", "(", "value", ",", "SI...
This method converts the DictCell into a python `dict`. This is useful for JSON serialization.
[ "This", "method", "converts", "the", "DictCell", "into", "a", "python", "dict", ".", "This", "is", "useful", "for", "JSON", "serialization", "." ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/dicts.py#L209-L232
EventTeam/beliefs
src/beliefs/cells/dicts.py
DictCell.to_latex
def to_latex(self): """ Returns a LaTeX representation of an attribute-value matrix """ latex = r"[{} " for attribute, value in self: if attribute in ['speaker_model', 'is_in_commonground']: continue value_l = value.to_latex() if value_l == "": continue ...
python
def to_latex(self): """ Returns a LaTeX representation of an attribute-value matrix """ latex = r"[{} " for attribute, value in self: if attribute in ['speaker_model', 'is_in_commonground']: continue value_l = value.to_latex() if value_l == "": continue ...
[ "def", "to_latex", "(", "self", ")", ":", "latex", "=", "r\"[{} \"", "for", "attribute", ",", "value", "in", "self", ":", "if", "attribute", "in", "[", "'speaker_model'", ",", "'is_in_commonground'", "]", ":", "continue", "value_l", "=", "value", ".", "to_...
Returns a LaTeX representation of an attribute-value matrix
[ "Returns", "a", "LaTeX", "representation", "of", "an", "attribute", "-", "value", "matrix" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/dicts.py#L234-L243
samirelanduk/quickplots
quickplots/quick.py
line
def line(*args, **kwargs): """This function creates a line chart. Specifcally it creates an :py:class:`.AxisChart` and then adds a :py:class:`.LineSeries` to it. :param \*data: The data for the line series as either (x,y) values or two\ big tuples/lists of x and y values respectively. :param str na...
python
def line(*args, **kwargs): """This function creates a line chart. Specifcally it creates an :py:class:`.AxisChart` and then adds a :py:class:`.LineSeries` to it. :param \*data: The data for the line series as either (x,y) values or two\ big tuples/lists of x and y values respectively. :param str na...
[ "def", "line", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "line_series_kwargs", "=", "{", "}", "for", "kwarg", "in", "(", "\"name\"", ",", "\"color\"", ",", "\"linestyle\"", ",", "\"linewidth\"", ")", ":", "if", "kwarg", "in", "kwargs", ":", ...
This function creates a line chart. Specifcally it creates an :py:class:`.AxisChart` and then adds a :py:class:`.LineSeries` to it. :param \*data: The data for the line series as either (x,y) values or two\ big tuples/lists of x and y values respectively. :param str name: The name to be associated with...
[ "This", "function", "creates", "a", "line", "chart", ".", "Specifcally", "it", "creates", "an", ":", "py", ":", "class", ":", ".", "AxisChart", "and", "then", "adds", "a", ":", "py", ":", "class", ":", ".", "LineSeries", "to", "it", "." ]
train
https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/quick.py#L5-L36
samirelanduk/quickplots
quickplots/quick.py
scatter
def scatter(*args, **kwargs): """This function creates a scatter chart. Specifcally it creates an :py:class:`.AxisChart` and then adds a :py:class:`.ScatterSeries` to it. :param \*data: The data for the scatter series as either (x,y) values or two\ big tuples/lists of x and y values respectively. :...
python
def scatter(*args, **kwargs): """This function creates a scatter chart. Specifcally it creates an :py:class:`.AxisChart` and then adds a :py:class:`.ScatterSeries` to it. :param \*data: The data for the scatter series as either (x,y) values or two\ big tuples/lists of x and y values respectively. :...
[ "def", "scatter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "scatter_series_kwargs", "=", "{", "}", "for", "kwarg", "in", "(", "\"name\"", ",", "\"color\"", ",", "\"size\"", ",", "\"linewidth\"", ")", ":", "if", "kwarg", "in", "kwargs", ":",...
This function creates a scatter chart. Specifcally it creates an :py:class:`.AxisChart` and then adds a :py:class:`.ScatterSeries` to it. :param \*data: The data for the scatter series as either (x,y) values or two\ big tuples/lists of x and y values respectively. :param str name: The name to be associ...
[ "This", "function", "creates", "a", "scatter", "chart", ".", "Specifcally", "it", "creates", "an", ":", "py", ":", "class", ":", ".", "AxisChart", "and", "then", "adds", "a", ":", "py", ":", "class", ":", ".", "ScatterSeries", "to", "it", "." ]
train
https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/quick.py#L39-L68
alexhayes/django-toolkit
django_toolkit/date_util.py
start_of_month
def start_of_month(d, d_years=0, d_months=0): """ Given a date, return a date first day of the month. @param d: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to apply to date. @see http://co...
python
def start_of_month(d, d_years=0, d_months=0): """ Given a date, return a date first day of the month. @param d: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to apply to date. @see http://co...
[ "def", "start_of_month", "(", "d", ",", "d_years", "=", "0", ",", "d_months", "=", "0", ")", ":", "y", ",", "m", "=", "d", ".", "year", "+", "d_years", ",", "d", ".", "month", "+", "d_months", "a", ",", "m", "=", "divmod", "(", "m", "-", "1",...
Given a date, return a date first day of the month. @param d: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to apply to date. @see http://code.activestate.com/recipes/476197-first-last-day-of-the-mo...
[ "Given", "a", "date", "return", "a", "date", "first", "day", "of", "the", "month", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/date_util.py#L11-L23
alexhayes/django-toolkit
django_toolkit/date_util.py
business_days
def business_days(start, stop): """ Return business days between two inclusive dates - ignoring public holidays. Note that start must be less than stop or else 0 is returned. @param start: Start date @param stop: Stop date @return int """ dates=rrule.rruleset() # Get dates ...
python
def business_days(start, stop): """ Return business days between two inclusive dates - ignoring public holidays. Note that start must be less than stop or else 0 is returned. @param start: Start date @param stop: Stop date @return int """ dates=rrule.rruleset() # Get dates ...
[ "def", "business_days", "(", "start", ",", "stop", ")", ":", "dates", "=", "rrule", ".", "rruleset", "(", ")", "# Get dates between start/stop (which are inclusive)", "dates", ".", "rrule", "(", "rrule", ".", "rrule", "(", "rrule", ".", "DAILY", ",", "dtstart"...
Return business days between two inclusive dates - ignoring public holidays. Note that start must be less than stop or else 0 is returned. @param start: Start date @param stop: Stop date @return int
[ "Return", "business", "days", "between", "two", "inclusive", "dates", "-", "ignoring", "public", "holidays", ".", "Note", "that", "start", "must", "be", "less", "than", "stop", "or", "else", "0", "is", "returned", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/date_util.py#L33-L48
alexhayes/django-toolkit
django_toolkit/date_util.py
days
def days(start, stop): """ Return days between start & stop (inclusive) Note that start must be less than stop or else 0 is returned. @param start: Start date @param stop: Stop date @return int """ dates=rrule.rruleset() # Get dates between start/stop (which are inclusive) ...
python
def days(start, stop): """ Return days between start & stop (inclusive) Note that start must be less than stop or else 0 is returned. @param start: Start date @param stop: Stop date @return int """ dates=rrule.rruleset() # Get dates between start/stop (which are inclusive) ...
[ "def", "days", "(", "start", ",", "stop", ")", ":", "dates", "=", "rrule", ".", "rruleset", "(", ")", "# Get dates between start/stop (which are inclusive)", "dates", ".", "rrule", "(", "rrule", ".", "rrule", "(", "rrule", ".", "DAILY", ",", "dtstart", "=", ...
Return days between start & stop (inclusive) Note that start must be less than stop or else 0 is returned. @param start: Start date @param stop: Stop date @return int
[ "Return", "days", "between", "start", "&", "stop", "(", "inclusive", ")", "Note", "that", "start", "must", "be", "less", "than", "stop", "or", "else", "0", "is", "returned", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/date_util.py#L50-L63
alexhayes/django-toolkit
django_toolkit/date_util.py
get_anniversary_periods
def get_anniversary_periods(start, finish, anniversary=1): """ Return a list of anniversaries periods between start and finish. """ import sys current = start periods = [] while current <= finish: (period_start, period_finish) = date_period(DATE_FREQUENCY_MONTHLY, anniversary, curre...
python
def get_anniversary_periods(start, finish, anniversary=1): """ Return a list of anniversaries periods between start and finish. """ import sys current = start periods = [] while current <= finish: (period_start, period_finish) = date_period(DATE_FREQUENCY_MONTHLY, anniversary, curre...
[ "def", "get_anniversary_periods", "(", "start", ",", "finish", ",", "anniversary", "=", "1", ")", ":", "import", "sys", "current", "=", "start", "periods", "=", "[", "]", "while", "current", "<=", "finish", ":", "(", "period_start", ",", "period_finish", "...
Return a list of anniversaries periods between start and finish.
[ "Return", "a", "list", "of", "anniversaries", "periods", "between", "start", "and", "finish", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/date_util.py#L68-L81
alexhayes/django-toolkit
django_toolkit/date_util.py
date_period
def date_period(frequency, anniversary, now=None): """ Retrieve a date period given a day of month. For example, if the period is month:15 and now is equal to 2012-11-22 then this method will return the following: (date(2012, 11, 15), date(2012, 12, 14)) Other examples: ...
python
def date_period(frequency, anniversary, now=None): """ Retrieve a date period given a day of month. For example, if the period is month:15 and now is equal to 2012-11-22 then this method will return the following: (date(2012, 11, 15), date(2012, 12, 14)) Other examples: ...
[ "def", "date_period", "(", "frequency", ",", "anniversary", ",", "now", "=", "None", ")", ":", "if", "frequency", "!=", "DATE_FREQUENCY_MONTHLY", ":", "raise", "DateFrequencyError", "(", "\"Only monthly date frequency is supported - not '%s'\"", "%", "(", "frequency", ...
Retrieve a date period given a day of month. For example, if the period is month:15 and now is equal to 2012-11-22 then this method will return the following: (date(2012, 11, 15), date(2012, 12, 14)) Other examples: monthly:1 with now 2012-12-1 would return: (date(2012, 11, 1...
[ "Retrieve", "a", "date", "period", "given", "a", "day", "of", "month", ".", "For", "example", "if", "the", "period", "is", "month", ":", "15", "and", "now", "is", "equal", "to", "2012", "-", "11", "-", "22", "then", "this", "method", "will", "return"...
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/date_util.py#L83-L116
alexhayes/django-toolkit
django_toolkit/date_util.py
exact_anniversaries
def exact_anniversaries(frequency, anniversary, start, finish): """ Returns the number of exact anniversaries if start and finish represent an anniversary. ie.. exact_anniversaries(DATE_FREQUENCY_MONTHLY, 10, date(2012, 2, 10), date(2012, 3, 9)) returns 1 exact_anniversaries(DATE_FREQUENC...
python
def exact_anniversaries(frequency, anniversary, start, finish): """ Returns the number of exact anniversaries if start and finish represent an anniversary. ie.. exact_anniversaries(DATE_FREQUENCY_MONTHLY, 10, date(2012, 2, 10), date(2012, 3, 9)) returns 1 exact_anniversaries(DATE_FREQUENC...
[ "def", "exact_anniversaries", "(", "frequency", ",", "anniversary", ",", "start", ",", "finish", ")", ":", "if", "frequency", "!=", "DATE_FREQUENCY_MONTHLY", ":", "raise", "DateFrequencyError", "(", "\"Only monthly date frequency is supported - not '%s'\"", "%", "(", "f...
Returns the number of exact anniversaries if start and finish represent an anniversary. ie.. exact_anniversaries(DATE_FREQUENCY_MONTHLY, 10, date(2012, 2, 10), date(2012, 3, 9)) returns 1 exact_anniversaries(DATE_FREQUENCY_MONTHLY, 10, date(2012, 2, 10), date(2012, 4, 9)) returns 2
[ "Returns", "the", "number", "of", "exact", "anniversaries", "if", "start", "and", "finish", "represent", "an", "anniversary", ".", "ie", "..", "exact_anniversaries", "(", "DATE_FREQUENCY_MONTHLY", "10", "date", "(", "2012", "2", "10", ")", "date", "(", "2012",...
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/date_util.py#L140-L164
alexhayes/django-toolkit
django_toolkit/date_util.py
quarter
def quarter(d): """ Return start/stop datetime for the quarter as defined by dt. """ from django_toolkit.datetime_util import quarter as datetime_quarter first_date, last_date = datetime_quarter(datetime(d.year, d.month, d.day)) return first_date.date(), last_date.date()
python
def quarter(d): """ Return start/stop datetime for the quarter as defined by dt. """ from django_toolkit.datetime_util import quarter as datetime_quarter first_date, last_date = datetime_quarter(datetime(d.year, d.month, d.day)) return first_date.date(), last_date.date()
[ "def", "quarter", "(", "d", ")", ":", "from", "django_toolkit", ".", "datetime_util", "import", "quarter", "as", "datetime_quarter", "first_date", ",", "last_date", "=", "datetime_quarter", "(", "datetime", "(", "d", ".", "year", ",", "d", ".", "month", ",",...
Return start/stop datetime for the quarter as defined by dt.
[ "Return", "start", "/", "stop", "datetime", "for", "the", "quarter", "as", "defined", "by", "dt", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/date_util.py#L166-L172
alexhayes/django-toolkit
django_toolkit/date_util.py
previous_quarter
def previous_quarter(d): """ Retrieve the previous quarter for dt """ from django_toolkit.datetime_util import quarter as datetime_quarter return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )
python
def previous_quarter(d): """ Retrieve the previous quarter for dt """ from django_toolkit.datetime_util import quarter as datetime_quarter return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )
[ "def", "previous_quarter", "(", "d", ")", ":", "from", "django_toolkit", ".", "datetime_util", "import", "quarter", "as", "datetime_quarter", "return", "quarter", "(", "(", "datetime_quarter", "(", "datetime", "(", "d", ".", "year", ",", "d", ".", "month", "...
Retrieve the previous quarter for dt
[ "Retrieve", "the", "previous", "quarter", "for", "dt" ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/date_util.py#L174-L179
miquelo/resort
packages/resort/component/postgresql.py
Connection.execute
def execute(self, script): """ Execute script. :param str script: Script to be executed. """ try: conn = self.__connect() conn.cursor().execute(script) conn.commit() finally: conn.close()
python
def execute(self, script): """ Execute script. :param str script: Script to be executed. """ try: conn = self.__connect() conn.cursor().execute(script) conn.commit() finally: conn.close()
[ "def", "execute", "(", "self", ",", "script", ")", ":", "try", ":", "conn", "=", "self", ".", "__connect", "(", ")", "conn", ".", "cursor", "(", ")", ".", "execute", "(", "script", ")", "conn", ".", "commit", "(", ")", "finally", ":", "conn", "."...
Execute script. :param str script: Script to be executed.
[ "Execute", "script", ".", ":", "param", "str", "script", ":", "Script", "to", "be", "executed", "." ]
train
https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/component/postgresql.py#L58-L72
miquelo/resort
packages/resort/component/postgresql.py
DatabaseChanges.insert
def insert(self, context): """ Applies database changes. :param resort.engine.execution.Context context: Current execution context. """ script_path = context.resolve(self.__script_path) buf = io.StringIO() self.__preprocess(script_path, buf) buf.seek(0) self.__conn.execute(buf.read())
python
def insert(self, context): """ Applies database changes. :param resort.engine.execution.Context context: Current execution context. """ script_path = context.resolve(self.__script_path) buf = io.StringIO() self.__preprocess(script_path, buf) buf.seek(0) self.__conn.execute(buf.read())
[ "def", "insert", "(", "self", ",", "context", ")", ":", "script_path", "=", "context", ".", "resolve", "(", "self", ".", "__script_path", ")", "buf", "=", "io", ".", "StringIO", "(", ")", "self", ".", "__preprocess", "(", "script_path", ",", "buf", ")"...
Applies database changes. :param resort.engine.execution.Context context: Current execution context.
[ "Applies", "database", "changes", ".", ":", "param", "resort", ".", "engine", ".", "execution", ".", "Context", "context", ":", "Current", "execution", "context", "." ]
train
https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/component/postgresql.py#L131-L144
knagra/farnsworth
workshift/signals.py
create_workshift_profile
def create_workshift_profile(sender, instance, created, **kwargs): ''' Function to add a workshift profile for every User that is created. Parameters: instance is an of UserProfile that was just saved. ''' if instance.user.username == ANONYMOUS_USERNAME or \ instance.status != UserPro...
python
def create_workshift_profile(sender, instance, created, **kwargs): ''' Function to add a workshift profile for every User that is created. Parameters: instance is an of UserProfile that was just saved. ''' if instance.user.username == ANONYMOUS_USERNAME or \ instance.status != UserPro...
[ "def", "create_workshift_profile", "(", "sender", ",", "instance", ",", "created", ",", "*", "*", "kwargs", ")", ":", "if", "instance", ".", "user", ".", "username", "==", "ANONYMOUS_USERNAME", "or", "instance", ".", "status", "!=", "UserProfile", ".", "RESI...
Function to add a workshift profile for every User that is created. Parameters: instance is an of UserProfile that was just saved.
[ "Function", "to", "add", "a", "workshift", "profile", "for", "every", "User", "that", "is", "created", ".", "Parameters", ":", "instance", "is", "an", "of", "UserProfile", "that", "was", "just", "saved", "." ]
train
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/signals.py#L20-L43
knagra/farnsworth
workshift/signals.py
_check_field_changed
def _check_field_changed(instance, old_instance, field_name, update_fields=None): """ Examines update_fields and an attribute of an instance to determine if that attribute has changed prior to the instance being saved. Parameters ---------- field_name : str instance : object old_instanc...
python
def _check_field_changed(instance, old_instance, field_name, update_fields=None): """ Examines update_fields and an attribute of an instance to determine if that attribute has changed prior to the instance being saved. Parameters ---------- field_name : str instance : object old_instanc...
[ "def", "_check_field_changed", "(", "instance", ",", "old_instance", ",", "field_name", ",", "update_fields", "=", "None", ")", ":", "if", "update_fields", "is", "not", "None", "and", "field_name", "not", "in", "update_fields", ":", "return", "False", "return", ...
Examines update_fields and an attribute of an instance to determine if that attribute has changed prior to the instance being saved. Parameters ---------- field_name : str instance : object old_instance : object update_fields : list of str, optional
[ "Examines", "update_fields", "and", "an", "attribute", "of", "an", "instance", "to", "determine", "if", "that", "attribute", "has", "changed", "prior", "to", "the", "instance", "being", "saved", "." ]
train
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/signals.py#L116-L131
happy5214/competitions-match
competitions/match/default/SimpleMatch.py
SimpleMatch.play
def play(self): """Play the match. This match simulator iterates through two lists of random numbers 25 times, one for each team, comparing the numbers and awarding a point to the team with the higher number. The team with more points at the end of the lists wins and is recorded...
python
def play(self): """Play the match. This match simulator iterates through two lists of random numbers 25 times, one for each team, comparing the numbers and awarding a point to the team with the higher number. The team with more points at the end of the lists wins and is recorded...
[ "def", "play", "(", "self", ")", ":", "score1", "=", "0", "score2", "=", "0", "for", "__", "in", "range", "(", "25", ")", ":", "num1", "=", "random", ".", "randint", "(", "0", ",", "100", ")", "num2", "=", "random", ".", "randint", "(", "0", ...
Play the match. This match simulator iterates through two lists of random numbers 25 times, one for each team, comparing the numbers and awarding a point to the team with the higher number. The team with more points at the end of the lists wins and is recorded in the winner field. If th...
[ "Play", "the", "match", "." ]
train
https://github.com/happy5214/competitions-match/blob/0eb77af258d9207c9c3b952e49ce70c856e15588/competitions/match/default/SimpleMatch.py#L72-L107
erbriones/shapeshift
shapeshift/generic.py
create_logger
def create_logger(name, formatter=None, handler=None, level=None): """ Returns a new logger for the specified name. """ logger = logging.getLogger(name) #: remove existing handlers logger.handlers = [] #: use a standard out handler if handler is None: handler = logging.StreamHa...
python
def create_logger(name, formatter=None, handler=None, level=None): """ Returns a new logger for the specified name. """ logger = logging.getLogger(name) #: remove existing handlers logger.handlers = [] #: use a standard out handler if handler is None: handler = logging.StreamHa...
[ "def", "create_logger", "(", "name", ",", "formatter", "=", "None", ",", "handler", "=", "None", ",", "level", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "#: remove existing handlers", "logger", ".", "handlers", "=...
Returns a new logger for the specified name.
[ "Returns", "a", "new", "logger", "for", "the", "specified", "name", "." ]
train
https://github.com/erbriones/shapeshift/blob/f930cdc0d520b08238e0fc2c582458f341b87775/shapeshift/generic.py#L10-L34
uw-it-aca/uw-restclients-trumba
uw_trumba/calendars.py
_load_calendar
def _load_calendar(campus, resp_fragment, calendar_dict, parent): """ :return: a dictionary of {calenderid, TrumbaCalendar} None if error, {} if not exists """ for record in resp_fragment: if re.match(r'Internal Event Actions', record['Name']) or\ re.match(r'Migrated...
python
def _load_calendar(campus, resp_fragment, calendar_dict, parent): """ :return: a dictionary of {calenderid, TrumbaCalendar} None if error, {} if not exists """ for record in resp_fragment: if re.match(r'Internal Event Actions', record['Name']) or\ re.match(r'Migrated...
[ "def", "_load_calendar", "(", "campus", ",", "resp_fragment", ",", "calendar_dict", ",", "parent", ")", ":", "for", "record", "in", "resp_fragment", ":", "if", "re", ".", "match", "(", "r'Internal Event Actions'", ",", "record", "[", "'Name'", "]", ")", "or"...
:return: a dictionary of {calenderid, TrumbaCalendar} None if error, {} if not exists
[ ":", "return", ":", "a", "dictionary", "of", "{", "calenderid", "TrumbaCalendar", "}", "None", "if", "error", "{}", "if", "not", "exists" ]
train
https://github.com/uw-it-aca/uw-restclients-trumba/blob/49e739924c332f08128a32b73fb798d580b9eafd/uw_trumba/calendars.py#L172-L200
uw-it-aca/uw-restclients-trumba
uw_trumba/calendars.py
_load_permissions
def _load_permissions(campus, calendarid, resp_fragment, permission_list): """ :return: a list of sorted trumba.Permission objects None if error, [] if not exists """ for record in resp_fragment: if not _is_valid_email(record['Email']): # skip the non UW users ...
python
def _load_permissions(campus, calendarid, resp_fragment, permission_list): """ :return: a list of sorted trumba.Permission objects None if error, [] if not exists """ for record in resp_fragment: if not _is_valid_email(record['Email']): # skip the non UW users ...
[ "def", "_load_permissions", "(", "campus", ",", "calendarid", ",", "resp_fragment", ",", "permission_list", ")", ":", "for", "record", "in", "resp_fragment", ":", "if", "not", "_is_valid_email", "(", "record", "[", "'Email'", "]", ")", ":", "# skip the non UW us...
:return: a list of sorted trumba.Permission objects None if error, [] if not exists
[ ":", "return", ":", "a", "list", "of", "sorted", "trumba", ".", "Permission", "objects", "None", "if", "error", "[]", "if", "not", "exists" ]
train
https://github.com/uw-it-aca/uw-restclients-trumba/blob/49e739924c332f08128a32b73fb798d580b9eafd/uw_trumba/calendars.py#L230-L245
abe-winter/pg13-py
pg13/diff.py
splitpreserve
def splitpreserve(s,redelim=r'\s'): 'split, but preserves the delimiter so the string can be reassembled with double-spaces (etc) intact' pattern='[^%s]*%s*'%(redelim,redelim) return re.findall(pattern,s)
python
def splitpreserve(s,redelim=r'\s'): 'split, but preserves the delimiter so the string can be reassembled with double-spaces (etc) intact' pattern='[^%s]*%s*'%(redelim,redelim) return re.findall(pattern,s)
[ "def", "splitpreserve", "(", "s", ",", "redelim", "=", "r'\\s'", ")", ":", "pattern", "=", "'[^%s]*%s*'", "%", "(", "redelim", ",", "redelim", ")", "return", "re", ".", "findall", "(", "pattern", ",", "s", ")" ]
split, but preserves the delimiter so the string can be reassembled with double-spaces (etc) intact
[ "split", "but", "preserves", "the", "delimiter", "so", "the", "string", "can", "be", "reassembled", "with", "double", "-", "spaces", "(", "etc", ")", "intact" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/diff.py#L7-L10
abe-winter/pg13-py
pg13/diff.py
applydiff
def applydiff(tokens,deltas): "tokens can be a string or a list of strings.\ deltas is [Delta,...]. Delta.text is actually a tokenlist of the same type as tokens (string or list of string).\ If tokens & tokenslist are strings, must be unicode for the offsets to match what JS produces.\ (If they're lists, ...
python
def applydiff(tokens,deltas): "tokens can be a string or a list of strings.\ deltas is [Delta,...]. Delta.text is actually a tokenlist of the same type as tokens (string or list of string).\ If tokens & tokenslist are strings, must be unicode for the offsets to match what JS produces.\ (If they're lists, ...
[ "def", "applydiff", "(", "tokens", ",", "deltas", ")", ":", "sizechange", "=", "0", "for", "a", ",", "b", ",", "replace", "in", "deltas", ":", "tokens", "=", "tokens", "[", ":", "a", "+", "sizechange", "]", "+", "replace", "+", "tokens", "[", "b", ...
tokens can be a string or a list of strings.\ deltas is [Delta,...]. Delta.text is actually a tokenlist of the same type as tokens (string or list of string).\ If tokens & tokenslist are strings, must be unicode for the offsets to match what JS produces.\ (If they're lists, it doesn't matter; the offsets are...
[ "tokens", "can", "be", "a", "string", "or", "a", "list", "of", "strings", ".", "\\", "deltas", "is", "[", "Delta", "...", "]", ".", "Delta", ".", "text", "is", "actually", "a", "tokenlist", "of", "the", "same", "type", "as", "tokens", "(", "string", ...
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/diff.py#L12-L21
abe-winter/pg13-py
pg13/diff.py
splitstatus
def splitstatus(a,statusfn): 'split sequence into subsequences based on binary condition statusfn. a is a list, returns list of lists' groups=[]; mode=None for elt,status in zip(a,map(statusfn,a)): assert isinstance(status,bool) if status!=mode: mode=status; group=[mode]; groups.append(group) gr...
python
def splitstatus(a,statusfn): 'split sequence into subsequences based on binary condition statusfn. a is a list, returns list of lists' groups=[]; mode=None for elt,status in zip(a,map(statusfn,a)): assert isinstance(status,bool) if status!=mode: mode=status; group=[mode]; groups.append(group) gr...
[ "def", "splitstatus", "(", "a", ",", "statusfn", ")", ":", "groups", "=", "[", "]", "mode", "=", "None", "for", "elt", ",", "status", "in", "zip", "(", "a", ",", "map", "(", "statusfn", ",", "a", ")", ")", ":", "assert", "isinstance", "(", "statu...
split sequence into subsequences based on binary condition statusfn. a is a list, returns list of lists
[ "split", "sequence", "into", "subsequences", "based", "on", "binary", "condition", "statusfn", ".", "a", "is", "a", "list", "returns", "list", "of", "lists" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/diff.py#L28-L35
abe-winter/pg13-py
pg13/diff.py
seqingroups
def seqingroups(groups,seq): 'helper for contigsub. takes the list of lists returned by groupelts and an array to check.\ returns (groupindex,indexingroup,matchlen) of longest match or None if no match' if not (groups and seq): return None bestmatch=None,None,0 if any(len(g)<2 for g in groups): raise Val...
python
def seqingroups(groups,seq): 'helper for contigsub. takes the list of lists returned by groupelts and an array to check.\ returns (groupindex,indexingroup,matchlen) of longest match or None if no match' if not (groups and seq): return None bestmatch=None,None,0 if any(len(g)<2 for g in groups): raise Val...
[ "def", "seqingroups", "(", "groups", ",", "seq", ")", ":", "if", "not", "(", "groups", "and", "seq", ")", ":", "return", "None", "bestmatch", "=", "None", ",", "None", ",", "0", "if", "any", "(", "len", "(", "g", ")", "<", "2", "for", "g", "in"...
helper for contigsub. takes the list of lists returned by groupelts and an array to check.\ returns (groupindex,indexingroup,matchlen) of longest match or None if no match
[ "helper", "for", "contigsub", ".", "takes", "the", "list", "of", "lists", "returned", "by", "groupelts", "and", "an", "array", "to", "check", ".", "\\", "returns", "(", "groupindex", "indexingroup", "matchlen", ")", "of", "longest", "match", "or", "None", ...
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/diff.py#L42-L61
abe-winter/pg13-py
pg13/diff.py
ungroupslice
def ungroupslice(groups,gslice): 'this is a helper for contigsub.' 'coordinate transform: takes a match from seqingroups() and transforms to ungrouped coordinates' eltsbefore=0 for i in range(gslice[0]): eltsbefore+=len(groups[i])-1 x=eltsbefore+gslice[1]; return [x-1,x+gslice[2]-1]
python
def ungroupslice(groups,gslice): 'this is a helper for contigsub.' 'coordinate transform: takes a match from seqingroups() and transforms to ungrouped coordinates' eltsbefore=0 for i in range(gslice[0]): eltsbefore+=len(groups[i])-1 x=eltsbefore+gslice[1]; return [x-1,x+gslice[2]-1]
[ "def", "ungroupslice", "(", "groups", ",", "gslice", ")", ":", "'coordinate transform: takes a match from seqingroups() and transforms to ungrouped coordinates'", "eltsbefore", "=", "0", "for", "i", "in", "range", "(", "gslice", "[", "0", "]", ")", ":", "eltsbefore", ...
this is a helper for contigsub.
[ "this", "is", "a", "helper", "for", "contigsub", "." ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/diff.py#L63-L68
abe-winter/pg13-py
pg13/diff.py
contigsub
def contigsub(a,b): 'find longest common substring. return its slice coordinates (in a and b; see last line) or None if not found' 'a and b are token lists' common=commonelts(a,b); groupsa=groupelts(a,common); groupsb=groupelts(b,common) bestmatch=[None,None,0]; bslice=None for i in range(len(groupsb)): ...
python
def contigsub(a,b): 'find longest common substring. return its slice coordinates (in a and b; see last line) or None if not found' 'a and b are token lists' common=commonelts(a,b); groupsa=groupelts(a,common); groupsb=groupelts(b,common) bestmatch=[None,None,0]; bslice=None for i in range(len(groupsb)): ...
[ "def", "contigsub", "(", "a", ",", "b", ")", ":", "'a and b are token lists'", "common", "=", "commonelts", "(", "a", ",", "b", ")", "groupsa", "=", "groupelts", "(", "a", ",", "common", ")", "groupsb", "=", "groupelts", "(", "b", ",", "common", ")", ...
find longest common substring. return its slice coordinates (in a and b; see last line) or None if not found
[ "find", "longest", "common", "substring", ".", "return", "its", "slice", "coordinates", "(", "in", "a", "and", "b", ";", "see", "last", "line", ")", "or", "None", "if", "not", "found" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/diff.py#L70-L82