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
vilmibm/done
parsedatetime/parsedatetime_consts.py
_initConstants
def _initConstants(ptc): """ Create localized versions of the units, week and month names """ # build weekday offsets - yes, it assumes the Weekday and shortWeekday # lists are in the same order and Mon..Sun (Python style) ptc.WeekdayOffsets = {} o = 0 for key in ptc.Weekdays: ...
python
def _initConstants(ptc): """ Create localized versions of the units, week and month names """ # build weekday offsets - yes, it assumes the Weekday and shortWeekday # lists are in the same order and Mon..Sun (Python style) ptc.WeekdayOffsets = {} o = 0 for key in ptc.Weekdays: ...
[ "def", "_initConstants", "(", "ptc", ")", ":", "# build weekday offsets - yes, it assumes the Weekday and shortWeekday", "# lists are in the same order and Mon..Sun (Python style)", "ptc", ".", "WeekdayOffsets", "=", "{", "}", "o", "=", "0", "for", "key", "in", "ptc", ".", ...
Create localized versions of the units, week and month names
[ "Create", "localized", "versions", "of", "the", "units", "week", "and", "month", "names" ]
train
https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime_consts.py#L841-L869
vilmibm/done
parsedatetime/parsedatetime_consts.py
Constants.buildSources
def buildSources(self, sourceTime=None): """ Return a dictionary of date/time tuples based on the keys found in self.re_sources. The current time is used as the default and any specified item found in self.re_sources is inserted into the value and the generated dictionar...
python
def buildSources(self, sourceTime=None): """ Return a dictionary of date/time tuples based on the keys found in self.re_sources. The current time is used as the default and any specified item found in self.re_sources is inserted into the value and the generated dictionar...
[ "def", "buildSources", "(", "self", ",", "sourceTime", "=", "None", ")", ":", "if", "sourceTime", "is", "None", ":", "(", "yr", ",", "mth", ",", "dy", ",", "hr", ",", "mn", ",", "sec", ",", "wd", ",", "yd", ",", "isdst", ")", "=", "time", ".", ...
Return a dictionary of date/time tuples based on the keys found in self.re_sources. The current time is used as the default and any specified item found in self.re_sources is inserted into the value and the generated dictionary is returned.
[ "Return", "a", "dictionary", "of", "date", "/", "time", "tuples", "based", "on", "the", "keys", "found", "in", "self", ".", "re_sources", "." ]
train
https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime_consts.py#L1087-L1118
krinj/k-util
k_util/serializable.py
Serializable.write_to_file
def write_to_file(self, file_path: str) -> None: """ Serialize and write the data into a JSON file. """ data = self.encode() with open(file_path, "w") as f: json.dump(data, f, indent=1)
python
def write_to_file(self, file_path: str) -> None: """ Serialize and write the data into a JSON file. """ data = self.encode() with open(file_path, "w") as f: json.dump(data, f, indent=1)
[ "def", "write_to_file", "(", "self", ",", "file_path", ":", "str", ")", "->", "None", ":", "data", "=", "self", ".", "encode", "(", ")", "with", "open", "(", "file_path", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "...
Serialize and write the data into a JSON file.
[ "Serialize", "and", "write", "the", "data", "into", "a", "JSON", "file", "." ]
train
https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/serializable.py#L54-L58
krinj/k-util
k_util/serializable.py
Serializable.load_from_file
def load_from_file(cls, file_path: str): """ Read and reconstruct the data from a JSON file. """ with open(file_path, "r") as f: data = json.load(f) item = cls.decode(data=data) return item
python
def load_from_file(cls, file_path: str): """ Read and reconstruct the data from a JSON file. """ with open(file_path, "r") as f: data = json.load(f) item = cls.decode(data=data) return item
[ "def", "load_from_file", "(", "cls", ",", "file_path", ":", "str", ")", ":", "with", "open", "(", "file_path", ",", "\"r\"", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ")", "item", "=", "cls", ".", "decode", "(", "data", "="...
Read and reconstruct the data from a JSON file.
[ "Read", "and", "reconstruct", "the", "data", "from", "a", "JSON", "file", "." ]
train
https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/serializable.py#L61-L66
fr33jc/bang
bang/providers/bases.py
Provider.gen_component_name
def gen_component_name(self, basename, postfix_length=13): """ Creates a resource identifier with a random postfix. This is an attempt to minimize name collisions in provider namespaces. :param str basename: The string that will be prefixed with the stack name, and postfix...
python
def gen_component_name(self, basename, postfix_length=13): """ Creates a resource identifier with a random postfix. This is an attempt to minimize name collisions in provider namespaces. :param str basename: The string that will be prefixed with the stack name, and postfix...
[ "def", "gen_component_name", "(", "self", ",", "basename", ",", "postfix_length", "=", "13", ")", ":", "def", "newcname", "(", ")", ":", "postfix", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "_AWS_NAME_CHARS", ")", "for", "i", "in", "xr...
Creates a resource identifier with a random postfix. This is an attempt to minimize name collisions in provider namespaces. :param str basename: The string that will be prefixed with the stack name, and postfixed with some random string. :param int postfix_length: The length of ...
[ "Creates", "a", "resource", "identifier", "with", "a", "random", "postfix", ".", "This", "is", "an", "attempt", "to", "minimize", "name", "collisions", "in", "provider", "namespaces", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/bases.py#L32-L53
fr33jc/bang
bang/providers/bases.py
Provider.get_consul
def get_consul(self, resource_type): """ Returns an object that a :class:`~bang.deployers.deployer.Deployer` uses to control resources of :attr:`resource_type`. :param str service: Any of the resources defined in :mod:`bang.resources`. """ consul = self.CON...
python
def get_consul(self, resource_type): """ Returns an object that a :class:`~bang.deployers.deployer.Deployer` uses to control resources of :attr:`resource_type`. :param str service: Any of the resources defined in :mod:`bang.resources`. """ consul = self.CON...
[ "def", "get_consul", "(", "self", ",", "resource_type", ")", ":", "consul", "=", "self", ".", "CONSUL_MAP", ".", "get", "(", "resource_type", ")", "if", "consul", ":", "return", "consul", "(", "self", ")" ]
Returns an object that a :class:`~bang.deployers.deployer.Deployer` uses to control resources of :attr:`resource_type`. :param str service: Any of the resources defined in :mod:`bang.resources`.
[ "Returns", "an", "object", "that", "a", ":", "class", ":", "~bang", ".", "deployers", ".", "deployer", ".", "Deployer", "uses", "to", "control", "resources", "of", ":", "attr", ":", "resource_type", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/bases.py#L55-L66
political-memory/django-representatives
representatives/migrations/0020_rep_unique_slug_remove_remoteid.py
update_slugs
def update_slugs(apps, schema_editor): """ Include birthdate in slugs """ # Get model managers Representative = apps.get_model("representatives", "Representative") for rep in Representative.objects.all(): rep.slug = '%s-%s' % (rep.slug, rep.birth_date) rep.save()
python
def update_slugs(apps, schema_editor): """ Include birthdate in slugs """ # Get model managers Representative = apps.get_model("representatives", "Representative") for rep in Representative.objects.all(): rep.slug = '%s-%s' % (rep.slug, rep.birth_date) rep.save()
[ "def", "update_slugs", "(", "apps", ",", "schema_editor", ")", ":", "# Get model managers", "Representative", "=", "apps", ".", "get_model", "(", "\"representatives\"", ",", "\"Representative\"", ")", "for", "rep", "in", "Representative", ".", "objects", ".", "all...
Include birthdate in slugs
[ "Include", "birthdate", "in", "slugs" ]
train
https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/migrations/0020_rep_unique_slug_remove_remoteid.py#L9-L19
political-memory/django-representatives
representatives/migrations/0020_rep_unique_slug_remove_remoteid.py
create_parl_websites
def create_parl_websites(apps, schema_editor): """ Prepare for remote_id removal by creating WebSite entities from it. """ # Get model managers Representative = apps.get_model("representatives", "Representative") WebSite = apps.get_model("representatives", "WebSite") today = datetime.date....
python
def create_parl_websites(apps, schema_editor): """ Prepare for remote_id removal by creating WebSite entities from it. """ # Get model managers Representative = apps.get_model("representatives", "Representative") WebSite = apps.get_model("representatives", "WebSite") today = datetime.date....
[ "def", "create_parl_websites", "(", "apps", ",", "schema_editor", ")", ":", "# Get model managers", "Representative", "=", "apps", ".", "get_model", "(", "\"representatives\"", ",", "\"Representative\"", ")", "WebSite", "=", "apps", ".", "get_model", "(", "\"represe...
Prepare for remote_id removal by creating WebSite entities from it.
[ "Prepare", "for", "remote_id", "removal", "by", "creating", "WebSite", "entities", "from", "it", "." ]
train
https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/migrations/0020_rep_unique_slug_remove_remoteid.py#L22-L79
phenicle/cfgpy
cfgpy/tools.py
determine_file_extension_based_on_format
def determine_file_extension_based_on_format(format_specifier): """ returns file extension string """ if format_specifier == FMT_INI: return 'ini' if format_specifier == FMT_DELIMITED: return '' if format_specifier == FMT_XML: return 'xml' if format_specifier == FMT_JSON: return 'json' if format_specifier...
python
def determine_file_extension_based_on_format(format_specifier): """ returns file extension string """ if format_specifier == FMT_INI: return 'ini' if format_specifier == FMT_DELIMITED: return '' if format_specifier == FMT_XML: return 'xml' if format_specifier == FMT_JSON: return 'json' if format_specifier...
[ "def", "determine_file_extension_based_on_format", "(", "format_specifier", ")", ":", "if", "format_specifier", "==", "FMT_INI", ":", "return", "'ini'", "if", "format_specifier", "==", "FMT_DELIMITED", ":", "return", "''", "if", "format_specifier", "==", "FMT_XML", ":...
returns file extension string
[ "returns", "file", "extension", "string" ]
train
https://github.com/phenicle/cfgpy/blob/d53a9ad4c91cdcd774b59cf3b8c59096fdf29d20/cfgpy/tools.py#L19-L31
phenicle/cfgpy
cfgpy/tools.py
CfgPy.read_element_using_argtuple
def read_element_using_argtuple(self, argtuple): """ takes a tuple of keys returns node found in cfg_dict found by traversing cfg_dict by successive application of keys from element_path """ # doesn't support DELIMITED, only dict-based formats if self.format == FMT_DELIMITED: return None node = ...
python
def read_element_using_argtuple(self, argtuple): """ takes a tuple of keys returns node found in cfg_dict found by traversing cfg_dict by successive application of keys from element_path """ # doesn't support DELIMITED, only dict-based formats if self.format == FMT_DELIMITED: return None node = ...
[ "def", "read_element_using_argtuple", "(", "self", ",", "argtuple", ")", ":", "# doesn't support DELIMITED, only dict-based formats", "if", "self", ".", "format", "==", "FMT_DELIMITED", ":", "return", "None", "node", "=", "self", ".", "cfg_dict", "for", "key", "in",...
takes a tuple of keys returns node found in cfg_dict found by traversing cfg_dict by successive application of keys from element_path
[ "takes", "a", "tuple", "of", "keys", "returns", "node", "found", "in", "cfg_dict", "found", "by", "traversing", "cfg_dict", "by", "successive", "application", "of", "keys", "from", "element_path" ]
train
https://github.com/phenicle/cfgpy/blob/d53a9ad4c91cdcd774b59cf3b8c59096fdf29d20/cfgpy/tools.py#L144-L159
phenicle/cfgpy
cfgpy/tools.py
CfgPy.load
def load(self): """ this is a glorified switch/case """ if self.format == FMT_INI: if self.filepaths: return self.load_using_ini_format_explicitly() return self.load_using_ini_format_implicitly() elif self.format == FMT_DELIMITED: if self.filepaths: return self.load_using_delimited_format_e...
python
def load(self): """ this is a glorified switch/case """ if self.format == FMT_INI: if self.filepaths: return self.load_using_ini_format_explicitly() return self.load_using_ini_format_implicitly() elif self.format == FMT_DELIMITED: if self.filepaths: return self.load_using_delimited_format_e...
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "format", "==", "FMT_INI", ":", "if", "self", ".", "filepaths", ":", "return", "self", ".", "load_using_ini_format_explicitly", "(", ")", "return", "self", ".", "load_using_ini_format_implicitly", "(", ...
this is a glorified switch/case
[ "this", "is", "a", "glorified", "switch", "/", "case" ]
train
https://github.com/phenicle/cfgpy/blob/d53a9ad4c91cdcd774b59cf3b8c59096fdf29d20/cfgpy/tools.py#L456-L489
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
Outline.length_estimate
def length_estimate(self): ''' Calculates and estimated word count based on number of characters, locations, and arcs. For reference see: http://www.writingexcuses.com/2017/07/02/12-27-choosing-a-length/ ''' characters = self.characterinstance_set.filter( Q(ma...
python
def length_estimate(self): ''' Calculates and estimated word count based on number of characters, locations, and arcs. For reference see: http://www.writingexcuses.com/2017/07/02/12-27-choosing-a-length/ ''' characters = self.characterinstance_set.filter( Q(ma...
[ "def", "length_estimate", "(", "self", ")", ":", "characters", "=", "self", ".", "characterinstance_set", ".", "filter", "(", "Q", "(", "main_character", "=", "True", ")", "|", "Q", "(", "pov_character", "=", "True", ")", "|", "Q", "(", "protagonist", "=...
Calculates and estimated word count based on number of characters, locations, and arcs. For reference see: http://www.writingexcuses.com/2017/07/02/12-27-choosing-a-length/
[ "Calculates", "and", "estimated", "word", "count", "based", "on", "number", "of", "characters", "locations", "and", "arcs", ".", "For", "reference", "see", ":", "http", ":", "//", "www", ".", "writingexcuses", ".", "com", "/", "2017", "/", "07", "/", "02...
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L371-L385
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
Outline.create_arc
def create_arc(self, mace_type, name): ''' Creates the story arc and initial tree for that arc for the current outline. Returns the resulting Arc instance. ''' arc = Arc(mace_type=mace_type, outline=self, name=name) arc.save() milestone_count = arc.generat...
python
def create_arc(self, mace_type, name): ''' Creates the story arc and initial tree for that arc for the current outline. Returns the resulting Arc instance. ''' arc = Arc(mace_type=mace_type, outline=self, name=name) arc.save() milestone_count = arc.generat...
[ "def", "create_arc", "(", "self", ",", "mace_type", ",", "name", ")", ":", "arc", "=", "Arc", "(", "mace_type", "=", "mace_type", ",", "outline", "=", "self", ",", "name", "=", "name", ")", "arc", ".", "save", "(", ")", "milestone_count", "=", "arc",...
Creates the story arc and initial tree for that arc for the current outline. Returns the resulting Arc instance.
[ "Creates", "the", "story", "arc", "and", "initial", "tree", "for", "that", "arc", "for", "the", "current", "outline", ".", "Returns", "the", "resulting", "Arc", "instance", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L410-L423
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
Outline.validate_nesting
def validate_nesting(self): ''' Reviews the story tree and validates associated arc elements are nested appropriately. Returns a dict of errors. ''' error_dict = {} story_root = self.story_tree_root story_nodes = story_root.get_descendants().prefetch_related('arce...
python
def validate_nesting(self): ''' Reviews the story tree and validates associated arc elements are nested appropriately. Returns a dict of errors. ''' error_dict = {} story_root = self.story_tree_root story_nodes = story_root.get_descendants().prefetch_related('arce...
[ "def", "validate_nesting", "(", "self", ")", ":", "error_dict", "=", "{", "}", "story_root", "=", "self", ".", "story_tree_root", "story_nodes", "=", "story_root", ".", "get_descendants", "(", ")", ".", "prefetch_related", "(", "'arcelementnode_set'", ")", ".", ...
Reviews the story tree and validates associated arc elements are nested appropriately. Returns a dict of errors.
[ "Reviews", "the", "story", "tree", "and", "validates", "associated", "arc", "elements", "are", "nested", "appropriately", ".", "Returns", "a", "dict", "of", "errors", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L425-L551
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
Arc.generate_template_arc_tree
def generate_template_arc_tree(self): ''' Generate a seven point template in this arc. Arc must be empty. ''' arc_root = self.arc_root_node if not arc_root: arc_root = ArcElementNode.add_root( arc_element_type='root', description='root ...
python
def generate_template_arc_tree(self): ''' Generate a seven point template in this arc. Arc must be empty. ''' arc_root = self.arc_root_node if not arc_root: arc_root = ArcElementNode.add_root( arc_element_type='root', description='root ...
[ "def", "generate_template_arc_tree", "(", "self", ")", ":", "arc_root", "=", "self", ".", "arc_root_node", "if", "not", "arc_root", ":", "arc_root", "=", "ArcElementNode", ".", "add_root", "(", "arc_element_type", "=", "'root'", ",", "description", "=", "'root o...
Generate a seven point template in this arc. Arc must be empty.
[ "Generate", "a", "seven", "point", "template", "in", "this", "arc", ".", "Arc", "must", "be", "empty", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L602-L619
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
Arc.fetch_arc_errors
def fetch_arc_errors(self): ''' Evaluates the current tree of the arc and provides a list of errors that the user should correct. ''' error_list = [] hnode = self.validate_first_element() if hnode: error_list.append({'hook_error': hnode}) rnode...
python
def fetch_arc_errors(self): ''' Evaluates the current tree of the arc and provides a list of errors that the user should correct. ''' error_list = [] hnode = self.validate_first_element() if hnode: error_list.append({'hook_error': hnode}) rnode...
[ "def", "fetch_arc_errors", "(", "self", ")", ":", "error_list", "=", "[", "]", "hnode", "=", "self", ".", "validate_first_element", "(", ")", "if", "hnode", ":", "error_list", ".", "append", "(", "{", "'hook_error'", ":", "hnode", "}", ")", "rnode", "=",...
Evaluates the current tree of the arc and provides a list of errors that the user should correct.
[ "Evaluates", "the", "current", "tree", "of", "the", "arc", "and", "provides", "a", "list", "of", "errors", "that", "the", "user", "should", "correct", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L621-L640
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
Arc.validate_generations
def validate_generations(self): ''' Make sure that the descendent depth is valid. ''' nodes = self.arc_root_node.get_descendants() for node in nodes: logger.debug("Checking parent for node of type %s" % node.arc_element_type) parent = ArcElementNode.object...
python
def validate_generations(self): ''' Make sure that the descendent depth is valid. ''' nodes = self.arc_root_node.get_descendants() for node in nodes: logger.debug("Checking parent for node of type %s" % node.arc_element_type) parent = ArcElementNode.object...
[ "def", "validate_generations", "(", "self", ")", ":", "nodes", "=", "self", ".", "arc_root_node", ".", "get_descendants", "(", ")", "for", "node", "in", "nodes", ":", "logger", ".", "debug", "(", "\"Checking parent for node of type %s\"", "%", "node", ".", "ar...
Make sure that the descendent depth is valid.
[ "Make", "sure", "that", "the", "descendent", "depth", "is", "valid", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L660-L674
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
Arc.validate_milestones
def validate_milestones(self): ''' Reviews the arc element tree to ensure that milestones appear in the right order. ''' milestones = self.arc_root_node.get_children().filter(arc_element_type__contains='mile') current_cursor = 0 for mile in milestones: ...
python
def validate_milestones(self): ''' Reviews the arc element tree to ensure that milestones appear in the right order. ''' milestones = self.arc_root_node.get_children().filter(arc_element_type__contains='mile') current_cursor = 0 for mile in milestones: ...
[ "def", "validate_milestones", "(", "self", ")", ":", "milestones", "=", "self", ".", "arc_root_node", ".", "get_children", "(", ")", ".", "filter", "(", "arc_element_type__contains", "=", "'mile'", ")", "current_cursor", "=", "0", "for", "mile", "in", "milesto...
Reviews the arc element tree to ensure that milestones appear in the right order.
[ "Reviews", "the", "arc", "element", "tree", "to", "ensure", "that", "milestones", "appear", "in", "the", "right", "order", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L676-L688
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
ArcElementNode.add_child
def add_child(self, arc_element_type, description=None, story_element_node=None, **kwargs): ''' Overrides the default `treebeard` function, adding additional integrity checks. ''' if 'mile' in arc_element_type: if 'mile' in self.arc_element_type: raise ArcGene...
python
def add_child(self, arc_element_type, description=None, story_element_node=None, **kwargs): ''' Overrides the default `treebeard` function, adding additional integrity checks. ''' if 'mile' in arc_element_type: if 'mile' in self.arc_element_type: raise ArcGene...
[ "def", "add_child", "(", "self", ",", "arc_element_type", ",", "description", "=", "None", ",", "story_element_node", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'mile'", "in", "arc_element_type", ":", "if", "'mile'", "in", "self", ".", "arc_ele...
Overrides the default `treebeard` function, adding additional integrity checks.
[ "Overrides", "the", "default", "treebeard", "function", "adding", "additional", "integrity", "checks", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L740-L759
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
ArcElementNode.add_sibling
def add_sibling(self, pos=None, arc_element_type=None, description=None, story_element_node=None, **kwargs): ''' Overrides the default `treebeard` function, adding additional integrity checks. ''' if 'mile' in arc_element_type: if self.get_depth() == 1: raise ...
python
def add_sibling(self, pos=None, arc_element_type=None, description=None, story_element_node=None, **kwargs): ''' Overrides the default `treebeard` function, adding additional integrity checks. ''' if 'mile' in arc_element_type: if self.get_depth() == 1: raise ...
[ "def", "add_sibling", "(", "self", ",", "pos", "=", "None", ",", "arc_element_type", "=", "None", ",", "description", "=", "None", ",", "story_element_node", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'mile'", "in", "arc_element_type", ":", "...
Overrides the default `treebeard` function, adding additional integrity checks.
[ "Overrides", "the", "default", "treebeard", "function", "adding", "additional", "integrity", "checks", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L761-L778
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
StoryElementNode.all_characters
def all_characters(self): ''' Returns a queryset of all characters associated with this node and its descendants, excluding any duplicates. ''' qs = self.assoc_characters.all() for node in self.get_descendants(): qs2 = node.assoc_characters.all() q...
python
def all_characters(self): ''' Returns a queryset of all characters associated with this node and its descendants, excluding any duplicates. ''' qs = self.assoc_characters.all() for node in self.get_descendants(): qs2 = node.assoc_characters.all() q...
[ "def", "all_characters", "(", "self", ")", ":", "qs", "=", "self", ".", "assoc_characters", ".", "all", "(", ")", "for", "node", "in", "self", ".", "get_descendants", "(", ")", ":", "qs2", "=", "node", ".", "assoc_characters", ".", "all", "(", ")", "...
Returns a queryset of all characters associated with this node and its descendants, excluding any duplicates.
[ "Returns", "a", "queryset", "of", "all", "characters", "associated", "with", "this", "node", "and", "its", "descendants", "excluding", "any", "duplicates", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L817-L826
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
StoryElementNode.impact_rating
def impact_rating(self): ''' Returns the impact rating for this node. Impact rating is a measure of how powerful this moment in the story is by evaluting how many simultaneous arc elements are associated with it. There is also a generational bleed element, where the impact score ...
python
def impact_rating(self): ''' Returns the impact rating for this node. Impact rating is a measure of how powerful this moment in the story is by evaluting how many simultaneous arc elements are associated with it. There is also a generational bleed element, where the impact score ...
[ "def", "impact_rating", "(", "self", ")", ":", "if", "self", ".", "depth", "==", "1", ":", "logger", ".", "debug", "(", "'Root node. Skipping.'", ")", "return", "0", "# pragma: no cover", "impact_bleed", "=", "{", "'mile'", ":", "0.5", ",", "# A milestone ex...
Returns the impact rating for this node. Impact rating is a measure of how powerful this moment in the story is by evaluting how many simultaneous arc elements are associated with it. There is also a generational bleed element, where the impact score creates shockwaves throughout their direct an...
[ "Returns", "the", "impact", "rating", "for", "this", "node", ".", "Impact", "rating", "is", "a", "measure", "of", "how", "powerful", "this", "moment", "in", "the", "story", "is", "by", "evaluting", "how", "many", "simultaneous", "arc", "elements", "are", "...
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L829-L878
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
StoryElementNode._local_impact_rating
def _local_impact_rating(self): ''' Traverses the generations to evaluate the impact/power of the arc elements associated with each node. ''' impact_values = { 'base': 0.5, 'mile': 2, 'beat': 0.5, 'tf': 0.5, 'mile_child'...
python
def _local_impact_rating(self): ''' Traverses the generations to evaluate the impact/power of the arc elements associated with each node. ''' impact_values = { 'base': 0.5, 'mile': 2, 'beat': 0.5, 'tf': 0.5, 'mile_child'...
[ "def", "_local_impact_rating", "(", "self", ")", ":", "impact_values", "=", "{", "'base'", ":", "0.5", ",", "'mile'", ":", "2", ",", "'beat'", ":", "0.5", ",", "'tf'", ":", "0.5", ",", "'mile_child'", ":", "0.5", ",", "'same_mile'", ":", "2.5", ",", ...
Traverses the generations to evaluate the impact/power of the arc elements associated with each node.
[ "Traverses", "the", "generations", "to", "evaluate", "the", "impact", "/", "power", "of", "the", "arc", "elements", "associated", "with", "each", "node", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L880-L924
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
StoryElementNode.all_locations
def all_locations(self): ''' Returns a queryset of all locations associated with this node and its descendants, excluding any duplicates. ''' qs = self.assoc_locations.all() for node in self.get_descendants(): qs2 = node.assoc_locations.all() qs = ...
python
def all_locations(self): ''' Returns a queryset of all locations associated with this node and its descendants, excluding any duplicates. ''' qs = self.assoc_locations.all() for node in self.get_descendants(): qs2 = node.assoc_locations.all() qs = ...
[ "def", "all_locations", "(", "self", ")", ":", "qs", "=", "self", ".", "assoc_locations", ".", "all", "(", ")", "for", "node", "in", "self", ".", "get_descendants", "(", ")", ":", "qs2", "=", "node", ".", "assoc_locations", ".", "all", "(", ")", "qs"...
Returns a queryset of all locations associated with this node and its descendants, excluding any duplicates.
[ "Returns", "a", "queryset", "of", "all", "locations", "associated", "with", "this", "node", "and", "its", "descendants", "excluding", "any", "duplicates", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L927-L936
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
StoryElementNode.move
def move(self, target, pos=None): ''' An override of the treebeard api in order to send a signal in advance. ''' if self.outline != target.outline: raise IntegrityError('Elements must be from the same outline!') tree_manipulation.send( sender=self.__class_...
python
def move(self, target, pos=None): ''' An override of the treebeard api in order to send a signal in advance. ''' if self.outline != target.outline: raise IntegrityError('Elements must be from the same outline!') tree_manipulation.send( sender=self.__class_...
[ "def", "move", "(", "self", ",", "target", ",", "pos", "=", "None", ")", ":", "if", "self", ".", "outline", "!=", "target", ".", "outline", ":", "raise", "IntegrityError", "(", "'Elements must be from the same outline!'", ")", "tree_manipulation", ".", "send",...
An override of the treebeard api in order to send a signal in advance.
[ "An", "override", "of", "the", "treebeard", "api", "in", "order", "to", "send", "a", "signal", "in", "advance", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L938-L952
maceoutliner/django-fiction-outlines
fiction_outlines/models.py
StoryElementNode.add_child
def add_child(self, story_element_type=None, outline=None, name=None, description=None, **kwargs): ''' An override of the treebeard add_child() method so we can send a signal. ''' if not outline: outline = self.outline if outline != self.outline: raise Int...
python
def add_child(self, story_element_type=None, outline=None, name=None, description=None, **kwargs): ''' An override of the treebeard add_child() method so we can send a signal. ''' if not outline: outline = self.outline if outline != self.outline: raise Int...
[ "def", "add_child", "(", "self", ",", "story_element_type", "=", "None", ",", "outline", "=", "None", ",", "name", "=", "None", ",", "description", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "outline", ":", "outline", "=", "self", "...
An override of the treebeard add_child() method so we can send a signal.
[ "An", "override", "of", "the", "treebeard", "add_child", "()", "method", "so", "we", "can", "send", "a", "signal", "." ]
train
https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/models.py#L954-L976
pyros-dev/pyros-common
pyros_interfaces_mock/pyros_mock.py
PyrosMock.topics
def topics(self): """ :return: the list of topics we interfaced with ( not the list of all available topics ) """ topics = self.interface.publishers.copy() topics.update(self.interface.subscribers) return topics
python
def topics(self): """ :return: the list of topics we interfaced with ( not the list of all available topics ) """ topics = self.interface.publishers.copy() topics.update(self.interface.subscribers) return topics
[ "def", "topics", "(", "self", ")", ":", "topics", "=", "self", ".", "interface", ".", "publishers", ".", "copy", "(", ")", "topics", ".", "update", "(", "self", ".", "interface", ".", "subscribers", ")", "return", "topics" ]
:return: the list of topics we interfaced with ( not the list of all available topics )
[ ":", "return", ":", "the", "list", "of", "topics", "we", "interfaced", "with", "(", "not", "the", "list", "of", "all", "available", "topics", ")" ]
train
https://github.com/pyros-dev/pyros-common/blob/0709538b8777ec055ea31f59cdca5bebaaabb04e/pyros_interfaces_mock/pyros_mock.py#L66-L72
pyros-dev/pyros-common
pyros_interfaces_mock/pyros_mock.py
PyrosMock.setup
def setup(self, publishers=None, subscribers=None, services=None, topics=None, params=None): """ :param publishers: :param subscribers: :param services: :param topics: ONLY HERE for BW compat :param params: :return: """ super(PyrosMock, self).setup...
python
def setup(self, publishers=None, subscribers=None, services=None, topics=None, params=None): """ :param publishers: :param subscribers: :param services: :param topics: ONLY HERE for BW compat :param params: :return: """ super(PyrosMock, self).setup...
[ "def", "setup", "(", "self", ",", "publishers", "=", "None", ",", "subscribers", "=", "None", ",", "services", "=", "None", ",", "topics", "=", "None", ",", "params", "=", "None", ")", ":", "super", "(", "PyrosMock", ",", "self", ")", ".", "setup", ...
:param publishers: :param subscribers: :param services: :param topics: ONLY HERE for BW compat :param params: :return:
[ ":", "param", "publishers", ":", ":", "param", "subscribers", ":", ":", "param", "services", ":", ":", "param", "topics", ":", "ONLY", "HERE", "for", "BW", "compat", ":", "param", "params", ":", ":", "return", ":" ]
train
https://github.com/pyros-dev/pyros-common/blob/0709538b8777ec055ea31f59cdca5bebaaabb04e/pyros_interfaces_mock/pyros_mock.py#L130-L139
stefankoegl/bitlove-python
bitlove.py
BitloveClient.get_by_enclosures
def get_by_enclosures(self, enclosure_urls): """ Get bitlove data for a list of enclosure URLs """ # prepare URLs enclosure_urls = map(str.strip, enclosure_urls) enclosure_urls = filter(None, enclosure_urls) return BitloveResponse(self.opener, enclosure_urls)
python
def get_by_enclosures(self, enclosure_urls): """ Get bitlove data for a list of enclosure URLs """ # prepare URLs enclosure_urls = map(str.strip, enclosure_urls) enclosure_urls = filter(None, enclosure_urls) return BitloveResponse(self.opener, enclosure_urls)
[ "def", "get_by_enclosures", "(", "self", ",", "enclosure_urls", ")", ":", "# prepare URLs", "enclosure_urls", "=", "map", "(", "str", ".", "strip", ",", "enclosure_urls", ")", "enclosure_urls", "=", "filter", "(", "None", ",", "enclosure_urls", ")", "return", ...
Get bitlove data for a list of enclosure URLs
[ "Get", "bitlove", "data", "for", "a", "list", "of", "enclosure", "URLs" ]
train
https://github.com/stefankoegl/bitlove-python/blob/4ca4a3fe8d115782876f9e7ee5deac66119cc410/bitlove.py#L71-L78
stefankoegl/bitlove-python
bitlove.py
BitloveResponse.get
def get(self, url): """ Get the response for the given enclosure URL """ self._query() return Enclosure(self._resp.get(url), url)
python
def get(self, url): """ Get the response for the given enclosure URL """ self._query() return Enclosure(self._resp.get(url), url)
[ "def", "get", "(", "self", ",", "url", ")", ":", "self", ".", "_query", "(", ")", "return", "Enclosure", "(", "self", ".", "_resp", ".", "get", "(", "url", ")", ",", "url", ")" ]
Get the response for the given enclosure URL
[ "Get", "the", "response", "for", "the", "given", "enclosure", "URL" ]
train
https://github.com/stefankoegl/bitlove-python/blob/4ca4a3fe8d115782876f9e7ee5deac66119cc410/bitlove.py#L90-L93
stefankoegl/bitlove-python
bitlove.py
BitloveResponse._query
def _query(self): """ perform a request to the API, only when necessary """ if not self.urls: self._resp = {} elif self._resp is None: params = [ ('url', url) for url in self.urls] query = urllib.urlencode(params) # query API r = sel...
python
def _query(self): """ perform a request to the API, only when necessary """ if not self.urls: self._resp = {} elif self._resp is None: params = [ ('url', url) for url in self.urls] query = urllib.urlencode(params) # query API r = sel...
[ "def", "_query", "(", "self", ")", ":", "if", "not", "self", ".", "urls", ":", "self", ".", "_resp", "=", "{", "}", "elif", "self", ".", "_resp", "is", "None", ":", "params", "=", "[", "(", "'url'", ",", "url", ")", "for", "url", "in", "self", ...
perform a request to the API, only when necessary
[ "perform", "a", "request", "to", "the", "API", "only", "when", "necessary" ]
train
https://github.com/stefankoegl/bitlove-python/blob/4ca4a3fe8d115782876f9e7ee5deac66119cc410/bitlove.py#L102-L114
iamFIREcracker/aadbook
aadbook/aadbook.py
_build_parser
def _build_parser(): """ Return a command-line arguments parser. """ parser = argparse.ArgumentParser(description='Search you Azure AD contacts from mutt or the command-line.') parser.add_argument('-c', '--config', help='Specify alternative configuration file.', metavar="FILE") parser.add_argume...
python
def _build_parser(): """ Return a command-line arguments parser. """ parser = argparse.ArgumentParser(description='Search you Azure AD contacts from mutt or the command-line.') parser.add_argument('-c', '--config', help='Specify alternative configuration file.', metavar="FILE") parser.add_argume...
[ "def", "_build_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Search you Azure AD contacts from mutt or the command-line.'", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--config'", ",", "help", "=", "...
Return a command-line arguments parser.
[ "Return", "a", "command", "-", "line", "arguments", "parser", "." ]
train
https://github.com/iamFIREcracker/aadbook/blob/d191e9d36a2309449ab91c1728eaf5901b7ef91c/aadbook/aadbook.py#L40-L75
krinj/k-util
setup.py
find_packages_under
def find_packages_under(path): """ Recursive list all of the packages under a specific package.""" all_packages = setuptools.find_packages() packages = [] for package in all_packages: package_split = package.split(".") if package_split[0] == path: packages.append(package) ...
python
def find_packages_under(path): """ Recursive list all of the packages under a specific package.""" all_packages = setuptools.find_packages() packages = [] for package in all_packages: package_split = package.split(".") if package_split[0] == path: packages.append(package) ...
[ "def", "find_packages_under", "(", "path", ")", ":", "all_packages", "=", "setuptools", ".", "find_packages", "(", ")", "packages", "=", "[", "]", "for", "package", "in", "all_packages", ":", "package_split", "=", "package", ".", "split", "(", "\".\"", ")", ...
Recursive list all of the packages under a specific package.
[ "Recursive", "list", "all", "of", "the", "packages", "under", "a", "specific", "package", "." ]
train
https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/setup.py#L25-L33
krinj/k-util
setup.py
copy_version_to_package
def copy_version_to_package(path): """ Copy the single source of truth version number into the package as well. """ init_file = os.path.join(path, "__init__.py") with open(init_file, "r") as original_file: lines = original_file.readlines() with open(init_file, "w") as new_file: for line...
python
def copy_version_to_package(path): """ Copy the single source of truth version number into the package as well. """ init_file = os.path.join(path, "__init__.py") with open(init_file, "r") as original_file: lines = original_file.readlines() with open(init_file, "w") as new_file: for line...
[ "def", "copy_version_to_package", "(", "path", ")", ":", "init_file", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"__init__.py\"", ")", "with", "open", "(", "init_file", ",", "\"r\"", ")", "as", "original_file", ":", "lines", "=", "original_fi...
Copy the single source of truth version number into the package as well.
[ "Copy", "the", "single", "source", "of", "truth", "version", "number", "into", "the", "package", "as", "well", "." ]
train
https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/setup.py#L36-L47
marcosgabarda/django-belt
setup.py
InstallStaticDependenciesCommand.run
def run(self): """Run command.""" command = ['npm', 'install'] self.announce( 'Running command: %s' % str(command), level=INFO) subprocess.check_call(command)
python
def run(self): """Run command.""" command = ['npm', 'install'] self.announce( 'Running command: %s' % str(command), level=INFO) subprocess.check_call(command)
[ "def", "run", "(", "self", ")", ":", "command", "=", "[", "'npm'", ",", "'install'", "]", "self", ".", "announce", "(", "'Running command: %s'", "%", "str", "(", "command", ")", ",", "level", "=", "INFO", ")", "subprocess", ".", "check_call", "(", "com...
Run command.
[ "Run", "command", "." ]
train
https://github.com/marcosgabarda/django-belt/blob/81404604c4dff664b1520b01e1f638c9c6bab41b/setup.py#L38-L44
privacee/freelan-configurator
freelan_configurator/freelan_cfg.py
FreelanCFG.validate
def validate(self): """Validation of configuration to check for required values""" if not self.server.enabled: if self.security.signature_certificate_file is self.security.defaults['signature_certificate_file']: print("ISSUE: If you are not configuring a server, you need to...
python
def validate(self): """Validation of configuration to check for required values""" if not self.server.enabled: if self.security.signature_certificate_file is self.security.defaults['signature_certificate_file']: print("ISSUE: If you are not configuring a server, you need to...
[ "def", "validate", "(", "self", ")", ":", "if", "not", "self", ".", "server", ".", "enabled", ":", "if", "self", ".", "security", ".", "signature_certificate_file", "is", "self", ".", "security", ".", "defaults", "[", "'signature_certificate_file'", "]", ":"...
Validation of configuration to check for required values
[ "Validation", "of", "configuration", "to", "check", "for", "required", "values" ]
train
https://github.com/privacee/freelan-configurator/blob/7c070f8958454792f870ef0d195a7f5da36edb5a/freelan_configurator/freelan_cfg.py#L192-L247
inveniosoftware-attic/invenio-knowledge
invenio_knowledge/admin.py
Knowledge_kbtype_formatter
def Knowledge_kbtype_formatter(view, context, model, name): """Formatter for the kbtype: return the Knowledge name instead.""" value = model.kbtype return next((key for key, val in KnwKB.KNWKB_TYPES.items() if val == value), None)
python
def Knowledge_kbtype_formatter(view, context, model, name): """Formatter for the kbtype: return the Knowledge name instead.""" value = model.kbtype return next((key for key, val in KnwKB.KNWKB_TYPES.items() if val == value), None)
[ "def", "Knowledge_kbtype_formatter", "(", "view", ",", "context", ",", "model", ",", "name", ")", ":", "value", "=", "model", ".", "kbtype", "return", "next", "(", "(", "key", "for", "key", ",", "val", "in", "KnwKB", ".", "KNWKB_TYPES", ".", "items", "...
Formatter for the kbtype: return the Knowledge name instead.
[ "Formatter", "for", "the", "kbtype", ":", "return", "the", "Knowledge", "name", "instead", "." ]
train
https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/admin.py#L40-L44
inveniosoftware-attic/invenio-knowledge
invenio_knowledge/admin.py
register_admin
def register_admin(app, admin): """Called on app initialization to register administration interface.""" category = 'Knowledge' admin.category_icon_classes[category] = "fa fa-mortar-board" admin.add_view( KnowledgeAdmin(app, KnwKB, db.session, name='Knowledge Base', catego...
python
def register_admin(app, admin): """Called on app initialization to register administration interface.""" category = 'Knowledge' admin.category_icon_classes[category] = "fa fa-mortar-board" admin.add_view( KnowledgeAdmin(app, KnwKB, db.session, name='Knowledge Base', catego...
[ "def", "register_admin", "(", "app", ",", "admin", ")", ":", "category", "=", "'Knowledge'", "admin", ".", "category_icon_classes", "[", "category", "]", "=", "\"fa fa-mortar-board\"", "admin", ".", "add_view", "(", "KnowledgeAdmin", "(", "app", ",", "KnwKB", ...
Called on app initialization to register administration interface.
[ "Called", "on", "app", "initialization", "to", "register", "administration", "interface", "." ]
train
https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/admin.py#L188-L201
inveniosoftware-attic/invenio-knowledge
invenio_knowledge/admin.py
KnowledgeAdmin.after_model_change
def after_model_change(self, form, model, is_created): """Save model.""" super(KnowledgeAdmin, self).after_model_change(form, model, is_created) from invenio_collections.models import Collection if form.kbtype.data == KnwKB.KNWKB_TYPES['dynamic']: id_collection = form.id_col...
python
def after_model_change(self, form, model, is_created): """Save model.""" super(KnowledgeAdmin, self).after_model_change(form, model, is_created) from invenio_collections.models import Collection if form.kbtype.data == KnwKB.KNWKB_TYPES['dynamic']: id_collection = form.id_col...
[ "def", "after_model_change", "(", "self", ",", "form", ",", "model", ",", "is_created", ")", ":", "super", "(", "KnowledgeAdmin", ",", "self", ")", ".", "after_model_change", "(", "form", ",", "model", ",", "is_created", ")", "from", "invenio_collections", "...
Save model.
[ "Save", "model", "." ]
train
https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/admin.py#L104-L125
inveniosoftware-attic/invenio-knowledge
invenio_knowledge/admin.py
KnowledgeAdmin.edit_form
def edit_form(self, obj=None): """Edit form.""" kbtype = request.args['kbtype'] if 'kbtype' in request.args else 'w' if kbtype == KnwKB.KNWKB_TYPES['written_as']: self.form = WrittenAsKnowledgeForm elif kbtype == KnwKB.KNWKB_TYPES['dynamic']: self.form = DynamicK...
python
def edit_form(self, obj=None): """Edit form.""" kbtype = request.args['kbtype'] if 'kbtype' in request.args else 'w' if kbtype == KnwKB.KNWKB_TYPES['written_as']: self.form = WrittenAsKnowledgeForm elif kbtype == KnwKB.KNWKB_TYPES['dynamic']: self.form = DynamicK...
[ "def", "edit_form", "(", "self", ",", "obj", "=", "None", ")", ":", "kbtype", "=", "request", ".", "args", "[", "'kbtype'", "]", "if", "'kbtype'", "in", "request", ".", "args", "else", "'w'", "if", "kbtype", "==", "KnwKB", ".", "KNWKB_TYPES", "[", "'...
Edit form.
[ "Edit", "form", "." ]
train
https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/admin.py#L127-L158
inveniosoftware-attic/invenio-knowledge
invenio_knowledge/admin.py
KnowledgeAdmin.create_form
def create_form(self, obj=None): """Create form.""" kbtype = request.args['kbtype'] if 'kbtype' in request.args else 'w' if kbtype == KnwKB.KNWKB_TYPES['written_as']: self.form = WrittenAsKnowledgeForm elif kbtype == KnwKB.KNWKB_TYPES['dynamic']: self.form = Dyna...
python
def create_form(self, obj=None): """Create form.""" kbtype = request.args['kbtype'] if 'kbtype' in request.args else 'w' if kbtype == KnwKB.KNWKB_TYPES['written_as']: self.form = WrittenAsKnowledgeForm elif kbtype == KnwKB.KNWKB_TYPES['dynamic']: self.form = Dyna...
[ "def", "create_form", "(", "self", ",", "obj", "=", "None", ")", ":", "kbtype", "=", "request", ".", "args", "[", "'kbtype'", "]", "if", "'kbtype'", "in", "request", ".", "args", "else", "'w'", "if", "kbtype", "==", "KnwKB", ".", "KNWKB_TYPES", "[", ...
Create form.
[ "Create", "form", "." ]
train
https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/admin.py#L160-L174
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC.connect
def connect(self): """与远端建立连接,并进行验证身份.""" self._client = Telnet(self.hostname, self.port) self.closed = False query = { "MPRPC": self.VERSION, "AUTH": { "USERNAME": self.username, "PASSWORD": self.password } } ...
python
def connect(self): """与远端建立连接,并进行验证身份.""" self._client = Telnet(self.hostname, self.port) self.closed = False query = { "MPRPC": self.VERSION, "AUTH": { "USERNAME": self.username, "PASSWORD": self.password } } ...
[ "def", "connect", "(", "self", ")", ":", "self", ".", "_client", "=", "Telnet", "(", "self", ".", "hostname", ",", "self", ".", "port", ")", "self", ".", "closed", "=", "False", "query", "=", "{", "\"MPRPC\"", ":", "self", ".", "VERSION", ",", "\"A...
与远端建立连接,并进行验证身份.
[ "与远端建立连接", "并进行验证身份", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L120-L135
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC.reconnect
def reconnect(self): """断线重连.""" self.closed = True self.connect() if self.debug: print("reconnect to {}".format((self.hostname, self.port)))
python
def reconnect(self): """断线重连.""" self.closed = True self.connect() if self.debug: print("reconnect to {}".format((self.hostname, self.port)))
[ "def", "reconnect", "(", "self", ")", ":", "self", ".", "closed", "=", "True", "self", ".", "connect", "(", ")", "if", "self", ".", "debug", ":", "print", "(", "\"reconnect to {}\"", ".", "format", "(", "(", "self", ".", "hostname", ",", "self", ".",...
断线重连.
[ "断线重连", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L137-L142
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC.close
def close(self): """关闭与远端的连接. 判断标志位closed是否为False,如果是则关闭,否则不进行操作 """ if self.closed is False: self._client.close() self.closed = True if self.debug is True: print('close') if self.debug is True: print("closed")
python
def close(self): """关闭与远端的连接. 判断标志位closed是否为False,如果是则关闭,否则不进行操作 """ if self.closed is False: self._client.close() self.closed = True if self.debug is True: print('close') if self.debug is True: print("closed")
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "closed", "is", "False", ":", "self", ".", "_client", ".", "close", "(", ")", "self", ".", "closed", "=", "True", "if", "self", ".", "debug", "is", "True", ":", "print", "(", "'close'", ")...
关闭与远端的连接. 判断标志位closed是否为False,如果是则关闭,否则不进行操作
[ "关闭与远端的连接", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L144-L156
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC._status_code_check
def _status_code_check(self, response: Dict[str, Any]): """检查响应码并进行对不同的响应进行处理. 主要包括: + 编码在500~599段为服务异常,直接抛出对应异常 + 编码在400~499段为调用异常,为对应ID的future设置异常 + 编码在300~399段为警告,会抛出对应警告 + 编码在200~399段为执行成功响应,将结果设置给对应ID的future. + 编码在100~199段为服务器响应,主要是处理验证响应和心跳响应 Param...
python
def _status_code_check(self, response: Dict[str, Any]): """检查响应码并进行对不同的响应进行处理. 主要包括: + 编码在500~599段为服务异常,直接抛出对应异常 + 编码在400~499段为调用异常,为对应ID的future设置异常 + 编码在300~399段为警告,会抛出对应警告 + 编码在200~399段为执行成功响应,将结果设置给对应ID的future. + 编码在100~199段为服务器响应,主要是处理验证响应和心跳响应 Param...
[ "def", "_status_code_check", "(", "self", ",", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "code", "=", "response", ".", "get", "(", "\"CODE\"", ")", "if", "self", ".", "debug", ":", "print", "(", "\"resv:{}\"", ".", "format", "("...
检查响应码并进行对不同的响应进行处理. 主要包括: + 编码在500~599段为服务异常,直接抛出对应异常 + 编码在400~499段为调用异常,为对应ID的future设置异常 + 编码在300~399段为警告,会抛出对应警告 + 编码在200~399段为执行成功响应,将结果设置给对应ID的future. + 编码在100~199段为服务器响应,主要是处理验证响应和心跳响应 Parameters: response (Dict[str, Any]): - 响应的python字典形式数据 ...
[ "检查响应码并进行对不同的响应进行处理", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L171-L214
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC._method_error_handler
def _method_error_handler(self, response: Dict[str, Any]): """处理400~499段状态码,为对应的任务设置异常. Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ exp = response.get('MESSAGE') code = response.get("CODE") ID = exp.g...
python
def _method_error_handler(self, response: Dict[str, Any]): """处理400~499段状态码,为对应的任务设置异常. Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ exp = response.get('MESSAGE') code = response.get("CODE") ID = exp.g...
[ "def", "_method_error_handler", "(", "self", ",", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "exp", "=", "response", ".", "get", "(", "'MESSAGE'", ")", "code", "=", "response", ".", "get", "(", "\"CODE\"", ")", "ID", "=", "exp", ...
处理400~499段状态码,为对应的任务设置异常. Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True
[ "处理400~499段状态码", "为对应的任务设置异常", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L231-L244
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC._warning_handler
def _warning_handler(self, code: int): """处理300~399段状态码,抛出对应警告. Parameters: (code): - 响应的状态码 Return: (bool): - 已知的警告类型则返回True,否则返回False """ if code == 300: warnings.warn( "ExpireWarning", RuntimeWarning, ...
python
def _warning_handler(self, code: int): """处理300~399段状态码,抛出对应警告. Parameters: (code): - 响应的状态码 Return: (bool): - 已知的警告类型则返回True,否则返回False """ if code == 300: warnings.warn( "ExpireWarning", RuntimeWarning, ...
[ "def", "_warning_handler", "(", "self", ",", "code", ":", "int", ")", ":", "if", "code", "==", "300", ":", "warnings", ".", "warn", "(", "\"ExpireWarning\"", ",", "RuntimeWarning", ",", "stacklevel", "=", "3", ")", "elif", "code", "==", "301", ":", "wa...
处理300~399段状态码,抛出对应警告. Parameters: (code): - 响应的状态码 Return: (bool): - 已知的警告类型则返回True,否则返回False
[ "处理300~399段状态码", "抛出对应警告", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L246-L272
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC._result_handler
def _result_handler(self, response: Dict[str, Any]): """应答结果响应处理. 将结果解析出来设置给任务对应的Future对象上 Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ res = response.get("MESSAGE") result = res.get("RESULT") ...
python
def _result_handler(self, response: Dict[str, Any]): """应答结果响应处理. 将结果解析出来设置给任务对应的Future对象上 Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ res = response.get("MESSAGE") result = res.get("RESULT") ...
[ "def", "_result_handler", "(", "self", ",", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "res", "=", "response", ".", "get", "(", "\"MESSAGE\"", ")", "result", "=", "res", ".", "get", "(", "\"RESULT\"", ")", "return", "result" ]
应答结果响应处理. 将结果解析出来设置给任务对应的Future对象上 Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True
[ "应答结果响应处理", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L311-L325
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC._gen_result_handler
def _gen_result_handler(self): """流式结果响应处理. 收到状态码标识201或301的响应后,创建一个生成器用于反映流. Yield: (Any): - 流中的运算结果 """ while True: try: data = self._client.read_until(self.SEPARATOR) except: raise else: ...
python
def _gen_result_handler(self): """流式结果响应处理. 收到状态码标识201或301的响应后,创建一个生成器用于反映流. Yield: (Any): - 流中的运算结果 """ while True: try: data = self._client.read_until(self.SEPARATOR) except: raise else: ...
[ "def", "_gen_result_handler", "(", "self", ")", ":", "while", "True", ":", "try", ":", "data", "=", "self", ".", "_client", ".", "read_until", "(", "self", ".", "SEPARATOR", ")", "except", ":", "raise", "else", ":", "response", "=", "self", ".", "decod...
流式结果响应处理. 收到状态码标识201或301的响应后,创建一个生成器用于反映流. Yield: (Any): - 流中的运算结果
[ "流式结果响应处理", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L329-L351
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC._make_query
def _make_query(self, ID: str, methodname: str, *args: Any, **kwargs: Any): """将调用请求的ID,方法名,参数包装为请求数据. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (Dict[str, ...
python
def _make_query(self, ID: str, methodname: str, *args: Any, **kwargs: Any): """将调用请求的ID,方法名,参数包装为请求数据. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (Dict[str, ...
[ "def", "_make_query", "(", "self", ",", "ID", ":", "str", ",", "methodname", ":", "str", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", ":", "query", "=", "{", "\"MPRPC\"", ":", "self", ".", "VERSION", ",", "\"ID\"", ":",...
将调用请求的ID,方法名,参数包装为请求数据. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (Dict[str, Any]) : - 请求的python字典形式
[ "将调用请求的ID", "方法名", "参数包装为请求数据", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L355-L377
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC._send_query
def _send_query(self, query: Dict[str, Any]): """将请求编码为字节串发送出去给服务端. Parameters: (query): - 请求的的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ queryb = self.encoder(query) self._client.write(queryb) if self.debug is True: ...
python
def _send_query(self, query: Dict[str, Any]): """将请求编码为字节串发送出去给服务端. Parameters: (query): - 请求的的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ queryb = self.encoder(query) self._client.write(queryb) if self.debug is True: ...
[ "def", "_send_query", "(", "self", ",", "query", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "queryb", "=", "self", ".", "encoder", "(", "query", ")", "self", ".", "_client", ".", "write", "(", "queryb", ")", "if", "self", ".", "debug", "...
将请求编码为字节串发送出去给服务端. Parameters: (query): - 请求的的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True
[ "将请求编码为字节串发送出去给服务端", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L379-L394
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC.send_query
def send_query(self, ID, methodname, *args, **kwargs): """将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (bool): - 准确地说没有错误就会...
python
def send_query(self, ID, methodname, *args, **kwargs): """将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (bool): - 准确地说没有错误就会...
[ "def", "send_query", "(", "self", ",", "ID", ",", "methodname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_make_query", "(", "ID", ",", "methodname", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", "...
将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (bool): - 准确地说没有错误就会返回True
[ "将调用请求的ID", "方法名", "参数包装为请求数据后编码为字节串发送出去", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L396-L412
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC._query
def _query(self, ID, methodname, *args, **kwargs): """将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (asyncio...
python
def _query(self, ID, methodname, *args, **kwargs): """将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (asyncio...
[ "def", "_query", "(", "self", ",", "ID", ",", "methodname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "send_query", "(", "ID", ",", "methodname", ",", "*", "args", ",", "*", "*", "kwargs", ")", "result", "=", "self", ".", ...
将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (asyncio.Future): - 返回对应ID的Future对象
[ "将调用请求的ID", "方法名", "参数包装为请求数据后编码为字节串发送出去", ".", "并创建一个Future对象占位", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L427-L443
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/sync.py
RPC.query
def query(self, methodname, *args, **kwargs): """异步调用一个远端的函数. 为调用创建一个ID,并将调用请求的方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (asyncio.Futu...
python
def query(self, methodname, *args, **kwargs): """异步调用一个远端的函数. 为调用创建一个ID,并将调用请求的方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (asyncio.Futu...
[ "def", "query", "(", "self", ",", "methodname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ID", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "result", "=", "self", ".", "_query", "(", "ID", "=", "ID", ",", "methodname", "=",...
异步调用一个远端的函数. 为调用创建一个ID,并将调用请求的方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (asyncio.Future): - 返回对应ID的Future对象
[ "异步调用一个远端的函数", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L445-L461
makinacorpus/tif2geojson
tif2geojson.py
_deep_value
def _deep_value(*args, **kwargs): """ Drills down into tree using the keys """ node, keys = args[0], args[1:] for key in keys: node = node.get(key, {}) default = kwargs.get('default', {}) if node in ({}, [], None): node = default return node
python
def _deep_value(*args, **kwargs): """ Drills down into tree using the keys """ node, keys = args[0], args[1:] for key in keys: node = node.get(key, {}) default = kwargs.get('default', {}) if node in ({}, [], None): node = default return node
[ "def", "_deep_value", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "node", ",", "keys", "=", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", "for", "key", "in", "keys", ":", "node", "=", "node", ".", "get", "(", "key", ",", ...
Drills down into tree using the keys
[ "Drills", "down", "into", "tree", "using", "the", "keys" ]
train
https://github.com/makinacorpus/tif2geojson/blob/071b26cea6e23a3ec87a5cd1f73cc800612021b9/tif2geojson.py#L162-L171
makinacorpus/tif2geojson
tif2geojson.py
Converter._parse_location
def _parse_location(self, entry): """ Return the **first** location as `geojson.Point`. """ locations = _deep_value_list(entry, 'tif:Geolocalisations') coords = [] for location in locations: coords = _deep_value(location, 'tif:DetailGeolocalisation', ...
python
def _parse_location(self, entry): """ Return the **first** location as `geojson.Point`. """ locations = _deep_value_list(entry, 'tif:Geolocalisations') coords = [] for location in locations: coords = _deep_value(location, 'tif:DetailGeolocalisation', ...
[ "def", "_parse_location", "(", "self", ",", "entry", ")", ":", "locations", "=", "_deep_value_list", "(", "entry", ",", "'tif:Geolocalisations'", ")", "coords", "=", "[", "]", "for", "location", "in", "locations", ":", "coords", "=", "_deep_value", "(", "loc...
Return the **first** location as `geojson.Point`.
[ "Return", "the", "**", "first", "**", "location", "as", "geojson", ".", "Point", "." ]
train
https://github.com/makinacorpus/tif2geojson/blob/071b26cea6e23a3ec87a5cd1f73cc800612021b9/tif2geojson.py#L54-L75
klahnakoski/mo-dots
mo_dots/__init__.py
_get_dict_default
def _get_dict_default(obj, key): """ obj MUST BE A DICT key IS EXPECTED TO BE LITERAL (NO ESCAPING) TRY BOTH ATTRIBUTE AND ITEM ACCESS, OR RETURN Null """ try: return obj[key] except Exception as f: pass try: if float(key) == round(float(key), 0): ret...
python
def _get_dict_default(obj, key): """ obj MUST BE A DICT key IS EXPECTED TO BE LITERAL (NO ESCAPING) TRY BOTH ATTRIBUTE AND ITEM ACCESS, OR RETURN Null """ try: return obj[key] except Exception as f: pass try: if float(key) == round(float(key), 0): ret...
[ "def", "_get_dict_default", "(", "obj", ",", "key", ")", ":", "try", ":", "return", "obj", "[", "key", "]", "except", "Exception", "as", "f", ":", "pass", "try", ":", "if", "float", "(", "key", ")", "==", "round", "(", "float", "(", "key", ")", "...
obj MUST BE A DICT key IS EXPECTED TO BE LITERAL (NO ESCAPING) TRY BOTH ATTRIBUTE AND ITEM ACCESS, OR RETURN Null
[ "obj", "MUST", "BE", "A", "DICT", "key", "IS", "EXPECTED", "TO", "BE", "LITERAL", "(", "NO", "ESCAPING", ")", "TRY", "BOTH", "ATTRIBUTE", "AND", "ITEM", "ACCESS", "OR", "RETURN", "Null" ]
train
https://github.com/klahnakoski/mo-dots/blob/53b16f754b46609419bcfa5acb6fcbba15f564fc/mo_dots/__init__.py#L262-L279
klahnakoski/mo-dots
mo_dots/__init__.py
listwrap
def listwrap(value): """ PERFORMS THE FOLLOWING TRANSLATION None -> [] value -> [value] [...] -> [...] (unchanged list) ##MOTIVATION## OFTEN IT IS NICE TO ALLOW FUNCTION PARAMETERS TO BE ASSIGNED A VALUE, OR A list-OF-VALUES, OR NULL. CHECKING FOR WHICH THE CALLER USED IS TEDIOUS....
python
def listwrap(value): """ PERFORMS THE FOLLOWING TRANSLATION None -> [] value -> [value] [...] -> [...] (unchanged list) ##MOTIVATION## OFTEN IT IS NICE TO ALLOW FUNCTION PARAMETERS TO BE ASSIGNED A VALUE, OR A list-OF-VALUES, OR NULL. CHECKING FOR WHICH THE CALLER USED IS TEDIOUS....
[ "def", "listwrap", "(", "value", ")", ":", "if", "value", "==", "None", ":", "return", "FlatList", "(", ")", "elif", "is_list", "(", "value", ")", ":", "return", "wrap", "(", "value", ")", "elif", "is_many", "(", "value", ")", ":", "return", "wrap", ...
PERFORMS THE FOLLOWING TRANSLATION None -> [] value -> [value] [...] -> [...] (unchanged list) ##MOTIVATION## OFTEN IT IS NICE TO ALLOW FUNCTION PARAMETERS TO BE ASSIGNED A VALUE, OR A list-OF-VALUES, OR NULL. CHECKING FOR WHICH THE CALLER USED IS TEDIOUS. INSTEAD WE CAST FROM THOSE THRE...
[ "PERFORMS", "THE", "FOLLOWING", "TRANSLATION", "None", "-", ">", "[]", "value", "-", ">", "[", "value", "]", "[", "...", "]", "-", ">", "[", "...", "]", "(", "unchanged", "list", ")" ]
train
https://github.com/klahnakoski/mo-dots/blob/53b16f754b46609419bcfa5acb6fcbba15f564fc/mo_dots/__init__.py#L546-L581
klahnakoski/mo-dots
mo_dots/__init__.py
tuplewrap
def tuplewrap(value): """ INTENDED TO TURN lists INTO tuples FOR USE AS KEYS """ if is_many(value): return tuple(tuplewrap(v) if is_sequence(v) else v for v in value) return unwrap(value),
python
def tuplewrap(value): """ INTENDED TO TURN lists INTO tuples FOR USE AS KEYS """ if is_many(value): return tuple(tuplewrap(v) if is_sequence(v) else v for v in value) return unwrap(value),
[ "def", "tuplewrap", "(", "value", ")", ":", "if", "is_many", "(", "value", ")", ":", "return", "tuple", "(", "tuplewrap", "(", "v", ")", "if", "is_sequence", "(", "v", ")", "else", "v", "for", "v", "in", "value", ")", "return", "unwrap", "(", "valu...
INTENDED TO TURN lists INTO tuples FOR USE AS KEYS
[ "INTENDED", "TO", "TURN", "lists", "INTO", "tuples", "FOR", "USE", "AS", "KEYS" ]
train
https://github.com/klahnakoski/mo-dots/blob/53b16f754b46609419bcfa5acb6fcbba15f564fc/mo_dots/__init__.py#L598-L604
MacHu-GWU/angora-project
angora/dataIO/pk.py
load_pk
def load_pk(abspath, compress=False, enable_verbose=True): """Load Python Object from Pickle file. :param abspath: File path. Use absolute path as much as you can. File extension has to be ``.pickle`` or ``.gz``. (for compressed Pickle) :type abspath: string :param compress: (default False) Lo...
python
def load_pk(abspath, compress=False, enable_verbose=True): """Load Python Object from Pickle file. :param abspath: File path. Use absolute path as much as you can. File extension has to be ``.pickle`` or ``.gz``. (for compressed Pickle) :type abspath: string :param compress: (default False) Lo...
[ "def", "load_pk", "(", "abspath", ",", "compress", "=", "False", ",", "enable_verbose", "=", "True", ")", ":", "abspath", "=", "str", "(", "abspath", ")", "# try stringlize", "msg", "=", "Messenger", "(", "enable_verbose", "=", "enable_verbose", ")", "if", ...
Load Python Object from Pickle file. :param abspath: File path. Use absolute path as much as you can. File extension has to be ``.pickle`` or ``.gz``. (for compressed Pickle) :type abspath: string :param compress: (default False) Load from a gzip compressed Pickle file. Check :func:`dump_p...
[ "Load", "Python", "Object", "from", "Pickle", "file", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/pk.py#L73-L135
MacHu-GWU/angora-project
angora/dataIO/pk.py
dump_pk
def dump_pk(obj, abspath, pk_protocol=pk_protocol, replace=False, compress=False, enable_verbose=True): """Dump Picklable Python Object to file. Provides multiple choice to customize the behavior. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file exten...
python
def dump_pk(obj, abspath, pk_protocol=pk_protocol, replace=False, compress=False, enable_verbose=True): """Dump Picklable Python Object to file. Provides multiple choice to customize the behavior. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file exten...
[ "def", "dump_pk", "(", "obj", ",", "abspath", ",", "pk_protocol", "=", "pk_protocol", ",", "replace", "=", "False", ",", "compress", "=", "False", ",", "enable_verbose", "=", "True", ")", ":", "abspath", "=", "str", "(", "abspath", ")", "# try stringlize",...
Dump Picklable Python Object to file. Provides multiple choice to customize the behavior. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file extension has to be ``.pickle`` or ``.gz`` (for compressed Pickle). :type abspath: string :param pk_protocol: (default your...
[ "Dump", "Picklable", "Python", "Object", "to", "file", ".", "Provides", "multiple", "choice", "to", "customize", "the", "behavior", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/pk.py#L138-L250
MacHu-GWU/angora-project
angora/dataIO/pk.py
safe_dump_pk
def safe_dump_pk(obj, abspath, pk_protocol=pk_protocol, compress=False, enable_verbose=True): """A stable version of dump_pk, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a inc...
python
def safe_dump_pk(obj, abspath, pk_protocol=pk_protocol, compress=False, enable_verbose=True): """A stable version of dump_pk, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a inc...
[ "def", "safe_dump_pk", "(", "obj", ",", "abspath", ",", "pk_protocol", "=", "pk_protocol", ",", "compress", "=", "False", ",", "enable_verbose", "=", "True", ")", ":", "abspath", "=", "str", "(", "abspath", ")", "# try stringlize", "temp_abspath", "=", "\"%s...
A stable version of dump_pk, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a incomplete file. If you use replace=True, then you also lose your old file. So a bettr way is to: 1. dump p...
[ "A", "stable", "version", "of", "dump_pk", "silently", "overwrite", "existing", "file", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/pk.py#L253-L326
MacHu-GWU/angora-project
angora/dataIO/pk.py
obj2str
def obj2str(obj, pk_protocol=pk_protocol): """Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1L...
python
def obj2str(obj, pk_protocol=pk_protocol): """Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1L...
[ "def", "obj2str", "(", "obj", ",", "pk_protocol", "=", "pk_protocol", ")", ":", "return", "base64", ".", "b64encode", "(", "pickle", ".", "dumps", "(", "obj", ",", "protocol", "=", "pk_protocol", ")", ")", ".", "decode", "(", "\"utf-8\"", ")" ]
Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1Lg==' **中文文档** 将可Pickle化的Python对象转化为utf-8...
[ "Convert", "arbitrary", "object", "to", "utf", "-", "8", "string", "using", "base64encode", "algorithm", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/pk.py#L363-L379
MacHu-GWU/angora-project
angora/gadget/codestats.py
CodeStats.run
def run(self): """Run analysis. The basic idea is to recursively find all script files in specific programming language, and analyze each file then sum it up. """ n_target_file, n_other_file = 0, 0 code, comment, docstr, purecode = 0, 0, 0, 0 fc = FileCollecti...
python
def run(self): """Run analysis. The basic idea is to recursively find all script files in specific programming language, and analyze each file then sum it up. """ n_target_file, n_other_file = 0, 0 code, comment, docstr, purecode = 0, 0, 0, 0 fc = FileCollecti...
[ "def", "run", "(", "self", ")", ":", "n_target_file", ",", "n_other_file", "=", "0", ",", "0", "code", ",", "comment", ",", "docstr", ",", "purecode", "=", "0", ",", "0", ",", "0", ",", "0", "fc", "=", "FileCollection", ".", "from_path_except", "(", ...
Run analysis. The basic idea is to recursively find all script files in specific programming language, and analyze each file then sum it up.
[ "Run", "analysis", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/codestats.py#L97-L137
MacHu-GWU/angora-project
angora/gadget/codestats.py
CodeStats.analyzePython
def analyzePython(code_text): """Count how many line of code, comment, dosstr, purecode in one Python script file. """ code, comment, docstr = 0, 0, 0 p1 = r"""(?<=%s)[\s\S]*?(?=%s)""" % ('"""', '"""') p2 = r"""(?<=%s)[\s\S]*?(?=%s)""" % ("'''", "'''") # count ...
python
def analyzePython(code_text): """Count how many line of code, comment, dosstr, purecode in one Python script file. """ code, comment, docstr = 0, 0, 0 p1 = r"""(?<=%s)[\s\S]*?(?=%s)""" % ('"""', '"""') p2 = r"""(?<=%s)[\s\S]*?(?=%s)""" % ("'''", "'''") # count ...
[ "def", "analyzePython", "(", "code_text", ")", ":", "code", ",", "comment", ",", "docstr", "=", "0", ",", "0", ",", "0", "p1", "=", "r\"\"\"(?<=%s)[\\s\\S]*?(?=%s)\"\"\"", "%", "(", "'\"\"\"'", ",", "'\"\"\"'", ")", "p2", "=", "r\"\"\"(?<=%s)[\\s\\S]*?(?=%s)\"...
Count how many line of code, comment, dosstr, purecode in one Python script file.
[ "Count", "how", "many", "line", "of", "code", "comment", "dosstr", "purecode", "in", "one", "Python", "script", "file", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/codestats.py#L147-L170
JNRowe/jnrbase
jnrbase/cmdline.py
get_default
def get_default(__func: Callable, __arg: str) -> str: """Fetch default value for a function argument Args: __func: Function to inspect __arg: Argument to extract default value for """ return signature(__func).parameters[__arg].default
python
def get_default(__func: Callable, __arg: str) -> str: """Fetch default value for a function argument Args: __func: Function to inspect __arg: Argument to extract default value for """ return signature(__func).parameters[__arg].default
[ "def", "get_default", "(", "__func", ":", "Callable", ",", "__arg", ":", "str", ")", "->", "str", ":", "return", "signature", "(", "__func", ")", ".", "parameters", "[", "__arg", "]", ".", "default" ]
Fetch default value for a function argument Args: __func: Function to inspect __arg: Argument to extract default value for
[ "Fetch", "default", "value", "for", "a", "function", "argument" ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L38-L45
JNRowe/jnrbase
jnrbase/cmdline.py
config_
def config_(name: str, local: bool, package: str, section: str, key: Optional[str]): """Extract or list values from config.""" cfg = config.read_configs(package, name, local=local) if key: with suppress(NoOptionError, NoSectionError): echo(cfg.get(section, key)) else: ...
python
def config_(name: str, local: bool, package: str, section: str, key: Optional[str]): """Extract or list values from config.""" cfg = config.read_configs(package, name, local=local) if key: with suppress(NoOptionError, NoSectionError): echo(cfg.get(section, key)) else: ...
[ "def", "config_", "(", "name", ":", "str", ",", "local", ":", "bool", ",", "package", ":", "str", ",", "section", ":", "str", ",", "key", ":", "Optional", "[", "str", "]", ")", ":", "cfg", "=", "config", ".", "read_configs", "(", "package", ",", ...
Extract or list values from config.
[ "Extract", "or", "list", "values", "from", "config", "." ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L97-L108
JNRowe/jnrbase
jnrbase/cmdline.py
find_tag
def find_tag(match: str, strict: bool, directory: str): """Find tag for git repository.""" with suppress(CalledProcessError): echo(git.find_tag(match, strict=strict, git_dir=directory))
python
def find_tag(match: str, strict: bool, directory: str): """Find tag for git repository.""" with suppress(CalledProcessError): echo(git.find_tag(match, strict=strict, git_dir=directory))
[ "def", "find_tag", "(", "match", ":", "str", ",", "strict", ":", "bool", ",", "directory", ":", "str", ")", ":", "with", "suppress", "(", "CalledProcessError", ")", ":", "echo", "(", "git", ".", "find_tag", "(", "match", ",", "strict", "=", "strict", ...
Find tag for git repository.
[ "Find", "tag", "for", "git", "repository", "." ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L117-L120
JNRowe/jnrbase
jnrbase/cmdline.py
pretty_time
def pretty_time(timestamp: str): """Format timestamp for human consumption.""" try: parsed = iso_8601.parse_datetime(timestamp) except ValueError: now = datetime.utcnow().replace(tzinfo=timezone.utc) try: delta = iso_8601.parse_delta(timestamp) except ValueError: ...
python
def pretty_time(timestamp: str): """Format timestamp for human consumption.""" try: parsed = iso_8601.parse_datetime(timestamp) except ValueError: now = datetime.utcnow().replace(tzinfo=timezone.utc) try: delta = iso_8601.parse_delta(timestamp) except ValueError: ...
[ "def", "pretty_time", "(", "timestamp", ":", "str", ")", ":", "try", ":", "parsed", "=", "iso_8601", ".", "parse_datetime", "(", "timestamp", ")", "except", "ValueError", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo"...
Format timestamp for human consumption.
[ "Format", "timestamp", "for", "human", "consumption", "." ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L131-L143
JNRowe/jnrbase
jnrbase/cmdline.py
pip_requires
def pip_requires(name: str): """Parse pip requirements file.""" requires = pip_support.parse_requires(name) for req in requires: echo(req)
python
def pip_requires(name: str): """Parse pip requirements file.""" requires = pip_support.parse_requires(name) for req in requires: echo(req)
[ "def", "pip_requires", "(", "name", ":", "str", ")", ":", "requires", "=", "pip_support", ".", "parse_requires", "(", "name", ")", "for", "req", "in", "requires", ":", "echo", "(", "req", ")" ]
Parse pip requirements file.
[ "Parse", "pip", "requirements", "file", "." ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L148-L152
JNRowe/jnrbase
jnrbase/cmdline.py
gen_text
def gen_text(env: TextIOBase, package: str, tmpl: str): """Create output from Jinja template.""" if env: env_args = json_datetime.load(env) else: env_args = {} jinja_env = template.setup(package) echo(jinja_env.get_template(tmpl).render(**env_args))
python
def gen_text(env: TextIOBase, package: str, tmpl: str): """Create output from Jinja template.""" if env: env_args = json_datetime.load(env) else: env_args = {} jinja_env = template.setup(package) echo(jinja_env.get_template(tmpl).render(**env_args))
[ "def", "gen_text", "(", "env", ":", "TextIOBase", ",", "package", ":", "str", ",", "tmpl", ":", "str", ")", ":", "if", "env", ":", "env_args", "=", "json_datetime", ".", "load", "(", "env", ")", "else", ":", "env_args", "=", "{", "}", "jinja_env", ...
Create output from Jinja template.
[ "Create", "output", "from", "Jinja", "template", "." ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L160-L167
JNRowe/jnrbase
jnrbase/cmdline.py
time
def time(ctx: Context, command: str): """Time the output of a command.""" with timer.Timing(verbose=True): proc = run(command, shell=True) ctx.exit(proc.returncode)
python
def time(ctx: Context, command: str): """Time the output of a command.""" with timer.Timing(verbose=True): proc = run(command, shell=True) ctx.exit(proc.returncode)
[ "def", "time", "(", "ctx", ":", "Context", ",", "command", ":", "str", ")", ":", "with", "timer", ".", "Timing", "(", "verbose", "=", "True", ")", ":", "proc", "=", "run", "(", "command", ",", "shell", "=", "True", ")", "ctx", ".", "exit", "(", ...
Time the output of a command.
[ "Time", "the", "output", "of", "a", "command", "." ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L173-L177
zerok/zs.bibtex
src/zs/bibtex/structures.py
TypeRegistry.register
def register(cls, name, type_): """ Register a new type for an entry-type. The 2nd argument has to be a subclass of structures.Entry. """ if not issubclass(type_, Entry): raise exceptions.InvalidEntryType("%s is not a subclass of Entry" % str(type_)) cls._reg...
python
def register(cls, name, type_): """ Register a new type for an entry-type. The 2nd argument has to be a subclass of structures.Entry. """ if not issubclass(type_, Entry): raise exceptions.InvalidEntryType("%s is not a subclass of Entry" % str(type_)) cls._reg...
[ "def", "register", "(", "cls", ",", "name", ",", "type_", ")", ":", "if", "not", "issubclass", "(", "type_", ",", "Entry", ")", ":", "raise", "exceptions", ".", "InvalidEntryType", "(", "\"%s is not a subclass of Entry\"", "%", "str", "(", "type_", ")", ")...
Register a new type for an entry-type. The 2nd argument has to be a subclass of structures.Entry.
[ "Register", "a", "new", "type", "for", "an", "entry", "-", "type", ".", "The", "2nd", "argument", "has", "to", "be", "a", "subclass", "of", "structures", ".", "Entry", "." ]
train
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/structures.py#L51-L59
zerok/zs.bibtex
src/zs/bibtex/structures.py
Bibliography.validate
def validate(self, **kwargs): """ Validates each entry (passing the provided arguments down to them and also tries to resolve all cross-references between the entries. """ self.check_crossrefs() for value in self.values(): value.validate(**kwargs)
python
def validate(self, **kwargs): """ Validates each entry (passing the provided arguments down to them and also tries to resolve all cross-references between the entries. """ self.check_crossrefs() for value in self.values(): value.validate(**kwargs)
[ "def", "validate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "check_crossrefs", "(", ")", "for", "value", "in", "self", ".", "values", "(", ")", ":", "value", ".", "validate", "(", "*", "*", "kwargs", ")" ]
Validates each entry (passing the provided arguments down to them and also tries to resolve all cross-references between the entries.
[ "Validates", "each", "entry", "(", "passing", "the", "provided", "arguments", "down", "to", "them", "and", "also", "tries", "to", "resolve", "all", "cross", "-", "references", "between", "the", "entries", "." ]
train
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/structures.py#L79-L86
zerok/zs.bibtex
src/zs/bibtex/structures.py
Bibliography.check_crossrefs
def check_crossrefs(self): """ Checks all crossreferences found in the bibliography. If one can not be resolved from *this* Bibliography instance, a BrokenCrossReferences exception is raised. """ broken = [] for value in self.values(): crossref = value...
python
def check_crossrefs(self): """ Checks all crossreferences found in the bibliography. If one can not be resolved from *this* Bibliography instance, a BrokenCrossReferences exception is raised. """ broken = [] for value in self.values(): crossref = value...
[ "def", "check_crossrefs", "(", "self", ")", ":", "broken", "=", "[", "]", "for", "value", "in", "self", ".", "values", "(", ")", ":", "crossref", "=", "value", ".", "get", "(", "'crossref'", ")", "if", "crossref", "is", "not", "None", ":", "if", "c...
Checks all crossreferences found in the bibliography. If one can not be resolved from *this* Bibliography instance, a BrokenCrossReferences exception is raised.
[ "Checks", "all", "crossreferences", "found", "in", "the", "bibliography", ".", "If", "one", "can", "not", "be", "resolved", "from", "*", "this", "*", "Bibliography", "instance", "a", "BrokenCrossReferences", "exception", "is", "raised", "." ]
train
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/structures.py#L88-L102
zerok/zs.bibtex
src/zs/bibtex/structures.py
Entry.validate
def validate(self, raise_unsupported=False): """ Checks if the Entry instance includes all the required fields of its type. If ``raise_unsupported`` is set to ``True`` it will also check for potentially unsupported types. If a problem is found, an InvalidStructure exception is r...
python
def validate(self, raise_unsupported=False): """ Checks if the Entry instance includes all the required fields of its type. If ``raise_unsupported`` is set to ``True`` it will also check for potentially unsupported types. If a problem is found, an InvalidStructure exception is r...
[ "def", "validate", "(", "self", ",", "raise_unsupported", "=", "False", ")", ":", "fields", "=", "set", "(", "self", ".", "keys", "(", ")", ")", "flattened_required_fields", "=", "set", "(", ")", "required_errors", "=", "[", "]", "for", "field", "in", ...
Checks if the Entry instance includes all the required fields of its type. If ``raise_unsupported`` is set to ``True`` it will also check for potentially unsupported types. If a problem is found, an InvalidStructure exception is raised.
[ "Checks", "if", "the", "Entry", "instance", "includes", "all", "the", "required", "fields", "of", "its", "type", ".", "If", "raise_unsupported", "is", "set", "to", "True", "it", "will", "also", "check", "for", "potentially", "unsupported", "types", "." ]
train
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/structures.py#L125-L156
nsavch/python-xonotic-db
xon_db/cli.py
dump
def dump(file_name, pattern): """ Print all keys and values where key matches PATTERN. Default pattern is * (all keys) """ db = XonoticDB.load_path(file_name) items = sorted(db.filter(pattern), key=lambda x: natural_sort_key(x[0])) for k, v in items: click.echo('%s: %s' % (k, v))
python
def dump(file_name, pattern): """ Print all keys and values where key matches PATTERN. Default pattern is * (all keys) """ db = XonoticDB.load_path(file_name) items = sorted(db.filter(pattern), key=lambda x: natural_sort_key(x[0])) for k, v in items: click.echo('%s: %s' % (k, v))
[ "def", "dump", "(", "file_name", ",", "pattern", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "items", "=", "sorted", "(", "db", ".", "filter", "(", "pattern", ")", ",", "key", "=", "lambda", "x", ":", "natural_sort_key", ...
Print all keys and values where key matches PATTERN. Default pattern is * (all keys)
[ "Print", "all", "keys", "and", "values", "where", "key", "matches", "PATTERN", ".", "Default", "pattern", "is", "*", "(", "all", "keys", ")" ]
train
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L18-L25
nsavch/python-xonotic-db
xon_db/cli.py
get
def get(file_name, key): """ Print a value for the specified key. If key is not found xon_db exists with code 1. """ db = XonoticDB.load_path(file_name) value = db.get(key) if value is None: sys.exit(1) else: click.echo(value)
python
def get(file_name, key): """ Print a value for the specified key. If key is not found xon_db exists with code 1. """ db = XonoticDB.load_path(file_name) value = db.get(key) if value is None: sys.exit(1) else: click.echo(value)
[ "def", "get", "(", "file_name", ",", "key", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "value", "=", "db", ".", "get", "(", "key", ")", "if", "value", "is", "None", ":", "sys", ".", "exit", "(", "1", ")", "else", ...
Print a value for the specified key. If key is not found xon_db exists with code 1.
[ "Print", "a", "value", "for", "the", "specified", "key", ".", "If", "key", "is", "not", "found", "xon_db", "exists", "with", "code", "1", "." ]
train
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L31-L40
nsavch/python-xonotic-db
xon_db/cli.py
set
def set(file_name, key, value, new): """ Set a new value for the specified key. """ db = XonoticDB.load_path(file_name) if key not in db and not new: click.echo('Key %s is not found in the database' % key, file=sys.stderr) sys.exit(1) else: db[key] = value db.save...
python
def set(file_name, key, value, new): """ Set a new value for the specified key. """ db = XonoticDB.load_path(file_name) if key not in db and not new: click.echo('Key %s is not found in the database' % key, file=sys.stderr) sys.exit(1) else: db[key] = value db.save...
[ "def", "set", "(", "file_name", ",", "key", ",", "value", ",", "new", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "if", "key", "not", "in", "db", "and", "not", "new", ":", "click", ".", "echo", "(", "'Key %s is not foun...
Set a new value for the specified key.
[ "Set", "a", "new", "value", "for", "the", "specified", "key", "." ]
train
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L48-L58
nsavch/python-xonotic-db
xon_db/cli.py
remove_cts_record
def remove_cts_record(file_name, map, position): """ Remove cts record on MAP and POSITION """ db = XonoticDB.load_path(file_name) db.remove_cts_record(map, position) db.save(file_name)
python
def remove_cts_record(file_name, map, position): """ Remove cts record on MAP and POSITION """ db = XonoticDB.load_path(file_name) db.remove_cts_record(map, position) db.save(file_name)
[ "def", "remove_cts_record", "(", "file_name", ",", "map", ",", "position", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "db", ".", "remove_cts_record", "(", "map", ",", "position", ")", "db", ".", "save", "(", "file_name", "...
Remove cts record on MAP and POSITION
[ "Remove", "cts", "record", "on", "MAP", "and", "POSITION" ]
train
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L65-L71
nsavch/python-xonotic-db
xon_db/cli.py
remove_all_cts_records_by
def remove_all_cts_records_by(file_name, crypto_idfp): """ Remove all cts records set by player with CRYPTO_IDFP """ db = XonoticDB.load_path(file_name) db.remove_all_cts_records_by(crypto_idfp) db.save(file_name)
python
def remove_all_cts_records_by(file_name, crypto_idfp): """ Remove all cts records set by player with CRYPTO_IDFP """ db = XonoticDB.load_path(file_name) db.remove_all_cts_records_by(crypto_idfp) db.save(file_name)
[ "def", "remove_all_cts_records_by", "(", "file_name", ",", "crypto_idfp", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "db", ".", "remove_all_cts_records_by", "(", "crypto_idfp", ")", "db", ".", "save", "(", "file_name", ")" ]
Remove all cts records set by player with CRYPTO_IDFP
[ "Remove", "all", "cts", "records", "set", "by", "player", "with", "CRYPTO_IDFP" ]
train
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L77-L83
nsavch/python-xonotic-db
xon_db/cli.py
merge_cts_records
def merge_cts_records(file_name, crypto_idfp, crypto_idfps): """ Merge cts records made by CRYPTO_IDFPS to CRYPTO_IDFP """ db = XonoticDB.load_path(file_name) db.merge_cts_records(crypto_idfp, crypto_idfps) db.save(file_name)
python
def merge_cts_records(file_name, crypto_idfp, crypto_idfps): """ Merge cts records made by CRYPTO_IDFPS to CRYPTO_IDFP """ db = XonoticDB.load_path(file_name) db.merge_cts_records(crypto_idfp, crypto_idfps) db.save(file_name)
[ "def", "merge_cts_records", "(", "file_name", ",", "crypto_idfp", ",", "crypto_idfps", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "db", ".", "merge_cts_records", "(", "crypto_idfp", ",", "crypto_idfps", ")", "db", ".", "save", ...
Merge cts records made by CRYPTO_IDFPS to CRYPTO_IDFP
[ "Merge", "cts", "records", "made", "by", "CRYPTO_IDFPS", "to", "CRYPTO_IDFP" ]
train
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L90-L96
Arvedui/picuplib
picuplib/checks.py
check_rotation
def check_rotation(rotation): """checks rotation parameter if illegal value raises exception""" if rotation not in ALLOWED_ROTATION: allowed_rotation = ', '.join(ALLOWED_ROTATION) raise UnsupportedRotation('Rotation %s is not allwoed. Allowed are %s' % (rotatio...
python
def check_rotation(rotation): """checks rotation parameter if illegal value raises exception""" if rotation not in ALLOWED_ROTATION: allowed_rotation = ', '.join(ALLOWED_ROTATION) raise UnsupportedRotation('Rotation %s is not allwoed. Allowed are %s' % (rotatio...
[ "def", "check_rotation", "(", "rotation", ")", ":", "if", "rotation", "not", "in", "ALLOWED_ROTATION", ":", "allowed_rotation", "=", "', '", ".", "join", "(", "ALLOWED_ROTATION", ")", "raise", "UnsupportedRotation", "(", "'Rotation %s is not allwoed. Allowed are %s'", ...
checks rotation parameter if illegal value raises exception
[ "checks", "rotation", "parameter", "if", "illegal", "value", "raises", "exception" ]
train
https://github.com/Arvedui/picuplib/blob/c8a5d1542dbd421e84afd5ee81fe76efec89fb95/picuplib/checks.py#L31-L37
Arvedui/picuplib
picuplib/checks.py
check_resize
def check_resize(resize): """checks resize parameter if illegal value raises exception""" if resize is None: return resize = resize.lower().strip() if 'x' in resize: tmp = resize.lower().split('x') tmp = [x.strip() for x in resize.split('x')] if len(tmp) == 2 and tmp[0]...
python
def check_resize(resize): """checks resize parameter if illegal value raises exception""" if resize is None: return resize = resize.lower().strip() if 'x' in resize: tmp = resize.lower().split('x') tmp = [x.strip() for x in resize.split('x')] if len(tmp) == 2 and tmp[0]...
[ "def", "check_resize", "(", "resize", ")", ":", "if", "resize", "is", "None", ":", "return", "resize", "=", "resize", ".", "lower", "(", ")", ".", "strip", "(", ")", "if", "'x'", "in", "resize", ":", "tmp", "=", "resize", ".", "lower", "(", ")", ...
checks resize parameter if illegal value raises exception
[ "checks", "resize", "parameter", "if", "illegal", "value", "raises", "exception" ]
train
https://github.com/Arvedui/picuplib/blob/c8a5d1542dbd421e84afd5ee81fe76efec89fb95/picuplib/checks.py#L40-L62
Arvedui/picuplib
picuplib/checks.py
check_response
def check_response(response): """ checks the response if the server returned an error raises an exception. """ if response.status_code < 200 or response.status_code > 300: raise ServerError('API requests returned with error: %s' % response.status_code) try: ...
python
def check_response(response): """ checks the response if the server returned an error raises an exception. """ if response.status_code < 200 or response.status_code > 300: raise ServerError('API requests returned with error: %s' % response.status_code) try: ...
[ "def", "check_response", "(", "response", ")", ":", "if", "response", ".", "status_code", "<", "200", "or", "response", ".", "status_code", ">", "300", ":", "raise", "ServerError", "(", "'API requests returned with error: %s'", "%", "response", ".", "status_code",...
checks the response if the server returned an error raises an exception.
[ "checks", "the", "response", "if", "the", "server", "returned", "an", "error", "raises", "an", "exception", "." ]
train
https://github.com/Arvedui/picuplib/blob/c8a5d1542dbd421e84afd5ee81fe76efec89fb95/picuplib/checks.py#L77-L98
Arvedui/picuplib
picuplib/checks.py
check_if_redirect
def check_if_redirect(url): """ checks if server redirects url """ response = head(url, headers={'User-Agent': USER_AGENT}) if response.status_code >= 300 and response.status_code < 400: return response.headers['location'] return None
python
def check_if_redirect(url): """ checks if server redirects url """ response = head(url, headers={'User-Agent': USER_AGENT}) if response.status_code >= 300 and response.status_code < 400: return response.headers['location'] return None
[ "def", "check_if_redirect", "(", "url", ")", ":", "response", "=", "head", "(", "url", ",", "headers", "=", "{", "'User-Agent'", ":", "USER_AGENT", "}", ")", "if", "response", ".", "status_code", ">=", "300", "and", "response", ".", "status_code", "<", "...
checks if server redirects url
[ "checks", "if", "server", "redirects", "url" ]
train
https://github.com/Arvedui/picuplib/blob/c8a5d1542dbd421e84afd5ee81fe76efec89fb95/picuplib/checks.py#L101-L109
deviantony/valigator
valigator/scheduler.py
validate_backup
def validate_backup(configuration, backup_data): """Celery task. It will extract the backup archive into a unique folder in the temporary directory specified in the configuration. Once extracted, a Docker container will be started and will start a restoration procedure. The worker will wait for the...
python
def validate_backup(configuration, backup_data): """Celery task. It will extract the backup archive into a unique folder in the temporary directory specified in the configuration. Once extracted, a Docker container will be started and will start a restoration procedure. The worker will wait for the...
[ "def", "validate_backup", "(", "configuration", ",", "backup_data", ")", ":", "extract_archive", "(", "backup_data", "[", "'archive_path'", "]", ",", "backup_data", "[", "'workdir'", "]", ")", "docker_client", "=", "Client", "(", "configuration", "[", "'docker'", ...
Celery task. It will extract the backup archive into a unique folder in the temporary directory specified in the configuration. Once extracted, a Docker container will be started and will start a restoration procedure. The worker will wait for the container to exit and retrieve its return code. ...
[ "Celery", "task", ".", "It", "will", "extract", "the", "backup", "archive", "into", "a", "unique", "folder", "in", "the", "temporary", "directory", "specified", "in", "the", "configuration", "." ]
train
https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/scheduler.py#L11-L38
deviantony/valigator
valigator/scheduler.py
run_container
def run_container(docker_client, backup_data): """Pull the Docker image and creates a container with a '/backup' volume. This volume will be mounted on the temporary workdir previously created. It will then start the container and return the container object. """ docker_client.pull(backup_data[...
python
def run_container(docker_client, backup_data): """Pull the Docker image and creates a container with a '/backup' volume. This volume will be mounted on the temporary workdir previously created. It will then start the container and return the container object. """ docker_client.pull(backup_data[...
[ "def", "run_container", "(", "docker_client", ",", "backup_data", ")", ":", "docker_client", ".", "pull", "(", "backup_data", "[", "'image'", "]", ")", "container", "=", "docker_client", ".", "create_container", "(", "image", "=", "backup_data", "[", "'image'", ...
Pull the Docker image and creates a container with a '/backup' volume. This volume will be mounted on the temporary workdir previously created. It will then start the container and return the container object.
[ "Pull", "the", "Docker", "image", "and", "creates", "a", "container", "with", "a", "/", "backup", "volume", ".", "This", "volume", "will", "be", "mounted", "on", "the", "temporary", "workdir", "previously", "created", "." ]
train
https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/scheduler.py#L41-L61
codecobblers/modified
modified.py
module_files
def module_files(module, dependencies_dict=None): """ Scan a module and its entire dependency tree to create a dict of all files and their modified time. @param module: A <module> object @param dependencies_dict: Pass an existing dict to add only unscanned files or None to create a new file...
python
def module_files(module, dependencies_dict=None): """ Scan a module and its entire dependency tree to create a dict of all files and their modified time. @param module: A <module> object @param dependencies_dict: Pass an existing dict to add only unscanned files or None to create a new file...
[ "def", "module_files", "(", "module", ",", "dependencies_dict", "=", "None", ")", ":", "if", "dependencies_dict", "is", "None", ":", "dependencies_dict", "=", "dict", "(", ")", "if", "hasattr", "(", "module", ",", "'__file__'", ")", ":", "filename", "=", "...
Scan a module and its entire dependency tree to create a dict of all files and their modified time. @param module: A <module> object @param dependencies_dict: Pass an existing dict to add only unscanned files or None to create a new file dict @return: A dict containing filenames as keys with th...
[ "Scan", "a", "module", "and", "its", "entire", "dependency", "tree", "to", "create", "a", "dict", "of", "all", "files", "and", "their", "modified", "time", "." ]
train
https://github.com/codecobblers/modified/blob/1cca9337d4de44fa660d1601ed43b71e00d8b6f5/modified.py#L82-L112
codecobblers/modified
modified.py
files
def files(): """ Scan all modules in the currently running app to create a dict of all files and their modified time. @note The scan only occurs the first time this function is called. Subsequent calls simply return the global dict. @return: A dict containing filenames as keys with their m...
python
def files(): """ Scan all modules in the currently running app to create a dict of all files and their modified time. @note The scan only occurs the first time this function is called. Subsequent calls simply return the global dict. @return: A dict containing filenames as keys with their m...
[ "def", "files", "(", ")", ":", "if", "not", "_scanned", ":", "if", "not", "module_files", "(", "sys", ".", "modules", "[", "'__main__'", "]", ",", "_process_files", ")", ":", "for", "module", "in", "sys", ".", "modules", ".", "values", "(", ")", ":",...
Scan all modules in the currently running app to create a dict of all files and their modified time. @note The scan only occurs the first time this function is called. Subsequent calls simply return the global dict. @return: A dict containing filenames as keys with their modified time as v...
[ "Scan", "all", "modules", "in", "the", "currently", "running", "app", "to", "create", "a", "dict", "of", "all", "files", "and", "their", "modified", "time", "." ]
train
https://github.com/codecobblers/modified/blob/1cca9337d4de44fa660d1601ed43b71e00d8b6f5/modified.py#L115-L135
codecobblers/modified
modified.py
track
def track(*args): """ Track additional files. It is often useful to use glob.glob here. For instance: track('config.ini', glob.glob('templates/*.pt'), glob.glob('db/*.db')) @param args: A list where each element is either a filename or an iterable of filenames """ for arg in ar...
python
def track(*args): """ Track additional files. It is often useful to use glob.glob here. For instance: track('config.ini', glob.glob('templates/*.pt'), glob.glob('db/*.db')) @param args: A list where each element is either a filename or an iterable of filenames """ for arg in ar...
[ "def", "track", "(", "*", "args", ")", ":", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "str", ")", ":", "arg", "=", "[", "arg", "]", "for", "filename", "in", "arg", ":", "realname", ",", "modified_time", "=", "_get_filena...
Track additional files. It is often useful to use glob.glob here. For instance: track('config.ini', glob.glob('templates/*.pt'), glob.glob('db/*.db')) @param args: A list where each element is either a filename or an iterable of filenames
[ "Track", "additional", "files", ".", "It", "is", "often", "useful", "to", "use", "glob", ".", "glob", "here", ".", "For", "instance", ":" ]
train
https://github.com/codecobblers/modified/blob/1cca9337d4de44fa660d1601ed43b71e00d8b6f5/modified.py#L148-L164
codecobblers/modified
modified.py
hup_hook
def hup_hook(signal_or_callable=signal.SIGTERM, verbose=False): """ Register a signal handler for `signal.SIGHUP` that checks for modified files and only acts if at least one modified file is found. @type signal_or_callable: str, int or callable @param signal_or_callable: You can pass either a sign...
python
def hup_hook(signal_or_callable=signal.SIGTERM, verbose=False): """ Register a signal handler for `signal.SIGHUP` that checks for modified files and only acts if at least one modified file is found. @type signal_or_callable: str, int or callable @param signal_or_callable: You can pass either a sign...
[ "def", "hup_hook", "(", "signal_or_callable", "=", "signal", ".", "SIGTERM", ",", "verbose", "=", "False", ")", ":", "#noinspection PyUnusedLocal", "def", "handle_hup", "(", "signum", ",", "frame", ")", ":", "changed", "=", "modified", "(", ")", "if", "chang...
Register a signal handler for `signal.SIGHUP` that checks for modified files and only acts if at least one modified file is found. @type signal_or_callable: str, int or callable @param signal_or_callable: You can pass either a signal or a callable. The signal can be specified by name or number. If ...
[ "Register", "a", "signal", "handler", "for", "signal", ".", "SIGHUP", "that", "checks", "for", "modified", "files", "and", "only", "acts", "if", "at", "least", "one", "modified", "file", "is", "found", "." ]
train
https://github.com/codecobblers/modified/blob/1cca9337d4de44fa660d1601ed43b71e00d8b6f5/modified.py#L167-L225
salimm/msgpack-pystream
msgpackstream/backend/python/stream.py
StreamUnpacker.process
def process(self, buff): ''' Process the input buffer. The buffer can contains all or a segment of the bytes from the complete message. The function will buffer what will require extra bytes to be processed. :param buff: ''' # adding the current to the ...
python
def process(self, buff): ''' Process the input buffer. The buffer can contains all or a segment of the bytes from the complete message. The function will buffer what will require extra bytes to be processed. :param buff: ''' # adding the current to the ...
[ "def", "process", "(", "self", ",", "buff", ")", ":", "# adding the current to the available", "self", ".", "memory", "=", "self", ".", "memory", "+", "buff", "self", ".", "_available", "=", "len", "(", "self", ".", "memory", ")", "idx", "=", "0", "# pre...
Process the input buffer. The buffer can contains all or a segment of the bytes from the complete message. The function will buffer what will require extra bytes to be processed. :param buff:
[ "Process", "the", "input", "buffer", ".", "The", "buffer", "can", "contains", "all", "or", "a", "segment", "of", "the", "bytes", "from", "the", "complete", "message", ".", "The", "function", "will", "buffer", "what", "will", "require", "extra", "bytes", "t...
train
https://github.com/salimm/msgpack-pystream/blob/676158a5a8dd8ff56dca080d597943f67fc4325e/msgpackstream/backend/python/stream.py#L60-L113
salimm/msgpack-pystream
msgpackstream/backend/python/stream.py
StreamUnpacker.handle_read_length
def handle_read_length(self, buff, start, end): ''' handle read of number bytes needed to parse the value :param buff: :param start: :param end: ''' self.set_state_length(self._state, self.parse_uint(buff, start, end) * self._state[1].value.multiplier...
python
def handle_read_length(self, buff, start, end): ''' handle read of number bytes needed to parse the value :param buff: :param start: :param end: ''' self.set_state_length(self._state, self.parse_uint(buff, start, end) * self._state[1].value.multiplier...
[ "def", "handle_read_length", "(", "self", ",", "buff", ",", "start", ",", "end", ")", ":", "self", ".", "set_state_length", "(", "self", ".", "_state", ",", "self", ".", "parse_uint", "(", "buff", ",", "start", ",", "end", ")", "*", "self", ".", "_st...
handle read of number bytes needed to parse the value :param buff: :param start: :param end:
[ "handle", "read", "of", "number", "bytes", "needed", "to", "parse", "the", "value", ":", "param", "buff", ":", ":", "param", "start", ":", ":", "param", "end", ":" ]
train
https://github.com/salimm/msgpack-pystream/blob/676158a5a8dd8ff56dca080d597943f67fc4325e/msgpackstream/backend/python/stream.py#L118-L149
salimm/msgpack-pystream
msgpackstream/backend/python/stream.py
StreamUnpacker.handle_read_value
def handle_read_value(self, buff, start, end): ''' handle read of the value based on the expected length :param buff: :param start: :param end: ''' segmenttype = self._state[1].value.segmenttype value = None eventtype = None ft...
python
def handle_read_value(self, buff, start, end): ''' handle read of the value based on the expected length :param buff: :param start: :param end: ''' segmenttype = self._state[1].value.segmenttype value = None eventtype = None ft...
[ "def", "handle_read_value", "(", "self", ",", "buff", ",", "start", ",", "end", ")", ":", "segmenttype", "=", "self", ".", "_state", "[", "1", "]", ".", "value", ".", "segmenttype", "value", "=", "None", "eventtype", "=", "None", "ftype", "=", "self", ...
handle read of the value based on the expected length :param buff: :param start: :param end:
[ "handle", "read", "of", "the", "value", "based", "on", "the", "expected", "length", ":", "param", "buff", ":", ":", "param", "start", ":", ":", "param", "end", ":" ]
train
https://github.com/salimm/msgpack-pystream/blob/676158a5a8dd8ff56dca080d597943f67fc4325e/msgpackstream/backend/python/stream.py#L153-L177
salimm/msgpack-pystream
msgpackstream/backend/python/stream.py
StreamUnpacker.handle_read_header
def handle_read_header(self, byte): ''' handle read of header and assign fetching the appropriate template that is needed to parse expected segment based on header :param byte: ''' (_, frmtcode, _, frmtidx, val) = self.util.find(byte) template = self._templat...
python
def handle_read_header(self, byte): ''' handle read of header and assign fetching the appropriate template that is needed to parse expected segment based on header :param byte: ''' (_, frmtcode, _, frmtidx, val) = self.util.find(byte) template = self._templat...
[ "def", "handle_read_header", "(", "self", ",", "byte", ")", ":", "(", "_", ",", "frmtcode", ",", "_", ",", "frmtidx", ",", "val", ")", "=", "self", ".", "util", ".", "find", "(", "byte", ")", "template", "=", "self", ".", "_templatelist", "[", "frm...
handle read of header and assign fetching the appropriate template that is needed to parse expected segment based on header :param byte:
[ "handle", "read", "of", "header", "and", "assign", "fetching", "the", "appropriate", "template", "that", "is", "needed", "to", "parse", "expected", "segment", "based", "on", "header", ":", "param", "byte", ":" ]
train
https://github.com/salimm/msgpack-pystream/blob/676158a5a8dd8ff56dca080d597943f67fc4325e/msgpackstream/backend/python/stream.py#L179-L236
salimm/msgpack-pystream
msgpackstream/backend/python/stream.py
StreamUnpacker.handle_segment_ended
def handle_segment_ended(self): ''' process end of the segment based on template ''' if self._state[1].value.endevent is not None: self.events.append((self._state[1].value.endevent, self._state[0], None)) if self._state[1].value.multiplier is 2: self.p...
python
def handle_segment_ended(self): ''' process end of the segment based on template ''' if self._state[1].value.endevent is not None: self.events.append((self._state[1].value.endevent, self._state[0], None)) if self._state[1].value.multiplier is 2: self.p...
[ "def", "handle_segment_ended", "(", "self", ")", ":", "if", "self", ".", "_state", "[", "1", "]", ".", "value", ".", "endevent", "is", "not", "None", ":", "self", ".", "events", ".", "append", "(", "(", "self", ".", "_state", "[", "1", "]", ".", ...
process end of the segment based on template
[ "process", "end", "of", "the", "segment", "based", "on", "template" ]
train
https://github.com/salimm/msgpack-pystream/blob/676158a5a8dd8ff56dca080d597943f67fc4325e/msgpackstream/backend/python/stream.py#L267-L292
salimm/msgpack-pystream
msgpackstream/backend/python/stream.py
StreamUnpacker.parse_value
def parse_value(self, frmtcode, buff, start, end): ''' parse the value from the buffer given the interval for the appropraite bytes :param formattype: :param buff: :param start: :param end: ''' frmttype = self.util._formatmap[frmtcode] ...
python
def parse_value(self, frmtcode, buff, start, end): ''' parse the value from the buffer given the interval for the appropraite bytes :param formattype: :param buff: :param start: :param end: ''' frmttype = self.util._formatmap[frmtcode] ...
[ "def", "parse_value", "(", "self", ",", "frmtcode", ",", "buff", ",", "start", ",", "end", ")", ":", "frmttype", "=", "self", ".", "util", ".", "_formatmap", "[", "frmtcode", "]", "if", "(", "frmtcode", "==", "FormatType", ".", "FLOAT_32", ".", "value"...
parse the value from the buffer given the interval for the appropraite bytes :param formattype: :param buff: :param start: :param end:
[ "parse", "the", "value", "from", "the", "buffer", "given", "the", "interval", "for", "the", "appropraite", "bytes", ":", "param", "formattype", ":", ":", "param", "buff", ":", ":", "param", "start", ":", ":", "param", "end", ":" ]
train
https://github.com/salimm/msgpack-pystream/blob/676158a5a8dd8ff56dca080d597943f67fc4325e/msgpackstream/backend/python/stream.py#L318-L337
salimm/msgpack-pystream
msgpackstream/backend/python/stream.py
StreamUnpacker.parse_uint
def parse_uint(self, buff, start, end): ''' parse an integer from the buffer given the interval of bytes :param buff: :param start: :param end: ''' return struct.unpack_from(self.ustructmap[end - start], buff, start)[0]
python
def parse_uint(self, buff, start, end): ''' parse an integer from the buffer given the interval of bytes :param buff: :param start: :param end: ''' return struct.unpack_from(self.ustructmap[end - start], buff, start)[0]
[ "def", "parse_uint", "(", "self", ",", "buff", ",", "start", ",", "end", ")", ":", "return", "struct", ".", "unpack_from", "(", "self", ".", "ustructmap", "[", "end", "-", "start", "]", ",", "buff", ",", "start", ")", "[", "0", "]" ]
parse an integer from the buffer given the interval of bytes :param buff: :param start: :param end:
[ "parse", "an", "integer", "from", "the", "buffer", "given", "the", "interval", "of", "bytes", ":", "param", "buff", ":", ":", "param", "start", ":", ":", "param", "end", ":" ]
train
https://github.com/salimm/msgpack-pystream/blob/676158a5a8dd8ff56dca080d597943f67fc4325e/msgpackstream/backend/python/stream.py#L339-L347
davidmiller/letter
letter/__main__.py
main
def main(): """ Do the things! Return: 0 Exceptions: """ description = 'Letter - a commandline interface' parser = argparse.ArgumentParser(description=description) parser.add_argument('--gmail', action='store_true', help='Send via Gmail', ) args = parser.parse_args() to ...
python
def main(): """ Do the things! Return: 0 Exceptions: """ description = 'Letter - a commandline interface' parser = argparse.ArgumentParser(description=description) parser.add_argument('--gmail', action='store_true', help='Send via Gmail', ) args = parser.parse_args() to ...
[ "def", "main", "(", ")", ":", "description", "=", "'Letter - a commandline interface'", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "description", ")", "parser", ".", "add_argument", "(", "'--gmail'", ",", "action", "=", "'store_true...
Do the things! Return: 0 Exceptions:
[ "Do", "the", "things!" ]
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__main__.py#L10-L44