id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
39,400 | standage/tag | tag/transcript.py | _emplace_pmrna | def _emplace_pmrna(mrnas, parent, strict=False):
"""Retrieve the primary mRNA and discard all others."""
mrnas.sort(key=lambda m: (m.cdslen, m.get_attribute('ID')))
pmrna = mrnas.pop()
if strict:
parent.children = [pmrna]
else:
parent.children = [c for c in parent.children if c not i... | python | def _emplace_pmrna(mrnas, parent, strict=False):
"""Retrieve the primary mRNA and discard all others."""
mrnas.sort(key=lambda m: (m.cdslen, m.get_attribute('ID')))
pmrna = mrnas.pop()
if strict:
parent.children = [pmrna]
else:
parent.children = [c for c in parent.children if c not i... | [
"def",
"_emplace_pmrna",
"(",
"mrnas",
",",
"parent",
",",
"strict",
"=",
"False",
")",
":",
"mrnas",
".",
"sort",
"(",
"key",
"=",
"lambda",
"m",
":",
"(",
"m",
".",
"cdslen",
",",
"m",
".",
"get_attribute",
"(",
"'ID'",
")",
")",
")",
"pmrna",
... | Retrieve the primary mRNA and discard all others. | [
"Retrieve",
"the",
"primary",
"mRNA",
"and",
"discard",
"all",
"others",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L29-L36 |
39,401 | standage/tag | tag/transcript.py | _emplace_transcript | def _emplace_transcript(transcripts, parent):
"""Retrieve the primary transcript and discard all others."""
transcripts.sort(key=lambda t: (len(t), t.get_attribute('ID')))
pt = transcripts.pop()
parent.children = [pt] | python | def _emplace_transcript(transcripts, parent):
"""Retrieve the primary transcript and discard all others."""
transcripts.sort(key=lambda t: (len(t), t.get_attribute('ID')))
pt = transcripts.pop()
parent.children = [pt] | [
"def",
"_emplace_transcript",
"(",
"transcripts",
",",
"parent",
")",
":",
"transcripts",
".",
"sort",
"(",
"key",
"=",
"lambda",
"t",
":",
"(",
"len",
"(",
"t",
")",
",",
"t",
".",
"get_attribute",
"(",
"'ID'",
")",
")",
")",
"pt",
"=",
"transcripts... | Retrieve the primary transcript and discard all others. | [
"Retrieve",
"the",
"primary",
"transcript",
"and",
"discard",
"all",
"others",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L39-L43 |
39,402 | standage/tag | tag/transcript.py | primary_mrna | def primary_mrna(entrystream, parenttype='gene'):
"""
Select a single mRNA as a representative for each protein-coding gene.
The primary mRNA is the one with the longest translation product. In cases
where multiple isoforms have the same translated length, the feature ID is
used for sorting.
T... | python | def primary_mrna(entrystream, parenttype='gene'):
"""
Select a single mRNA as a representative for each protein-coding gene.
The primary mRNA is the one with the longest translation product. In cases
where multiple isoforms have the same translated length, the feature ID is
used for sorting.
T... | [
"def",
"primary_mrna",
"(",
"entrystream",
",",
"parenttype",
"=",
"'gene'",
")",
":",
"for",
"entry",
"in",
"entrystream",
":",
"if",
"not",
"isinstance",
"(",
"entry",
",",
"tag",
".",
"Feature",
")",
":",
"yield",
"entry",
"continue",
"for",
"parent",
... | Select a single mRNA as a representative for each protein-coding gene.
The primary mRNA is the one with the longest translation product. In cases
where multiple isoforms have the same translated length, the feature ID is
used for sorting.
This function **does not** return only mRNA features, it return... | [
"Select",
"a",
"single",
"mRNA",
"as",
"a",
"representative",
"for",
"each",
"protein",
"-",
"coding",
"gene",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L46-L74 |
39,403 | standage/tag | tag/transcript.py | _get_primary_type | def _get_primary_type(ttypes, parent, logstream=stderr):
"""Check for multiple transcript types and, if possible, select one."""
if len(ttypes) > 1:
if logstream: # pragma: no branch
message = '[tag::transcript::primary_transcript]'
message += ' WARNING: feature {:s}'.format(par... | python | def _get_primary_type(ttypes, parent, logstream=stderr):
"""Check for multiple transcript types and, if possible, select one."""
if len(ttypes) > 1:
if logstream: # pragma: no branch
message = '[tag::transcript::primary_transcript]'
message += ' WARNING: feature {:s}'.format(par... | [
"def",
"_get_primary_type",
"(",
"ttypes",
",",
"parent",
",",
"logstream",
"=",
"stderr",
")",
":",
"if",
"len",
"(",
"ttypes",
")",
">",
"1",
":",
"if",
"logstream",
":",
"# pragma: no branch",
"message",
"=",
"'[tag::transcript::primary_transcript]'",
"messag... | Check for multiple transcript types and, if possible, select one. | [
"Check",
"for",
"multiple",
"transcript",
"types",
"and",
"if",
"possible",
"select",
"one",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L77-L93 |
39,404 | standage/tag | tag/transcript.py | primary_transcript | def primary_transcript(entrystream, parenttype='gene', logstream=stderr):
"""
Select a single transcript as a representative for each gene.
This function is a generalization of the `primary_mrna` function that
attempts, under certain conditions, to select a single transcript as a
representative for... | python | def primary_transcript(entrystream, parenttype='gene', logstream=stderr):
"""
Select a single transcript as a representative for each gene.
This function is a generalization of the `primary_mrna` function that
attempts, under certain conditions, to select a single transcript as a
representative for... | [
"def",
"primary_transcript",
"(",
"entrystream",
",",
"parenttype",
"=",
"'gene'",
",",
"logstream",
"=",
"stderr",
")",
":",
"for",
"entry",
"in",
"entrystream",
":",
"if",
"not",
"isinstance",
"(",
"entry",
",",
"tag",
".",
"Feature",
")",
":",
"yield",
... | Select a single transcript as a representative for each gene.
This function is a generalization of the `primary_mrna` function that
attempts, under certain conditions, to select a single transcript as a
representative for each gene. If a gene encodes multiple transcript types,
one of those types must b... | [
"Select",
"a",
"single",
"transcript",
"as",
"a",
"representative",
"for",
"each",
"gene",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L96-L154 |
39,405 | pauleveritt/kaybee | kaybee/plugins/resources/base_resource.py | parse_parent | def parse_parent(docname):
""" Given a docname path, pick apart and return name of parent """
lineage = docname.split('/')
lineage_count = len(lineage)
if docname == 'index':
# This is the top of the Sphinx project
parent = None
elif lineage_count == 1:
# This is a non-inde... | python | def parse_parent(docname):
""" Given a docname path, pick apart and return name of parent """
lineage = docname.split('/')
lineage_count = len(lineage)
if docname == 'index':
# This is the top of the Sphinx project
parent = None
elif lineage_count == 1:
# This is a non-inde... | [
"def",
"parse_parent",
"(",
"docname",
")",
":",
"lineage",
"=",
"docname",
".",
"split",
"(",
"'/'",
")",
"lineage_count",
"=",
"len",
"(",
"lineage",
")",
"if",
"docname",
"==",
"'index'",
":",
"# This is the top of the Sphinx project",
"parent",
"=",
"None"... | Given a docname path, pick apart and return name of parent | [
"Given",
"a",
"docname",
"path",
"pick",
"apart",
"and",
"return",
"name",
"of",
"parent"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/base_resource.py#L8-L33 |
39,406 | pauleveritt/kaybee | kaybee/plugins/resources/base_resource.py | BaseResource.parents | def parents(self, resources):
""" Split the path in name and get parents """
if self.docname == 'index':
# The root has no parents
return []
parents = []
parent = resources.get(self.parent)
while parent is not None:
parents.append(parent)
... | python | def parents(self, resources):
""" Split the path in name and get parents """
if self.docname == 'index':
# The root has no parents
return []
parents = []
parent = resources.get(self.parent)
while parent is not None:
parents.append(parent)
... | [
"def",
"parents",
"(",
"self",
",",
"resources",
")",
":",
"if",
"self",
".",
"docname",
"==",
"'index'",
":",
"# The root has no parents",
"return",
"[",
"]",
"parents",
"=",
"[",
"]",
"parent",
"=",
"resources",
".",
"get",
"(",
"self",
".",
"parent",
... | Split the path in name and get parents | [
"Split",
"the",
"path",
"in",
"name",
"and",
"get",
"parents"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/base_resource.py#L63-L74 |
39,407 | pauleveritt/kaybee | kaybee/plugins/resources/base_resource.py | BaseResource.acquire | def acquire(self, resources, prop_name):
""" Starting with self, walk until you find prop or None """
# Instance
custom_prop = getattr(self.props, prop_name, None)
if custom_prop:
return custom_prop
# Parents...can't use acquire as have to keep going on acquireds
... | python | def acquire(self, resources, prop_name):
""" Starting with self, walk until you find prop or None """
# Instance
custom_prop = getattr(self.props, prop_name, None)
if custom_prop:
return custom_prop
# Parents...can't use acquire as have to keep going on acquireds
... | [
"def",
"acquire",
"(",
"self",
",",
"resources",
",",
"prop_name",
")",
":",
"# Instance",
"custom_prop",
"=",
"getattr",
"(",
"self",
".",
"props",
",",
"prop_name",
",",
"None",
")",
"if",
"custom_prop",
":",
"return",
"custom_prop",
"# Parents...can't use a... | Starting with self, walk until you find prop or None | [
"Starting",
"with",
"self",
"walk",
"until",
"you",
"find",
"prop",
"or",
"None"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/base_resource.py#L76-L102 |
39,408 | pauleveritt/kaybee | kaybee/plugins/resources/base_resource.py | BaseResource.find_prop_item | def find_prop_item(self, prop_name, prop_key, prop_value):
""" Look for a list prop with an item where key == value """
# Image props are a sequence of dicts. We often need one of them.
# Where one of the items has a dict key matching a value, and if
# nothing matches, return None
... | python | def find_prop_item(self, prop_name, prop_key, prop_value):
""" Look for a list prop with an item where key == value """
# Image props are a sequence of dicts. We often need one of them.
# Where one of the items has a dict key matching a value, and if
# nothing matches, return None
... | [
"def",
"find_prop_item",
"(",
"self",
",",
"prop_name",
",",
"prop_key",
",",
"prop_value",
")",
":",
"# Image props are a sequence of dicts. We often need one of them.",
"# Where one of the items has a dict key matching a value, and if",
"# nothing matches, return None",
"prop",
"="... | Look for a list prop with an item where key == value | [
"Look",
"for",
"a",
"list",
"prop",
"with",
"an",
"item",
"where",
"key",
"==",
"value"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/base_resource.py#L120-L134 |
39,409 | Prev/shaman | shamanld/shaman.py | Shaman.detect | def detect(self, code) :
""" Detect language with code
"""
keywords = KeywordFetcher.fetch( code )
probabilities = {}
for keyword in keywords :
if keyword not in self.trained_set['keywords'] :
continue
data = self.trained_set['keywords'][keyword]
p_avg = sum(data.values()) / len(data) # Aver... | python | def detect(self, code) :
""" Detect language with code
"""
keywords = KeywordFetcher.fetch( code )
probabilities = {}
for keyword in keywords :
if keyword not in self.trained_set['keywords'] :
continue
data = self.trained_set['keywords'][keyword]
p_avg = sum(data.values()) / len(data) # Aver... | [
"def",
"detect",
"(",
"self",
",",
"code",
")",
":",
"keywords",
"=",
"KeywordFetcher",
".",
"fetch",
"(",
"code",
")",
"probabilities",
"=",
"{",
"}",
"for",
"keyword",
"in",
"keywords",
":",
"if",
"keyword",
"not",
"in",
"self",
".",
"trained_set",
"... | Detect language with code | [
"Detect",
"language",
"with",
"code"
] | 82891c17c6302f7f9881a215789856d460a85f9c | https://github.com/Prev/shaman/blob/82891c17c6302f7f9881a215789856d460a85f9c/shamanld/shaman.py#L43-L84 |
39,410 | Prev/shaman | shamanld/shaman.py | KeywordFetcher.fetch | def fetch(code) :
""" Fetch keywords by Code
"""
ret = {}
code = KeywordFetcher._remove_strings(code)
result = KeywordFetcher.prog.findall(code)
for keyword in result :
if len(keyword) <= 1: continue # Ignore single-length word
if keyword.isdigit(): continue # Ignore number
if keyword[0] == '-' ... | python | def fetch(code) :
""" Fetch keywords by Code
"""
ret = {}
code = KeywordFetcher._remove_strings(code)
result = KeywordFetcher.prog.findall(code)
for keyword in result :
if len(keyword) <= 1: continue # Ignore single-length word
if keyword.isdigit(): continue # Ignore number
if keyword[0] == '-' ... | [
"def",
"fetch",
"(",
"code",
")",
":",
"ret",
"=",
"{",
"}",
"code",
"=",
"KeywordFetcher",
".",
"_remove_strings",
"(",
"code",
")",
"result",
"=",
"KeywordFetcher",
".",
"prog",
".",
"findall",
"(",
"code",
")",
"for",
"keyword",
"in",
"result",
":",... | Fetch keywords by Code | [
"Fetch",
"keywords",
"by",
"Code"
] | 82891c17c6302f7f9881a215789856d460a85f9c | https://github.com/Prev/shaman/blob/82891c17c6302f7f9881a215789856d460a85f9c/shamanld/shaman.py#L92-L111 |
39,411 | Prev/shaman | shamanld/shaman.py | KeywordFetcher._remove_strings | def _remove_strings(code) :
""" Remove strings in code
"""
removed_string = ""
is_string_now = None
for i in range(0, len(code)-1) :
append_this_turn = False
if code[i] == "'" and (i == 0 or code[i-1] != '\\') :
if is_string_now == "'" :
is_string_now = None
elif is_string_now == None ... | python | def _remove_strings(code) :
""" Remove strings in code
"""
removed_string = ""
is_string_now = None
for i in range(0, len(code)-1) :
append_this_turn = False
if code[i] == "'" and (i == 0 or code[i-1] != '\\') :
if is_string_now == "'" :
is_string_now = None
elif is_string_now == None ... | [
"def",
"_remove_strings",
"(",
"code",
")",
":",
"removed_string",
"=",
"\"\"",
"is_string_now",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"code",
")",
"-",
"1",
")",
":",
"append_this_turn",
"=",
"False",
"if",
"code",
"[",
... | Remove strings in code | [
"Remove",
"strings",
"in",
"code"
] | 82891c17c6302f7f9881a215789856d460a85f9c | https://github.com/Prev/shaman/blob/82891c17c6302f7f9881a215789856d460a85f9c/shamanld/shaman.py#L115-L144 |
39,412 | Prev/shaman | shamanld/shaman.py | PatternMatcher.getratio | def getratio(self, code) :
""" Get ratio of code and pattern matched
"""
if len(code) == 0 : return 0
code_replaced = self.prog.sub('', code)
return (len(code) - len(code_replaced)) / len(code) | python | def getratio(self, code) :
""" Get ratio of code and pattern matched
"""
if len(code) == 0 : return 0
code_replaced = self.prog.sub('', code)
return (len(code) - len(code_replaced)) / len(code) | [
"def",
"getratio",
"(",
"self",
",",
"code",
")",
":",
"if",
"len",
"(",
"code",
")",
"==",
"0",
":",
"return",
"0",
"code_replaced",
"=",
"self",
".",
"prog",
".",
"sub",
"(",
"''",
",",
"code",
")",
"return",
"(",
"len",
"(",
"code",
")",
"-"... | Get ratio of code and pattern matched | [
"Get",
"ratio",
"of",
"code",
"and",
"pattern",
"matched"
] | 82891c17c6302f7f9881a215789856d460a85f9c | https://github.com/Prev/shaman/blob/82891c17c6302f7f9881a215789856d460a85f9c/shamanld/shaman.py#L167-L173 |
39,413 | bitesofcode/projex | projex/xmlutil.py | XmlObject.loadXmlProperty | def loadXmlProperty(self, xprop):
"""
Loads an XML property that is a child of the root data being loaded.
:param xprop | <xml.etree.ElementTree.Element>
"""
if xprop.tag == 'property':
value = self.dataInterface().fromXml(xprop[0])
self._xmlData[xpr... | python | def loadXmlProperty(self, xprop):
"""
Loads an XML property that is a child of the root data being loaded.
:param xprop | <xml.etree.ElementTree.Element>
"""
if xprop.tag == 'property':
value = self.dataInterface().fromXml(xprop[0])
self._xmlData[xpr... | [
"def",
"loadXmlProperty",
"(",
"self",
",",
"xprop",
")",
":",
"if",
"xprop",
".",
"tag",
"==",
"'property'",
":",
"value",
"=",
"self",
".",
"dataInterface",
"(",
")",
".",
"fromXml",
"(",
"xprop",
"[",
"0",
"]",
")",
"self",
".",
"_xmlData",
"[",
... | Loads an XML property that is a child of the root data being loaded.
:param xprop | <xml.etree.ElementTree.Element> | [
"Loads",
"an",
"XML",
"property",
"that",
"is",
"a",
"child",
"of",
"the",
"root",
"data",
"being",
"loaded",
"."
] | d31743ec456a41428709968ab11a2cf6c6c76247 | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xmlutil.py#L38-L46 |
39,414 | bitesofcode/projex | projex/xmlutil.py | XmlObject.toXml | def toXml(self, xparent=None):
"""
Converts this object to XML.
:param xparent | <xml.etree.ElementTree.Element> || None
:return <xml.etree.ElementTree.Element>
"""
if xparent is None:
xml = ElementTree.Element('object')
else:
xm... | python | def toXml(self, xparent=None):
"""
Converts this object to XML.
:param xparent | <xml.etree.ElementTree.Element> || None
:return <xml.etree.ElementTree.Element>
"""
if xparent is None:
xml = ElementTree.Element('object')
else:
xm... | [
"def",
"toXml",
"(",
"self",
",",
"xparent",
"=",
"None",
")",
":",
"if",
"xparent",
"is",
"None",
":",
"xml",
"=",
"ElementTree",
".",
"Element",
"(",
"'object'",
")",
"else",
":",
"xml",
"=",
"ElementTree",
".",
"SubElement",
"(",
"xparent",
",",
"... | Converts this object to XML.
:param xparent | <xml.etree.ElementTree.Element> || None
:return <xml.etree.ElementTree.Element> | [
"Converts",
"this",
"object",
"to",
"XML",
"."
] | d31743ec456a41428709968ab11a2cf6c6c76247 | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xmlutil.py#L57-L75 |
39,415 | bitesofcode/projex | projex/xmlutil.py | XmlObject.fromXml | def fromXml(cls, xml):
"""
Restores an object from XML.
:param xml | <xml.etree.ElementTree.Element>
:return subclass of <XmlObject>
"""
clsname = xml.get('class')
if clsname:
subcls = XmlObject.byName(clsname)
if subcls is None:... | python | def fromXml(cls, xml):
"""
Restores an object from XML.
:param xml | <xml.etree.ElementTree.Element>
:return subclass of <XmlObject>
"""
clsname = xml.get('class')
if clsname:
subcls = XmlObject.byName(clsname)
if subcls is None:... | [
"def",
"fromXml",
"(",
"cls",
",",
"xml",
")",
":",
"clsname",
"=",
"xml",
".",
"get",
"(",
"'class'",
")",
"if",
"clsname",
":",
"subcls",
"=",
"XmlObject",
".",
"byName",
"(",
"clsname",
")",
"if",
"subcls",
"is",
"None",
":",
"inst",
"=",
"Missi... | Restores an object from XML.
:param xml | <xml.etree.ElementTree.Element>
:return subclass of <XmlObject> | [
"Restores",
"an",
"object",
"from",
"XML",
"."
] | d31743ec456a41428709968ab11a2cf6c6c76247 | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xmlutil.py#L86-L105 |
39,416 | e7dal/bubble3 | behave4cmd0/textutil.py | template_substitute | def template_substitute(text, **kwargs):
"""
Replace placeholders in text by using the data mapping.
Other placeholders that is not represented by data is left untouched.
:param text: Text to search and replace placeholders.
:param data: Data mapping/dict for placeholder key and values.
:re... | python | def template_substitute(text, **kwargs):
"""
Replace placeholders in text by using the data mapping.
Other placeholders that is not represented by data is left untouched.
:param text: Text to search and replace placeholders.
:param data: Data mapping/dict for placeholder key and values.
:re... | [
"def",
"template_substitute",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"name",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"placeholder_pattern",
"=",
"\"{%s}\"",
"%",
"name",
"if",
"placeholder_pattern",
"in",
"text",
":",
"... | Replace placeholders in text by using the data mapping.
Other placeholders that is not represented by data is left untouched.
:param text: Text to search and replace placeholders.
:param data: Data mapping/dict for placeholder key and values.
:return: Potentially modified text with replaced placeho... | [
"Replace",
"placeholders",
"in",
"text",
"by",
"using",
"the",
"data",
"mapping",
".",
"Other",
"placeholders",
"that",
"is",
"not",
"represented",
"by",
"data",
"is",
"left",
"untouched",
"."
] | 59c735281a95b44f6263a25f4d6ce24fca520082 | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/textutil.py#L148-L161 |
39,417 | SteemData/steemdata | steemdata/markets.py | Tickers._wva | def _wva(values, weights):
""" Calculates a weighted average
"""
assert len(values) == len(weights) and len(weights) > 0
return sum([mul(*x) for x in zip(values, weights)]) / sum(weights) | python | def _wva(values, weights):
""" Calculates a weighted average
"""
assert len(values) == len(weights) and len(weights) > 0
return sum([mul(*x) for x in zip(values, weights)]) / sum(weights) | [
"def",
"_wva",
"(",
"values",
",",
"weights",
")",
":",
"assert",
"len",
"(",
"values",
")",
"==",
"len",
"(",
"weights",
")",
"and",
"len",
"(",
"weights",
")",
">",
"0",
"return",
"sum",
"(",
"[",
"mul",
"(",
"*",
"x",
")",
"for",
"x",
"in",
... | Calculates a weighted average | [
"Calculates",
"a",
"weighted",
"average"
] | 64dfc6d795deeb922e9041fa53e0946f07708ea1 | https://github.com/SteemData/steemdata/blob/64dfc6d795deeb922e9041fa53e0946f07708ea1/steemdata/markets.py#L113-L117 |
39,418 | MacHu-GWU/crawlib-project | crawlib/spider.py | execute_one_to_many_job | def execute_one_to_many_job(parent_class=None,
get_unfinished_kwargs=None,
get_unfinished_limit=None,
parser_func=None,
parser_func_kwargs=None,
build_url_func_kwargs=None,
... | python | def execute_one_to_many_job(parent_class=None,
get_unfinished_kwargs=None,
get_unfinished_limit=None,
parser_func=None,
parser_func_kwargs=None,
build_url_func_kwargs=None,
... | [
"def",
"execute_one_to_many_job",
"(",
"parent_class",
"=",
"None",
",",
"get_unfinished_kwargs",
"=",
"None",
",",
"get_unfinished_limit",
"=",
"None",
",",
"parser_func",
"=",
"None",
",",
"parser_func_kwargs",
"=",
"None",
",",
"build_url_func_kwargs",
"=",
"None... | A standard one-to-many crawling workflow.
:param parent_class:
:param get_unfinished_kwargs:
:param get_unfinished_limit:
:param parser_func: html parser function.
:param parser_func_kwargs: other keyword arguments for ``parser_func``
:param build_url_func_kwargs: other keyword arguments for
... | [
"A",
"standard",
"one",
"-",
"to",
"-",
"many",
"crawling",
"workflow",
"."
] | 241516f2a7a0a32c692f7af35a1f44064e8ce1ab | https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/spider.py#L24-L114 |
39,419 | sparknetworks/pgpm | pgpm/lib/utils/db.py | SqlScriptsHelper.create_db_schema | def create_db_schema(cls, cur, schema_name):
"""
Create Postgres schema script and execute it on cursor
"""
create_schema_script = "CREATE SCHEMA {0} ;\n".format(schema_name)
cur.execute(create_schema_script) | python | def create_db_schema(cls, cur, schema_name):
"""
Create Postgres schema script and execute it on cursor
"""
create_schema_script = "CREATE SCHEMA {0} ;\n".format(schema_name)
cur.execute(create_schema_script) | [
"def",
"create_db_schema",
"(",
"cls",
",",
"cur",
",",
"schema_name",
")",
":",
"create_schema_script",
"=",
"\"CREATE SCHEMA {0} ;\\n\"",
".",
"format",
"(",
"schema_name",
")",
"cur",
".",
"execute",
"(",
"create_schema_script",
")"
] | Create Postgres schema script and execute it on cursor | [
"Create",
"Postgres",
"schema",
"script",
"and",
"execute",
"it",
"on",
"cursor"
] | 1a060df46a886095181f692ea870a73a32510a2e | https://github.com/sparknetworks/pgpm/blob/1a060df46a886095181f692ea870a73a32510a2e/pgpm/lib/utils/db.py#L152-L157 |
39,420 | sparknetworks/pgpm | pgpm/lib/utils/db.py | SqlScriptsHelper.revoke_all | def revoke_all(cls, cur, schema_name, roles):
"""
Revoke all privileges from schema, tables, sequences and functions for a specific role
"""
cur.execute('REVOKE ALL ON SCHEMA {0} FROM {1};'
'REVOKE ALL ON ALL TABLES IN SCHEMA {0} FROM {1};'
'REVOKE... | python | def revoke_all(cls, cur, schema_name, roles):
"""
Revoke all privileges from schema, tables, sequences and functions for a specific role
"""
cur.execute('REVOKE ALL ON SCHEMA {0} FROM {1};'
'REVOKE ALL ON ALL TABLES IN SCHEMA {0} FROM {1};'
'REVOKE... | [
"def",
"revoke_all",
"(",
"cls",
",",
"cur",
",",
"schema_name",
",",
"roles",
")",
":",
"cur",
".",
"execute",
"(",
"'REVOKE ALL ON SCHEMA {0} FROM {1};'",
"'REVOKE ALL ON ALL TABLES IN SCHEMA {0} FROM {1};'",
"'REVOKE ALL ON ALL SEQUENCES IN SCHEMA {0} FROM {1};'",
"'REVOKE A... | Revoke all privileges from schema, tables, sequences and functions for a specific role | [
"Revoke",
"all",
"privileges",
"from",
"schema",
"tables",
"sequences",
"and",
"functions",
"for",
"a",
"specific",
"role"
] | 1a060df46a886095181f692ea870a73a32510a2e | https://github.com/sparknetworks/pgpm/blob/1a060df46a886095181f692ea870a73a32510a2e/pgpm/lib/utils/db.py#L191-L198 |
39,421 | sparknetworks/pgpm | pgpm/lib/utils/db.py | SqlScriptsHelper.schema_exists | def schema_exists(cls, cur, schema_name):
"""
Check if schema exists
"""
cur.execute("SELECT EXISTS (SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}');"
.format(schema_name))
return cur.fetchone()[0] | python | def schema_exists(cls, cur, schema_name):
"""
Check if schema exists
"""
cur.execute("SELECT EXISTS (SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}');"
.format(schema_name))
return cur.fetchone()[0] | [
"def",
"schema_exists",
"(",
"cls",
",",
"cur",
",",
"schema_name",
")",
":",
"cur",
".",
"execute",
"(",
"\"SELECT EXISTS (SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}');\"",
".",
"format",
"(",
"schema_name",
")",
")",
"return",
"cur",
... | Check if schema exists | [
"Check",
"if",
"schema",
"exists"
] | 1a060df46a886095181f692ea870a73a32510a2e | https://github.com/sparknetworks/pgpm/blob/1a060df46a886095181f692ea870a73a32510a2e/pgpm/lib/utils/db.py#L209-L215 |
39,422 | jplusplus/statscraper | statscraper/base_scraper.py | ResultSet.pandas | def pandas(self):
"""Return a Pandas dataframe."""
if self._pandas is None:
self._pandas = pd.DataFrame().from_records(self.list_of_dicts)
return self._pandas | python | def pandas(self):
"""Return a Pandas dataframe."""
if self._pandas is None:
self._pandas = pd.DataFrame().from_records(self.list_of_dicts)
return self._pandas | [
"def",
"pandas",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pandas",
"is",
"None",
":",
"self",
".",
"_pandas",
"=",
"pd",
".",
"DataFrame",
"(",
")",
".",
"from_records",
"(",
"self",
".",
"list_of_dicts",
")",
"return",
"self",
".",
"_pandas"
] | Return a Pandas dataframe. | [
"Return",
"a",
"Pandas",
"dataframe",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L72-L76 |
39,423 | jplusplus/statscraper | statscraper/base_scraper.py | ResultSet.translate | def translate(self, dialect):
"""Return a copy of this ResultSet in a different dialect."""
new_resultset = copy(self)
new_resultset.dialect = dialect
for result in new_resultset:
for dimensionvalue in result.dimensionvalues:
dimensionvalue.value = dimensionv... | python | def translate(self, dialect):
"""Return a copy of this ResultSet in a different dialect."""
new_resultset = copy(self)
new_resultset.dialect = dialect
for result in new_resultset:
for dimensionvalue in result.dimensionvalues:
dimensionvalue.value = dimensionv... | [
"def",
"translate",
"(",
"self",
",",
"dialect",
")",
":",
"new_resultset",
"=",
"copy",
"(",
"self",
")",
"new_resultset",
".",
"dialect",
"=",
"dialect",
"for",
"result",
"in",
"new_resultset",
":",
"for",
"dimensionvalue",
"in",
"result",
".",
"dimensionv... | Return a copy of this ResultSet in a different dialect. | [
"Return",
"a",
"copy",
"of",
"this",
"ResultSet",
"in",
"a",
"different",
"dialect",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L78-L86 |
39,424 | jplusplus/statscraper | statscraper/base_scraper.py | ResultSet.append | def append(self, val):
"""Connect any new results to the resultset.
This is where all the heavy lifting is done for creating results:
- We add a datatype here, so that each result can handle
validation etc independently. This is so that scraper authors
don't need to worry about... | python | def append(self, val):
"""Connect any new results to the resultset.
This is where all the heavy lifting is done for creating results:
- We add a datatype here, so that each result can handle
validation etc independently. This is so that scraper authors
don't need to worry about... | [
"def",
"append",
"(",
"self",
",",
"val",
")",
":",
"val",
".",
"resultset",
"=",
"self",
"val",
".",
"dataset",
"=",
"self",
".",
"dataset",
"# Check result dimensions against available dimensions for this dataset",
"if",
"val",
".",
"dataset",
":",
"dataset_dime... | Connect any new results to the resultset.
This is where all the heavy lifting is done for creating results:
- We add a datatype here, so that each result can handle
validation etc independently. This is so that scraper authors
don't need to worry about creating and passing around datat... | [
"Connect",
"any",
"new",
"results",
"to",
"the",
"resultset",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L88-L140 |
39,425 | jplusplus/statscraper | statscraper/base_scraper.py | Dimension.allowed_values | def allowed_values(self):
"""Return a list of allowed values."""
if self._allowed_values is None:
self._allowed_values = ValueList()
for val in self.scraper._fetch_allowed_values(self):
if isinstance(val, DimensionValue):
self._allowed_values.a... | python | def allowed_values(self):
"""Return a list of allowed values."""
if self._allowed_values is None:
self._allowed_values = ValueList()
for val in self.scraper._fetch_allowed_values(self):
if isinstance(val, DimensionValue):
self._allowed_values.a... | [
"def",
"allowed_values",
"(",
"self",
")",
":",
"if",
"self",
".",
"_allowed_values",
"is",
"None",
":",
"self",
".",
"_allowed_values",
"=",
"ValueList",
"(",
")",
"for",
"val",
"in",
"self",
".",
"scraper",
".",
"_fetch_allowed_values",
"(",
"self",
")",... | Return a list of allowed values. | [
"Return",
"a",
"list",
"of",
"allowed",
"values",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L240-L250 |
39,426 | jplusplus/statscraper | statscraper/base_scraper.py | ItemList.append | def append(self, val):
"""Connect any new items to the scraper."""
val.scraper = self.scraper
val._collection_path = copy(self.collection._collection_path)
val._collection_path.append(val)
super(ItemList, self).append(val) | python | def append(self, val):
"""Connect any new items to the scraper."""
val.scraper = self.scraper
val._collection_path = copy(self.collection._collection_path)
val._collection_path.append(val)
super(ItemList, self).append(val) | [
"def",
"append",
"(",
"self",
",",
"val",
")",
":",
"val",
".",
"scraper",
"=",
"self",
".",
"scraper",
"val",
".",
"_collection_path",
"=",
"copy",
"(",
"self",
".",
"collection",
".",
"_collection_path",
")",
"val",
".",
"_collection_path",
".",
"appen... | Connect any new items to the scraper. | [
"Connect",
"any",
"new",
"items",
"to",
"the",
"scraper",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L272-L277 |
39,427 | jplusplus/statscraper | statscraper/base_scraper.py | Item._move_here | def _move_here(self):
"""Move the cursor to this item."""
cu = self.scraper.current_item
# Already here?
if self is cu:
return
# A child?
if cu.items and self in cu.items:
self.scraper.move_to(self)
return
# A parent?
if... | python | def _move_here(self):
"""Move the cursor to this item."""
cu = self.scraper.current_item
# Already here?
if self is cu:
return
# A child?
if cu.items and self in cu.items:
self.scraper.move_to(self)
return
# A parent?
if... | [
"def",
"_move_here",
"(",
"self",
")",
":",
"cu",
"=",
"self",
".",
"scraper",
".",
"current_item",
"# Already here?",
"if",
"self",
"is",
"cu",
":",
"return",
"# A child?",
"if",
"cu",
".",
"items",
"and",
"self",
"in",
"cu",
".",
"items",
":",
"self"... | Move the cursor to this item. | [
"Move",
"the",
"cursor",
"to",
"this",
"item",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L298-L319 |
39,428 | jplusplus/statscraper | statscraper/base_scraper.py | Collection.items | def items(self):
"""ItemList of children."""
if self.scraper.current_item is not self:
self._move_here()
if self._items is None:
self._items = ItemList()
self._items.scraper = self.scraper
self._items.collection = self
for i in self.sc... | python | def items(self):
"""ItemList of children."""
if self.scraper.current_item is not self:
self._move_here()
if self._items is None:
self._items = ItemList()
self._items.scraper = self.scraper
self._items.collection = self
for i in self.sc... | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"self",
".",
"scraper",
".",
"current_item",
"is",
"not",
"self",
":",
"self",
".",
"_move_here",
"(",
")",
"if",
"self",
".",
"_items",
"is",
"None",
":",
"self",
".",
"_items",
"=",
"ItemList",
"(",
")... | ItemList of children. | [
"ItemList",
"of",
"children",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L361-L375 |
39,429 | jplusplus/statscraper | statscraper/base_scraper.py | Dataset._hash | def _hash(self):
"""Return a hash for the current query.
This hash is _not_ a unique representation of the dataset!
"""
dump = dumps(self.query, sort_keys=True)
if isinstance(dump, str):
dump = dump.encode('utf-8')
return md5(dump).hexdigest() | python | def _hash(self):
"""Return a hash for the current query.
This hash is _not_ a unique representation of the dataset!
"""
dump = dumps(self.query, sort_keys=True)
if isinstance(dump, str):
dump = dump.encode('utf-8')
return md5(dump).hexdigest() | [
"def",
"_hash",
"(",
"self",
")",
":",
"dump",
"=",
"dumps",
"(",
"self",
".",
"query",
",",
"sort_keys",
"=",
"True",
")",
"if",
"isinstance",
"(",
"dump",
",",
"str",
")",
":",
"dump",
"=",
"dump",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
... | Return a hash for the current query.
This hash is _not_ a unique representation of the dataset! | [
"Return",
"a",
"hash",
"for",
"the",
"current",
"query",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L413-L421 |
39,430 | jplusplus/statscraper | statscraper/base_scraper.py | Dataset.dimensions | def dimensions(self):
"""Available dimensions, if defined."""
# First of all: Select this dataset
if self.scraper.current_item is not self:
self._move_here()
if self._dimensions is None:
self._dimensions = DimensionList()
for d in self.scraper._fetch_... | python | def dimensions(self):
"""Available dimensions, if defined."""
# First of all: Select this dataset
if self.scraper.current_item is not self:
self._move_here()
if self._dimensions is None:
self._dimensions = DimensionList()
for d in self.scraper._fetch_... | [
"def",
"dimensions",
"(",
"self",
")",
":",
"# First of all: Select this dataset",
"if",
"self",
".",
"scraper",
".",
"current_item",
"is",
"not",
"self",
":",
"self",
".",
"_move_here",
"(",
")",
"if",
"self",
".",
"_dimensions",
"is",
"None",
":",
"self",
... | Available dimensions, if defined. | [
"Available",
"dimensions",
"if",
"defined",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L478-L490 |
39,431 | jplusplus/statscraper | statscraper/base_scraper.py | BaseScraper.on | def on(cls, hook):
"""Hook decorator."""
def decorator(function_):
cls._hooks[hook].append(function_)
return function_
return decorator | python | def on(cls, hook):
"""Hook decorator."""
def decorator(function_):
cls._hooks[hook].append(function_)
return function_
return decorator | [
"def",
"on",
"(",
"cls",
",",
"hook",
")",
":",
"def",
"decorator",
"(",
"function_",
")",
":",
"cls",
".",
"_hooks",
"[",
"hook",
"]",
".",
"append",
"(",
"function_",
")",
"return",
"function_",
"return",
"decorator"
] | Hook decorator. | [
"Hook",
"decorator",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L514-L519 |
39,432 | jplusplus/statscraper | statscraper/base_scraper.py | BaseScraper.move_to_top | def move_to_top(self):
"""Move to root item."""
self.current_item = self.root
for f in self._hooks["top"]:
f(self)
return self | python | def move_to_top(self):
"""Move to root item."""
self.current_item = self.root
for f in self._hooks["top"]:
f(self)
return self | [
"def",
"move_to_top",
"(",
"self",
")",
":",
"self",
".",
"current_item",
"=",
"self",
".",
"root",
"for",
"f",
"in",
"self",
".",
"_hooks",
"[",
"\"top\"",
"]",
":",
"f",
"(",
"self",
")",
"return",
"self"
] | Move to root item. | [
"Move",
"to",
"root",
"item",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L560-L565 |
39,433 | jplusplus/statscraper | statscraper/base_scraper.py | BaseScraper.move_up | def move_up(self):
"""Move up one level in the hierarchy, unless already on top."""
if self.current_item.parent is not None:
self.current_item = self.current_item.parent
for f in self._hooks["up"]:
f(self)
if self.current_item is self.root:
for f in s... | python | def move_up(self):
"""Move up one level in the hierarchy, unless already on top."""
if self.current_item.parent is not None:
self.current_item = self.current_item.parent
for f in self._hooks["up"]:
f(self)
if self.current_item is self.root:
for f in s... | [
"def",
"move_up",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_item",
".",
"parent",
"is",
"not",
"None",
":",
"self",
".",
"current_item",
"=",
"self",
".",
"current_item",
".",
"parent",
"for",
"f",
"in",
"self",
".",
"_hooks",
"[",
"\"up\"",
... | Move up one level in the hierarchy, unless already on top. | [
"Move",
"up",
"one",
"level",
"in",
"the",
"hierarchy",
"unless",
"already",
"on",
"top",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L567-L577 |
39,434 | jplusplus/statscraper | statscraper/base_scraper.py | BaseScraper.descendants | def descendants(self):
"""Recursively return every dataset below current item."""
for i in self.current_item.items:
self.move_to(i)
if i.type == TYPE_COLLECTION:
for c in self.children:
yield c
else:
yield i
... | python | def descendants(self):
"""Recursively return every dataset below current item."""
for i in self.current_item.items:
self.move_to(i)
if i.type == TYPE_COLLECTION:
for c in self.children:
yield c
else:
yield i
... | [
"def",
"descendants",
"(",
"self",
")",
":",
"for",
"i",
"in",
"self",
".",
"current_item",
".",
"items",
":",
"self",
".",
"move_to",
"(",
"i",
")",
"if",
"i",
".",
"type",
"==",
"TYPE_COLLECTION",
":",
"for",
"c",
"in",
"self",
".",
"children",
"... | Recursively return every dataset below current item. | [
"Recursively",
"return",
"every",
"dataset",
"below",
"current",
"item",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L626-L635 |
39,435 | jplusplus/statscraper | statscraper/base_scraper.py | BaseScraper.children | def children(self):
"""Former, misleading name for descendants."""
from warnings import warn
warn("Deprecated. Use Scraper.descendants.", DeprecationWarning)
for descendant in self.descendants:
yield descendant | python | def children(self):
"""Former, misleading name for descendants."""
from warnings import warn
warn("Deprecated. Use Scraper.descendants.", DeprecationWarning)
for descendant in self.descendants:
yield descendant | [
"def",
"children",
"(",
"self",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"\"Deprecated. Use Scraper.descendants.\"",
",",
"DeprecationWarning",
")",
"for",
"descendant",
"in",
"self",
".",
"descendants",
":",
"yield",
"descendant"
] | Former, misleading name for descendants. | [
"Former",
"misleading",
"name",
"for",
"descendants",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L638-L643 |
39,436 | orbeckst/RecSQL | recsql/csv_table.py | make_python_name | def make_python_name(s, default=None, number_prefix='N',encoding="utf-8"):
"""Returns a unicode string that can be used as a legal python identifier.
:Arguments:
*s*
string
*default*
use *default* if *s* is ``None``
*number_prefix*
string to prepend if *s* starts wi... | python | def make_python_name(s, default=None, number_prefix='N',encoding="utf-8"):
"""Returns a unicode string that can be used as a legal python identifier.
:Arguments:
*s*
string
*default*
use *default* if *s* is ``None``
*number_prefix*
string to prepend if *s* starts wi... | [
"def",
"make_python_name",
"(",
"s",
",",
"default",
"=",
"None",
",",
"number_prefix",
"=",
"'N'",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"s",
"in",
"(",
"''",
",",
"None",
")",
":",
"s",
"=",
"default",
"s",
"=",
"str",
"(",
"s",
")... | Returns a unicode string that can be used as a legal python identifier.
:Arguments:
*s*
string
*default*
use *default* if *s* is ``None``
*number_prefix*
string to prepend if *s* starts with a number | [
"Returns",
"a",
"unicode",
"string",
"that",
"can",
"be",
"used",
"as",
"a",
"legal",
"python",
"identifier",
"."
] | 6acbf821022361719391697c9c2f0822f9f8022a | https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/csv_table.py#L75-L92 |
39,437 | tradenity/python-sdk | tradenity/resources/option.py | Option.data_type | def data_type(self, data_type):
"""Sets the data_type of this Option.
:param data_type: The data_type of this Option.
:type: str
"""
allowed_values = ["string", "number", "date", "color"]
if data_type is not None and data_type not in allowed_values:
raise Va... | python | def data_type(self, data_type):
"""Sets the data_type of this Option.
:param data_type: The data_type of this Option.
:type: str
"""
allowed_values = ["string", "number", "date", "color"]
if data_type is not None and data_type not in allowed_values:
raise Va... | [
"def",
"data_type",
"(",
"self",
",",
"data_type",
")",
":",
"allowed_values",
"=",
"[",
"\"string\"",
",",
"\"number\"",
",",
"\"date\"",
",",
"\"color\"",
"]",
"if",
"data_type",
"is",
"not",
"None",
"and",
"data_type",
"not",
"in",
"allowed_values",
":",
... | Sets the data_type of this Option.
:param data_type: The data_type of this Option.
:type: str | [
"Sets",
"the",
"data_type",
"of",
"this",
"Option",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/option.py#L214-L228 |
39,438 | inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/helpers.py | get_callable_signature_as_string | def get_callable_signature_as_string(the_callable):
"""Return a string representing a callable.
It is executed as if it would have been declared on the prompt.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> get_callable_signature_as_string(foo)
def foo(arg1,... | python | def get_callable_signature_as_string(the_callable):
"""Return a string representing a callable.
It is executed as if it would have been declared on the prompt.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> get_callable_signature_as_string(foo)
def foo(arg1,... | [
"def",
"get_callable_signature_as_string",
"(",
"the_callable",
")",
":",
"args",
",",
"varargs",
",",
"varkw",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"the_callable",
")",
"tmp_args",
"=",
"list",
"(",
"args",
")",
"args_dict",
"=",
"{",
"}... | Return a string representing a callable.
It is executed as if it would have been declared on the prompt.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> get_callable_signature_as_string(foo)
def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd)
:param... | [
"Return",
"a",
"string",
"representing",
"a",
"callable",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/helpers.py#L27-L69 |
39,439 | inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/helpers.py | get_callable_documentation | def get_callable_documentation(the_callable):
"""Return a string with the callable signature and its docstring.
:param the_callable: the callable to be analyzed.
:type the_callable: function/callable.
:return: the signature.
"""
return wrap_text_in_a_box(
title=get_callable_signature_as... | python | def get_callable_documentation(the_callable):
"""Return a string with the callable signature and its docstring.
:param the_callable: the callable to be analyzed.
:type the_callable: function/callable.
:return: the signature.
"""
return wrap_text_in_a_box(
title=get_callable_signature_as... | [
"def",
"get_callable_documentation",
"(",
"the_callable",
")",
":",
"return",
"wrap_text_in_a_box",
"(",
"title",
"=",
"get_callable_signature_as_string",
"(",
"the_callable",
")",
",",
"body",
"=",
"(",
"getattr",
"(",
"the_callable",
",",
"'__doc__'",
")",
"or",
... | Return a string with the callable signature and its docstring.
:param the_callable: the callable to be analyzed.
:type the_callable: function/callable.
:return: the signature. | [
"Return",
"a",
"string",
"with",
"the",
"callable",
"signature",
"and",
"its",
"docstring",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/helpers.py#L72-L83 |
39,440 | objectrocket/python-client | objectrocket/util.py | register_extension_class | def register_extension_class(ext, base, *args, **kwargs):
"""Instantiate the given extension class and register as a public attribute of the given base.
README: The expected protocol here is to instantiate the given extension and pass the base
object as the first positional argument, then unpack args and k... | python | def register_extension_class(ext, base, *args, **kwargs):
"""Instantiate the given extension class and register as a public attribute of the given base.
README: The expected protocol here is to instantiate the given extension and pass the base
object as the first positional argument, then unpack args and k... | [
"def",
"register_extension_class",
"(",
"ext",
",",
"base",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ext_instance",
"=",
"ext",
".",
"plugin",
"(",
"base",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"setattr",
"(",
"base",
",",
"e... | Instantiate the given extension class and register as a public attribute of the given base.
README: The expected protocol here is to instantiate the given extension and pass the base
object as the first positional argument, then unpack args and kwargs as additional arguments to
the extension's constructor. | [
"Instantiate",
"the",
"given",
"extension",
"class",
"and",
"register",
"as",
"a",
"public",
"attribute",
"of",
"the",
"given",
"base",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/util.py#L12-L20 |
39,441 | objectrocket/python-client | objectrocket/util.py | register_extension_method | def register_extension_method(ext, base, *args, **kwargs):
"""Register the given extension method as a public attribute of the given base.
README: The expected protocol here is that the given extension method is an unbound function.
It will be bound to the specified base as a method, and then set as a publ... | python | def register_extension_method(ext, base, *args, **kwargs):
"""Register the given extension method as a public attribute of the given base.
README: The expected protocol here is that the given extension method is an unbound function.
It will be bound to the specified base as a method, and then set as a publ... | [
"def",
"register_extension_method",
"(",
"ext",
",",
"base",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bound_method",
"=",
"create_bound_method",
"(",
"ext",
".",
"plugin",
",",
"base",
")",
"setattr",
"(",
"base",
",",
"ext",
".",
"name",
... | Register the given extension method as a public attribute of the given base.
README: The expected protocol here is that the given extension method is an unbound function.
It will be bound to the specified base as a method, and then set as a public attribute of that
base. | [
"Register",
"the",
"given",
"extension",
"method",
"as",
"a",
"public",
"attribute",
"of",
"the",
"given",
"base",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/util.py#L23-L31 |
39,442 | objectrocket/python-client | objectrocket/util.py | token_auto_auth | def token_auto_auth(func):
"""Wrap class methods with automatic token re-authentication.
This wrapper will detect authentication failures coming from its wrapped method. When one is
caught, it will request a new token, and simply replay the original request.
The one constraint that this wrapper has is... | python | def token_auto_auth(func):
"""Wrap class methods with automatic token re-authentication.
This wrapper will detect authentication failures coming from its wrapped method. When one is
caught, it will request a new token, and simply replay the original request.
The one constraint that this wrapper has is... | [
"def",
"token_auto_auth",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"response",
"=",
"func",
"(",
"self",
",",
"*",
"ar... | Wrap class methods with automatic token re-authentication.
This wrapper will detect authentication failures coming from its wrapped method. When one is
caught, it will request a new token, and simply replay the original request.
The one constraint that this wrapper has is that the wrapped method's class m... | [
"Wrap",
"class",
"methods",
"with",
"automatic",
"token",
"re",
"-",
"authentication",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/util.py#L34-L62 |
39,443 | jkitzes/macroeco | doc/_ext/juliadoc/juliadoc/__init__.py | get_theme_dir | def get_theme_dir():
"""
Returns path to directory containing this package's theme.
This is designed to be used when setting the ``html_theme_path``
option within Sphinx's ``conf.py`` file.
"""
return os.path.abspath(os.path.join(os.path.dirname(__file__), "theme")) | python | def get_theme_dir():
"""
Returns path to directory containing this package's theme.
This is designed to be used when setting the ``html_theme_path``
option within Sphinx's ``conf.py`` file.
"""
return os.path.abspath(os.path.join(os.path.dirname(__file__), "theme")) | [
"def",
"get_theme_dir",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"theme\"",
")",
")"
] | Returns path to directory containing this package's theme.
This is designed to be used when setting the ``html_theme_path``
option within Sphinx's ``conf.py`` file. | [
"Returns",
"path",
"to",
"directory",
"containing",
"this",
"package",
"s",
"theme",
".",
"This",
"is",
"designed",
"to",
"be",
"used",
"when",
"setting",
"the",
"html_theme_path",
"option",
"within",
"Sphinx",
"s",
"conf",
".",
"py",
"file",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/doc/_ext/juliadoc/juliadoc/__init__.py#L3-L10 |
39,444 | trevisanj/a99 | a99/conversion.py | seconds2str | def seconds2str(seconds):
"""Returns string such as 1h 05m 55s."""
if seconds < 0:
return "{0:.3g}s".format(seconds)
elif math.isnan(seconds):
return "NaN"
elif math.isinf(seconds):
return "Inf"
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
if h >= 1:
... | python | def seconds2str(seconds):
"""Returns string such as 1h 05m 55s."""
if seconds < 0:
return "{0:.3g}s".format(seconds)
elif math.isnan(seconds):
return "NaN"
elif math.isinf(seconds):
return "Inf"
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
if h >= 1:
... | [
"def",
"seconds2str",
"(",
"seconds",
")",
":",
"if",
"seconds",
"<",
"0",
":",
"return",
"\"{0:.3g}s\"",
".",
"format",
"(",
"seconds",
")",
"elif",
"math",
".",
"isnan",
"(",
"seconds",
")",
":",
"return",
"\"NaN\"",
"elif",
"math",
".",
"isinf",
"("... | Returns string such as 1h 05m 55s. | [
"Returns",
"string",
"such",
"as",
"1h",
"05m",
"55s",
"."
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/conversion.py#L105-L122 |
39,445 | trevisanj/a99 | a99/conversion.py | eval_fieldnames | def eval_fieldnames(string_, varname="fieldnames"):
"""Evaluates string_, must evaluate to list of strings. Also converts field names to uppercase"""
ff = eval(string_)
if not isinstance(ff, list):
raise RuntimeError("{0!s} must be a list".format(varname))
if not all([isinstance(x, str) for... | python | def eval_fieldnames(string_, varname="fieldnames"):
"""Evaluates string_, must evaluate to list of strings. Also converts field names to uppercase"""
ff = eval(string_)
if not isinstance(ff, list):
raise RuntimeError("{0!s} must be a list".format(varname))
if not all([isinstance(x, str) for... | [
"def",
"eval_fieldnames",
"(",
"string_",
",",
"varname",
"=",
"\"fieldnames\"",
")",
":",
"ff",
"=",
"eval",
"(",
"string_",
")",
"if",
"not",
"isinstance",
"(",
"ff",
",",
"list",
")",
":",
"raise",
"RuntimeError",
"(",
"\"{0!s} must be a list\"",
".",
"... | Evaluates string_, must evaluate to list of strings. Also converts field names to uppercase | [
"Evaluates",
"string_",
"must",
"evaluate",
"to",
"list",
"of",
"strings",
".",
"Also",
"converts",
"field",
"names",
"to",
"uppercase"
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/conversion.py#L184-L192 |
39,446 | kgaughan/dbkit | examples/notary/notary.py | strip_accents | def strip_accents(s):
"""
Strip accents to prepare for slugification.
"""
nfkd = unicodedata.normalize('NFKD', unicode(s))
return u''.join(ch for ch in nfkd if not unicodedata.combining(ch)) | python | def strip_accents(s):
"""
Strip accents to prepare for slugification.
"""
nfkd = unicodedata.normalize('NFKD', unicode(s))
return u''.join(ch for ch in nfkd if not unicodedata.combining(ch)) | [
"def",
"strip_accents",
"(",
"s",
")",
":",
"nfkd",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"unicode",
"(",
"s",
")",
")",
"return",
"u''",
".",
"join",
"(",
"ch",
"for",
"ch",
"in",
"nfkd",
"if",
"not",
"unicodedata",
".",
"combini... | Strip accents to prepare for slugification. | [
"Strip",
"accents",
"to",
"prepare",
"for",
"slugification",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/examples/notary/notary.py#L35-L40 |
39,447 | kgaughan/dbkit | examples/notary/notary.py | slugify | def slugify(s):
"""
Converts the given string to a URL slug.
"""
s = strip_accents(s.replace("'", '').lower())
return re.sub('[^a-z0-9]+', ' ', s).strip().replace(' ', '-') | python | def slugify(s):
"""
Converts the given string to a URL slug.
"""
s = strip_accents(s.replace("'", '').lower())
return re.sub('[^a-z0-9]+', ' ', s).strip().replace(' ', '-') | [
"def",
"slugify",
"(",
"s",
")",
":",
"s",
"=",
"strip_accents",
"(",
"s",
".",
"replace",
"(",
"\"'\"",
",",
"''",
")",
".",
"lower",
"(",
")",
")",
"return",
"re",
".",
"sub",
"(",
"'[^a-z0-9]+'",
",",
"' '",
",",
"s",
")",
".",
"strip",
"(",... | Converts the given string to a URL slug. | [
"Converts",
"the",
"given",
"string",
"to",
"a",
"URL",
"slug",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/examples/notary/notary.py#L43-L48 |
39,448 | kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | _legacy_status | def _legacy_status(stat):
"""Legacy status method from the 'qsmobile.js' library.
Pass in the 'val' from &devices or the
'data' received after calling a specific ID.
"""
# 2d0c00002a0000
if stat[:2] == '30' or stat[:2] == '47': # RX1 CT
ooo = stat[4:5]
# console.log("legstat. "... | python | def _legacy_status(stat):
"""Legacy status method from the 'qsmobile.js' library.
Pass in the 'val' from &devices or the
'data' received after calling a specific ID.
"""
# 2d0c00002a0000
if stat[:2] == '30' or stat[:2] == '47': # RX1 CT
ooo = stat[4:5]
# console.log("legstat. "... | [
"def",
"_legacy_status",
"(",
"stat",
")",
":",
"# 2d0c00002a0000",
"if",
"stat",
"[",
":",
"2",
"]",
"==",
"'30'",
"or",
"stat",
"[",
":",
"2",
"]",
"==",
"'47'",
":",
"# RX1 CT",
"ooo",
"=",
"stat",
"[",
"4",
":",
"5",
"]",
"# console.log(\"legstat... | Legacy status method from the 'qsmobile.js' library.
Pass in the 'val' from &devices or the
'data' received after calling a specific ID. | [
"Legacy",
"status",
"method",
"from",
"the",
"qsmobile",
".",
"js",
"library",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L55-L98 |
39,449 | kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | decode_door | def decode_door(packet, channel=1):
"""Decode a door sensor."""
val = str(packet.get(QSDATA, ''))
if len(val) == 6 and val.startswith('46') and channel == 1:
return val[-1] == '0'
return None | python | def decode_door(packet, channel=1):
"""Decode a door sensor."""
val = str(packet.get(QSDATA, ''))
if len(val) == 6 and val.startswith('46') and channel == 1:
return val[-1] == '0'
return None | [
"def",
"decode_door",
"(",
"packet",
",",
"channel",
"=",
"1",
")",
":",
"val",
"=",
"str",
"(",
"packet",
".",
"get",
"(",
"QSDATA",
",",
"''",
")",
")",
"if",
"len",
"(",
"val",
")",
"==",
"6",
"and",
"val",
".",
"startswith",
"(",
"'46'",
")... | Decode a door sensor. | [
"Decode",
"a",
"door",
"sensor",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L211-L216 |
39,450 | kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | decode_imod | def decode_imod(packet, channel=1):
"""Decode an 4 channel imod. May support 6 channels."""
val = str(packet.get(QSDATA, ''))
if len(val) == 8 and val.startswith('4e'):
try:
_map = ((5, 1), (5, 2), (5, 4), (4, 1), (5, 1), (5, 2))[
channel - 1]
return (int(val[... | python | def decode_imod(packet, channel=1):
"""Decode an 4 channel imod. May support 6 channels."""
val = str(packet.get(QSDATA, ''))
if len(val) == 8 and val.startswith('4e'):
try:
_map = ((5, 1), (5, 2), (5, 4), (4, 1), (5, 1), (5, 2))[
channel - 1]
return (int(val[... | [
"def",
"decode_imod",
"(",
"packet",
",",
"channel",
"=",
"1",
")",
":",
"val",
"=",
"str",
"(",
"packet",
".",
"get",
"(",
"QSDATA",
",",
"''",
")",
")",
"if",
"len",
"(",
"val",
")",
"==",
"8",
"and",
"val",
".",
"startswith",
"(",
"'4e'",
")... | Decode an 4 channel imod. May support 6 channels. | [
"Decode",
"an",
"4",
"channel",
"imod",
".",
"May",
"support",
"6",
"channels",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L228-L238 |
39,451 | kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | decode_pir | def decode_pir(packet, channel=1):
"""Decode a PIR."""
val = str(packet.get(QSDATA, ''))
if len(val) == 8 and val.startswith('0f') and channel == 1:
return int(val[-4:], 16) > 0
return None | python | def decode_pir(packet, channel=1):
"""Decode a PIR."""
val = str(packet.get(QSDATA, ''))
if len(val) == 8 and val.startswith('0f') and channel == 1:
return int(val[-4:], 16) > 0
return None | [
"def",
"decode_pir",
"(",
"packet",
",",
"channel",
"=",
"1",
")",
":",
"val",
"=",
"str",
"(",
"packet",
".",
"get",
"(",
"QSDATA",
",",
"''",
")",
")",
"if",
"len",
"(",
"val",
")",
"==",
"8",
"and",
"val",
".",
"startswith",
"(",
"'0f'",
")"... | Decode a PIR. | [
"Decode",
"a",
"PIR",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L246-L251 |
39,452 | kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | decode_temperature | def decode_temperature(packet, channel=1):
"""Decode the temperature."""
val = str(packet.get(QSDATA, ''))
if len(val) == 12 and val.startswith('34') and channel == 1:
temperature = int(val[-4:], 16)
return round(float((-46.85 + (175.72 * (temperature / pow(2, 16))))))
return None | python | def decode_temperature(packet, channel=1):
"""Decode the temperature."""
val = str(packet.get(QSDATA, ''))
if len(val) == 12 and val.startswith('34') and channel == 1:
temperature = int(val[-4:], 16)
return round(float((-46.85 + (175.72 * (temperature / pow(2, 16))))))
return None | [
"def",
"decode_temperature",
"(",
"packet",
",",
"channel",
"=",
"1",
")",
":",
"val",
"=",
"str",
"(",
"packet",
".",
"get",
"(",
"QSDATA",
",",
"''",
")",
")",
"if",
"len",
"(",
"val",
")",
"==",
"12",
"and",
"val",
".",
"startswith",
"(",
"'34... | Decode the temperature. | [
"Decode",
"the",
"temperature",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L259-L265 |
39,453 | kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | decode_humidity | def decode_humidity(packet, channel=1):
"""Decode the humidity."""
val = str(packet.get(QSDATA, ''))
if len(val) == 12 and val.startswith('34') and channel == 1:
humidity = int(val[4:-4], 16)
return round(float(-6 + (125 * (humidity / pow(2, 16)))))
return None | python | def decode_humidity(packet, channel=1):
"""Decode the humidity."""
val = str(packet.get(QSDATA, ''))
if len(val) == 12 and val.startswith('34') and channel == 1:
humidity = int(val[4:-4], 16)
return round(float(-6 + (125 * (humidity / pow(2, 16)))))
return None | [
"def",
"decode_humidity",
"(",
"packet",
",",
"channel",
"=",
"1",
")",
":",
"val",
"=",
"str",
"(",
"packet",
".",
"get",
"(",
"QSDATA",
",",
"''",
")",
")",
"if",
"len",
"(",
"val",
")",
"==",
"12",
"and",
"val",
".",
"startswith",
"(",
"'34'",... | Decode the humidity. | [
"Decode",
"the",
"humidity",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L268-L274 |
39,454 | kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | QSDevices.update_devices | def update_devices(self, devices):
"""Update values from response of URL_DEVICES, callback if changed."""
for qspacket in devices:
try:
qsid = qspacket[QS_ID]
except KeyError:
_LOGGER.debug("Device without ID: %s", qspacket)
continu... | python | def update_devices(self, devices):
"""Update values from response of URL_DEVICES, callback if changed."""
for qspacket in devices:
try:
qsid = qspacket[QS_ID]
except KeyError:
_LOGGER.debug("Device without ID: %s", qspacket)
continu... | [
"def",
"update_devices",
"(",
"self",
",",
"devices",
")",
":",
"for",
"qspacket",
"in",
"devices",
":",
"try",
":",
"qsid",
"=",
"qspacket",
"[",
"QS_ID",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Device without ID: %s\"",
",",
"qsp... | Update values from response of URL_DEVICES, callback if changed. | [
"Update",
"values",
"from",
"response",
"of",
"URL_DEVICES",
"callback",
"if",
"changed",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L175-L198 |
39,455 | ten10solutions/Geist | geist/backends/replay.py | geist_replay | def geist_replay(wrapped, instance, args, kwargs):
"""Wraps a test of other function and injects a Geist GUI which will
enable replay (set environment variable GEIST_REPLAY_MODE to 'record' to
active record mode."""
path_parts = []
file_parts = []
if hasattr(wrapped, '__module__'):
modu... | python | def geist_replay(wrapped, instance, args, kwargs):
"""Wraps a test of other function and injects a Geist GUI which will
enable replay (set environment variable GEIST_REPLAY_MODE to 'record' to
active record mode."""
path_parts = []
file_parts = []
if hasattr(wrapped, '__module__'):
modu... | [
"def",
"geist_replay",
"(",
"wrapped",
",",
"instance",
",",
"args",
",",
"kwargs",
")",
":",
"path_parts",
"=",
"[",
"]",
"file_parts",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"wrapped",
",",
"'__module__'",
")",
":",
"module",
"=",
"wrapped",
".",
"__mo... | Wraps a test of other function and injects a Geist GUI which will
enable replay (set environment variable GEIST_REPLAY_MODE to 'record' to
active record mode. | [
"Wraps",
"a",
"test",
"of",
"other",
"function",
"and",
"injects",
"a",
"Geist",
"GUI",
"which",
"will",
"enable",
"replay",
"(",
"set",
"environment",
"variable",
"GEIST_REPLAY_MODE",
"to",
"record",
"to",
"active",
"record",
"mode",
"."
] | a1ef16d8b4c3777735008b671a50acfde3ce7bf1 | https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/backends/replay.py#L51-L84 |
39,456 | jkitzes/macroeco | macroeco/models/_distributions.py | _nbinom_ztrunc_p | def _nbinom_ztrunc_p(mu, k_agg):
""" Calculates p parameter for truncated negative binomial
Function given in Sampford 1955, equation 4
Note that omega = 1 / 1 + p in Sampford
"""
p_eq = lambda p, mu, k_agg: (k_agg * p) / (1 - (1 + p)**-k_agg) - mu
# The upper bound n... | python | def _nbinom_ztrunc_p(mu, k_agg):
""" Calculates p parameter for truncated negative binomial
Function given in Sampford 1955, equation 4
Note that omega = 1 / 1 + p in Sampford
"""
p_eq = lambda p, mu, k_agg: (k_agg * p) / (1 - (1 + p)**-k_agg) - mu
# The upper bound n... | [
"def",
"_nbinom_ztrunc_p",
"(",
"mu",
",",
"k_agg",
")",
":",
"p_eq",
"=",
"lambda",
"p",
",",
"mu",
",",
"k_agg",
":",
"(",
"k_agg",
"*",
"p",
")",
"/",
"(",
"1",
"-",
"(",
"1",
"+",
"p",
")",
"**",
"-",
"k_agg",
")",
"-",
"mu",
"# The upper... | Calculates p parameter for truncated negative binomial
Function given in Sampford 1955, equation 4
Note that omega = 1 / 1 + p in Sampford | [
"Calculates",
"p",
"parameter",
"for",
"truncated",
"negative",
"binomial"
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L879-L892 |
39,457 | jkitzes/macroeco | macroeco/models/_distributions.py | _ln_choose | def _ln_choose(n, k_agg):
'''
log binomial coefficient with extended gamma factorials. n and k_agg may be
int or array - if both array, must be the same length.
'''
gammaln = special.gammaln
return gammaln(n + 1) - (gammaln(k_agg + 1) + gammaln(n - k_agg + 1)) | python | def _ln_choose(n, k_agg):
'''
log binomial coefficient with extended gamma factorials. n and k_agg may be
int or array - if both array, must be the same length.
'''
gammaln = special.gammaln
return gammaln(n + 1) - (gammaln(k_agg + 1) + gammaln(n - k_agg + 1)) | [
"def",
"_ln_choose",
"(",
"n",
",",
"k_agg",
")",
":",
"gammaln",
"=",
"special",
".",
"gammaln",
"return",
"gammaln",
"(",
"n",
"+",
"1",
")",
"-",
"(",
"gammaln",
"(",
"k_agg",
"+",
"1",
")",
"+",
"gammaln",
"(",
"n",
"-",
"k_agg",
"+",
"1",
... | log binomial coefficient with extended gamma factorials. n and k_agg may be
int or array - if both array, must be the same length. | [
"log",
"binomial",
"coefficient",
"with",
"extended",
"gamma",
"factorials",
".",
"n",
"and",
"k_agg",
"may",
"be",
"int",
"or",
"array",
"-",
"if",
"both",
"array",
"must",
"be",
"the",
"same",
"length",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L1023-L1030 |
39,458 | jkitzes/macroeco | macroeco/models/_distributions.py | _solve_k_from_mu | def _solve_k_from_mu(data, k_array, nll, *args):
"""
For given args, return k_agg from searching some k_range.
Parameters
----------
data : array
k_range : array
nll : function
args :
Returns
--------
:float
Minimum k_agg
"""
# TODO: See if a root finder l... | python | def _solve_k_from_mu(data, k_array, nll, *args):
"""
For given args, return k_agg from searching some k_range.
Parameters
----------
data : array
k_range : array
nll : function
args :
Returns
--------
:float
Minimum k_agg
"""
# TODO: See if a root finder l... | [
"def",
"_solve_k_from_mu",
"(",
"data",
",",
"k_array",
",",
"nll",
",",
"*",
"args",
")",
":",
"# TODO: See if a root finder like fminbound would work with Decimal used in",
"# logpmf method (will this work with arrays?)",
"nll_array",
"=",
"np",
".",
"zeros",
"(",
"len",
... | For given args, return k_agg from searching some k_range.
Parameters
----------
data : array
k_range : array
nll : function
args :
Returns
--------
:float
Minimum k_agg | [
"For",
"given",
"args",
"return",
"k_agg",
"from",
"searching",
"some",
"k_range",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L1033-L1061 |
39,459 | jkitzes/macroeco | macroeco/models/_distributions.py | _expon_solve_lam_from_mu | def _expon_solve_lam_from_mu(mu, b):
"""
For the expon_uptrunc, given mu and b, return lam.
Similar to geom_uptrunc
"""
def lam_eq(lam, mu, b):
# Small offset added to denominator to avoid 0/0 erors
lam, mu, b = Decimal(lam), Decimal(mu), Decimal(b)
return ( (1 - (lam*b + 1)... | python | def _expon_solve_lam_from_mu(mu, b):
"""
For the expon_uptrunc, given mu and b, return lam.
Similar to geom_uptrunc
"""
def lam_eq(lam, mu, b):
# Small offset added to denominator to avoid 0/0 erors
lam, mu, b = Decimal(lam), Decimal(mu), Decimal(b)
return ( (1 - (lam*b + 1)... | [
"def",
"_expon_solve_lam_from_mu",
"(",
"mu",
",",
"b",
")",
":",
"def",
"lam_eq",
"(",
"lam",
",",
"mu",
",",
"b",
")",
":",
"# Small offset added to denominator to avoid 0/0 erors",
"lam",
",",
"mu",
",",
"b",
"=",
"Decimal",
"(",
"lam",
")",
",",
"Decim... | For the expon_uptrunc, given mu and b, return lam.
Similar to geom_uptrunc | [
"For",
"the",
"expon_uptrunc",
"given",
"mu",
"and",
"b",
"return",
"lam",
".",
"Similar",
"to",
"geom_uptrunc"
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L1823-L1835 |
39,460 | jkitzes/macroeco | macroeco/models/_distributions.py | _make_rank | def _make_rank(dist_obj, n, mu, sigma, crit=0.5, upper=10000, xtol=1):
"""
Make rank distribution using both ppf and brute force.
Setting crit = 1 is equivalent to just using the ppf
Parameters
----------
{0}
"""
qs = (np.arange(1, n + 1) - 0.5) / n
rank = np.empty(len(qs))
b... | python | def _make_rank(dist_obj, n, mu, sigma, crit=0.5, upper=10000, xtol=1):
"""
Make rank distribution using both ppf and brute force.
Setting crit = 1 is equivalent to just using the ppf
Parameters
----------
{0}
"""
qs = (np.arange(1, n + 1) - 0.5) / n
rank = np.empty(len(qs))
b... | [
"def",
"_make_rank",
"(",
"dist_obj",
",",
"n",
",",
"mu",
",",
"sigma",
",",
"crit",
"=",
"0.5",
",",
"upper",
"=",
"10000",
",",
"xtol",
"=",
"1",
")",
":",
"qs",
"=",
"(",
"np",
".",
"arange",
"(",
"1",
",",
"n",
"+",
"1",
")",
"-",
"0.5... | Make rank distribution using both ppf and brute force.
Setting crit = 1 is equivalent to just using the ppf
Parameters
----------
{0} | [
"Make",
"rank",
"distribution",
"using",
"both",
"ppf",
"and",
"brute",
"force",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L1976-L2014 |
39,461 | jkitzes/macroeco | macroeco/models/_distributions.py | _mean_var | def _mean_var(vals, pmf):
"""
Calculates the mean and variance from vals and pmf
Parameters
----------
vals : ndarray
Value range for a distribution
pmf : ndarray
pmf values corresponding with vals
Returns
-------
: tuple
(mean, variance)
"""
mean ... | python | def _mean_var(vals, pmf):
"""
Calculates the mean and variance from vals and pmf
Parameters
----------
vals : ndarray
Value range for a distribution
pmf : ndarray
pmf values corresponding with vals
Returns
-------
: tuple
(mean, variance)
"""
mean ... | [
"def",
"_mean_var",
"(",
"vals",
",",
"pmf",
")",
":",
"mean",
"=",
"np",
".",
"sum",
"(",
"vals",
"*",
"pmf",
")",
"var",
"=",
"np",
".",
"sum",
"(",
"vals",
"**",
"2",
"*",
"pmf",
")",
"-",
"mean",
"**",
"2",
"return",
"mean",
",",
"var"
] | Calculates the mean and variance from vals and pmf
Parameters
----------
vals : ndarray
Value range for a distribution
pmf : ndarray
pmf values corresponding with vals
Returns
-------
: tuple
(mean, variance) | [
"Calculates",
"the",
"mean",
"and",
"variance",
"from",
"vals",
"and",
"pmf"
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L2017-L2037 |
39,462 | jkitzes/macroeco | macroeco/models/_distributions.py | lognorm_gen._pdf_w_mean | def _pdf_w_mean(self, x, mean, sigma):
"""
Calculates the pdf of a lognormal distribution with parameters mean
and sigma
Parameters
----------
mean : float or ndarray
Mean of the lognormal distribution
sigma : float or ndarray
Sigma parame... | python | def _pdf_w_mean(self, x, mean, sigma):
"""
Calculates the pdf of a lognormal distribution with parameters mean
and sigma
Parameters
----------
mean : float or ndarray
Mean of the lognormal distribution
sigma : float or ndarray
Sigma parame... | [
"def",
"_pdf_w_mean",
"(",
"self",
",",
"x",
",",
"mean",
",",
"sigma",
")",
":",
"# Lognorm pmf with mean for optimization",
"mu",
",",
"sigma",
"=",
"self",
".",
"translate_args",
"(",
"mean",
",",
"sigma",
")",
"return",
"self",
".",
"logpdf",
"(",
"x",... | Calculates the pdf of a lognormal distribution with parameters mean
and sigma
Parameters
----------
mean : float or ndarray
Mean of the lognormal distribution
sigma : float or ndarray
Sigma parameter of the lognormal distribution
Returns
... | [
"Calculates",
"the",
"pdf",
"of",
"a",
"lognormal",
"distribution",
"with",
"parameters",
"mean",
"and",
"sigma"
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L1935-L1955 |
39,463 | soaxelbrooke/join | join/_join_funcs.py | union_join | def union_join(left, right, left_as='left', right_as='right'):
"""
Join function truest to the SQL style join. Merges both objects together in a sum-type,
saving references to each parent in ``left`` and ``right`` attributes.
>>> Dog = namedtuple('Dog', ['name', 'woof', 'weight'])
>>> dog ... | python | def union_join(left, right, left_as='left', right_as='right'):
"""
Join function truest to the SQL style join. Merges both objects together in a sum-type,
saving references to each parent in ``left`` and ``right`` attributes.
>>> Dog = namedtuple('Dog', ['name', 'woof', 'weight'])
>>> dog ... | [
"def",
"union_join",
"(",
"left",
",",
"right",
",",
"left_as",
"=",
"'left'",
",",
"right_as",
"=",
"'right'",
")",
":",
"attrs",
"=",
"{",
"}",
"attrs",
".",
"update",
"(",
"get_object_attrs",
"(",
"right",
")",
")",
"attrs",
".",
"update",
"(",
"g... | Join function truest to the SQL style join. Merges both objects together in a sum-type,
saving references to each parent in ``left`` and ``right`` attributes.
>>> Dog = namedtuple('Dog', ['name', 'woof', 'weight'])
>>> dog = Dog('gatsby', 'Ruff!', 15)
>>> Cat = namedtuple('Cat', ['name', '... | [
"Join",
"function",
"truest",
"to",
"the",
"SQL",
"style",
"join",
".",
"Merges",
"both",
"objects",
"together",
"in",
"a",
"sum",
"-",
"type",
"saving",
"references",
"to",
"each",
"parent",
"in",
"left",
"and",
"right",
"attributes",
"."
] | c84fca68ab6a52b1cee526065dc9f5a691764e69 | https://github.com/soaxelbrooke/join/blob/c84fca68ab6a52b1cee526065dc9f5a691764e69/join/_join_funcs.py#L42-L73 |
39,464 | mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Key/RPiKeyButtons.py | RPiKeyButtons.configKeyButtons | def configKeyButtons( self, enableButtons = [], bounceTime = DEF_BOUNCE_TIME_NORMAL, pullUpDown = GPIO.PUD_UP, event = GPIO.BOTH ):
"""!
\~english
Config multi key buttons IO and event on same time
@param enableButtons: an array of key button configs. eg. <br>
[{ "id":BU... | python | def configKeyButtons( self, enableButtons = [], bounceTime = DEF_BOUNCE_TIME_NORMAL, pullUpDown = GPIO.PUD_UP, event = GPIO.BOTH ):
"""!
\~english
Config multi key buttons IO and event on same time
@param enableButtons: an array of key button configs. eg. <br>
[{ "id":BU... | [
"def",
"configKeyButtons",
"(",
"self",
",",
"enableButtons",
"=",
"[",
"]",
",",
"bounceTime",
"=",
"DEF_BOUNCE_TIME_NORMAL",
",",
"pullUpDown",
"=",
"GPIO",
".",
"PUD_UP",
",",
"event",
"=",
"GPIO",
".",
"BOTH",
")",
":",
"for",
"key",
"in",
"enableButto... | !
\~english
Config multi key buttons IO and event on same time
@param enableButtons: an array of key button configs. eg. <br>
[{ "id":BUTTON_ACT_A, "callback": aCallbackFun }, ... ]
@param bounceTime: Default set to DEF_BOUNCE_TIME_NORMAL
@param pullUpDown: Defau... | [
"!",
"\\",
"~english",
"Config",
"multi",
"key",
"buttons",
"IO",
"and",
"event",
"on",
"same",
"time"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Key/RPiKeyButtons.py#L161-L189 |
39,465 | azraq27/gini | gini/matching.py | best_item_from_list | def best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False):
'''Returns just the best item, or ``None``'''
match = best_match_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess)
if match:
return match[0]
return None | python | def best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False):
'''Returns just the best item, or ``None``'''
match = best_match_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess)
if match:
return match[0]
return None | [
"def",
"best_item_from_list",
"(",
"item",
",",
"options",
",",
"fuzzy",
"=",
"90",
",",
"fname_match",
"=",
"True",
",",
"fuzzy_fragment",
"=",
"None",
",",
"guess",
"=",
"False",
")",
":",
"match",
"=",
"best_match_from_list",
"(",
"item",
",",
"options"... | Returns just the best item, or ``None`` | [
"Returns",
"just",
"the",
"best",
"item",
"or",
"None"
] | 3c2b5265d096d606b303bfe25ac9adb74b8cee14 | https://github.com/azraq27/gini/blob/3c2b5265d096d606b303bfe25ac9adb74b8cee14/gini/matching.py#L63-L68 |
39,466 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | create_hlk_sw16_connection | async def create_hlk_sw16_connection(port=None, host=None,
disconnect_callback=None,
reconnect_callback=None, loop=None,
logger=None, timeout=None,
reconnect_interval=None)... | python | async def create_hlk_sw16_connection(port=None, host=None,
disconnect_callback=None,
reconnect_callback=None, loop=None,
logger=None, timeout=None,
reconnect_interval=None)... | [
"async",
"def",
"create_hlk_sw16_connection",
"(",
"port",
"=",
"None",
",",
"host",
"=",
"None",
",",
"disconnect_callback",
"=",
"None",
",",
"reconnect_callback",
"=",
"None",
",",
"loop",
"=",
"None",
",",
"logger",
"=",
"None",
",",
"timeout",
"=",
"N... | Create HLK-SW16 Client class. | [
"Create",
"HLK",
"-",
"SW16",
"Client",
"class",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L292-L305 |
39,467 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol._reset_timeout | def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | python | def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | [
"def",
"_reset_timeout",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timeout",
":",
"self",
".",
"_timeout",
".",
"cancel",
"(",
")",
"self",
".",
"_timeout",
"=",
"self",
".",
"loop",
".",
"call_later",
"(",
"self",
".",
"client",
".",
"timeout",
",... | Reset timeout for date keep alive. | [
"Reset",
"timeout",
"for",
"date",
"keep",
"alive",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L30-L35 |
39,468 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol.reset_cmd_timeout | def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | python | def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | [
"def",
"reset_cmd_timeout",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cmd_timeout",
":",
"self",
".",
"_cmd_timeout",
".",
"cancel",
"(",
")",
"self",
".",
"_cmd_timeout",
"=",
"self",
".",
"loop",
".",
"call_later",
"(",
"self",
".",
"client",
".",
... | Reset timeout for command execution. | [
"Reset",
"timeout",
"for",
"command",
"execution",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L37-L42 |
39,469 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol._valid_packet | def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18... | python | def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18... | [
"def",
"_valid_packet",
"(",
"raw_packet",
")",
":",
"if",
"raw_packet",
"[",
"0",
":",
"1",
"]",
"!=",
"b'\\xcc'",
":",
"return",
"False",
"if",
"len",
"(",
"raw_packet",
")",
"!=",
"19",
":",
"return",
"False",
"checksum",
"=",
"0",
"for",
"i",
"in... | Validate incoming packet. | [
"Validate",
"incoming",
"packet",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L62-L73 |
39,470 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol._handle_raw_packet | def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
... | python | def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
... | [
"def",
"_handle_raw_packet",
"(",
"self",
",",
"raw_packet",
")",
":",
"if",
"raw_packet",
"[",
"1",
":",
"2",
"]",
"==",
"b'\\x1f'",
":",
"self",
".",
"_reset_timeout",
"(",
")",
"year",
"=",
"raw_packet",
"[",
"2",
"]",
"month",
"=",
"raw_packet",
"[... | Parse incoming packet. | [
"Parse",
"incoming",
"packet",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L75-L125 |
39,471 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol.send_packet | def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_pack... | python | def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_pack... | [
"def",
"send_packet",
"(",
"self",
")",
":",
"waiter",
",",
"packet",
"=",
"self",
".",
"client",
".",
"waiters",
".",
"popleft",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'sending packet: %s'",
",",
"binascii",
".",
"hexlify",
"(",
"packet",
... | Write next packet in send queue. | [
"Write",
"next",
"packet",
"in",
"send",
"queue",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L127-L135 |
39,472 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol.format_packet | def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim | python | def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim | [
"def",
"format_packet",
"(",
"command",
")",
":",
"frame_header",
"=",
"b\"\\xaa\"",
"verify",
"=",
"b\"\\x0b\"",
"send_delim",
"=",
"b\"\\xbb\"",
"return",
"frame_header",
"+",
"command",
".",
"ljust",
"(",
"17",
",",
"b\"\\x00\"",
")",
"+",
"verify",
"+",
... | Format packet to be sent. | [
"Format",
"packet",
"to",
"be",
"sent",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L138-L143 |
39,473 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.setup | async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop,... | python | async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop,... | [
"async",
"def",
"setup",
"(",
"self",
")",
":",
"while",
"True",
":",
"fut",
"=",
"self",
".",
"loop",
".",
"create_connection",
"(",
"lambda",
":",
"SW16Protocol",
"(",
"self",
",",
"disconnect_callback",
"=",
"self",
".",
"handle_disconnect_callback",
",",... | Set up the connection with automatic retry. | [
"Set",
"up",
"the",
"connection",
"with",
"automatic",
"retry",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L188-L211 |
39,474 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.stop | def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close() | python | def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"reconnect",
"=",
"False",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Shutting down.\"",
")",
"if",
"self",
".",
"transport",
":",
"self",
".",
"transport",
".",
"close",
"(",
")"
] | Shut down transport. | [
"Shut",
"down",
"transport",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L213-L218 |
39,475 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.handle_disconnect_callback | async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
aw... | python | async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
aw... | [
"async",
"def",
"handle_disconnect_callback",
"(",
"self",
")",
":",
"self",
".",
"is_connected",
"=",
"False",
"if",
"self",
".",
"disconnect_callback",
":",
"self",
".",
"disconnect_callback",
"(",
")",
"if",
"self",
".",
"reconnect",
":",
"self",
".",
"lo... | Reconnect automatically unless stopping. | [
"Reconnect",
"automatically",
"unless",
"stopping",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L220-L233 |
39,476 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.register_status_callback | def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback) | python | def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback) | [
"def",
"register_status_callback",
"(",
"self",
",",
"callback",
",",
"switch",
")",
":",
"if",
"self",
".",
"status_callbacks",
".",
"get",
"(",
"switch",
",",
"None",
")",
"is",
"None",
":",
"self",
".",
"status_callbacks",
"[",
"switch",
"]",
"=",
"["... | Register a callback which will fire when state changes. | [
"Register",
"a",
"callback",
"which",
"will",
"fire",
"when",
"state",
"changes",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L235-L239 |
39,477 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client._send | def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut | python | def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut | [
"def",
"_send",
"(",
"self",
",",
"packet",
")",
":",
"fut",
"=",
"self",
".",
"loop",
".",
"create_future",
"(",
")",
"self",
".",
"waiters",
".",
"append",
"(",
"(",
"fut",
",",
"packet",
")",
")",
"if",
"self",
".",
"waiters",
"and",
"self",
"... | Add packet to send queue. | [
"Add",
"packet",
"to",
"send",
"queue",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L241-L247 |
39,478 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.turn_on | async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
s... | python | async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
s... | [
"async",
"def",
"turn_on",
"(",
"self",
",",
"switch",
"=",
"None",
")",
":",
"if",
"switch",
"is",
"not",
"None",
":",
"switch",
"=",
"codecs",
".",
"decode",
"(",
"switch",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
",",
"'hex'",
")",
"packet",
"... | Turn on relay. | [
"Turn",
"on",
"relay",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L249-L257 |
39,479 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.turn_off | async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
... | python | async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
... | [
"async",
"def",
"turn_off",
"(",
"self",
",",
"switch",
"=",
"None",
")",
":",
"if",
"switch",
"is",
"not",
"None",
":",
"switch",
"=",
"codecs",
".",
"decode",
"(",
"switch",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
",",
"'hex'",
")",
"packet",
... | Turn off relay. | [
"Turn",
"off",
"relay",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L259-L267 |
39,480 | jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.status | async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = state... | python | async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = state... | [
"async",
"def",
"status",
"(",
"self",
",",
"switch",
"=",
"None",
")",
":",
"if",
"switch",
"is",
"not",
"None",
":",
"if",
"self",
".",
"waiters",
"or",
"self",
".",
"in_transaction",
":",
"fut",
"=",
"self",
".",
"loop",
".",
"create_future",
"(",... | Get current relay status. | [
"Get",
"current",
"relay",
"status",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L269-L289 |
39,481 | ThomasChiroux/attowiki | src/attowiki/git_tools.py | _delta_dir | def _delta_dir():
"""returns the relative path of the current directory to the git
repository.
This path will be added the 'filename' path to find the file.
It current_dir is the git root, this function returns an empty string.
Keyword Arguments:
<none>
Returns:
str -- relative... | python | def _delta_dir():
"""returns the relative path of the current directory to the git
repository.
This path will be added the 'filename' path to find the file.
It current_dir is the git root, this function returns an empty string.
Keyword Arguments:
<none>
Returns:
str -- relative... | [
"def",
"_delta_dir",
"(",
")",
":",
"repo",
"=",
"Repo",
"(",
")",
"current_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"repo_dir",
"=",
"repo",
".",
"tree",
"(",
")",
".",
"abspath",
"delta_dir",
"=",
"current_dir",
".",
"replace",
"(",
"repo_dir",
",... | returns the relative path of the current directory to the git
repository.
This path will be added the 'filename' path to find the file.
It current_dir is the git root, this function returns an empty string.
Keyword Arguments:
<none>
Returns:
str -- relative path of the current dir ... | [
"returns",
"the",
"relative",
"path",
"of",
"the",
"current",
"directory",
"to",
"the",
"git",
"repository",
".",
"This",
"path",
"will",
"be",
"added",
"the",
"filename",
"path",
"to",
"find",
"the",
"file",
".",
"It",
"current_dir",
"is",
"the",
"git",
... | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L32-L52 |
39,482 | ThomasChiroux/attowiki | src/attowiki/git_tools.py | add_file_to_repo | def add_file_to_repo(filename):
"""Add a file to the git repo
This method does the same than a ::
$ git add filename
Keyword Arguments:
:filename: (str) -- name of the file to commit
Returns:
<nothing>
"""
try:
repo = Repo()
index = repo.index
... | python | def add_file_to_repo(filename):
"""Add a file to the git repo
This method does the same than a ::
$ git add filename
Keyword Arguments:
:filename: (str) -- name of the file to commit
Returns:
<nothing>
"""
try:
repo = Repo()
index = repo.index
... | [
"def",
"add_file_to_repo",
"(",
"filename",
")",
":",
"try",
":",
"repo",
"=",
"Repo",
"(",
")",
"index",
"=",
"repo",
".",
"index",
"index",
".",
"add",
"(",
"[",
"_delta_dir",
"(",
")",
"+",
"filename",
"]",
")",
"except",
"Exception",
"as",
"e",
... | Add a file to the git repo
This method does the same than a ::
$ git add filename
Keyword Arguments:
:filename: (str) -- name of the file to commit
Returns:
<nothing> | [
"Add",
"a",
"file",
"to",
"the",
"git",
"repo"
] | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L94-L112 |
39,483 | ThomasChiroux/attowiki | src/attowiki/git_tools.py | reset_to_last_commit | def reset_to_last_commit():
"""reset a modified file to his last commit status
This method does the same than a ::
$ git reset --hard
Keyword Arguments:
<none>
Returns:
<nothing>
"""
try:
repo = Repo()
gitcmd = repo.git
gitcmd.reset(hard=True)
... | python | def reset_to_last_commit():
"""reset a modified file to his last commit status
This method does the same than a ::
$ git reset --hard
Keyword Arguments:
<none>
Returns:
<nothing>
"""
try:
repo = Repo()
gitcmd = repo.git
gitcmd.reset(hard=True)
... | [
"def",
"reset_to_last_commit",
"(",
")",
":",
"try",
":",
"repo",
"=",
"Repo",
"(",
")",
"gitcmd",
"=",
"repo",
".",
"git",
"gitcmd",
".",
"reset",
"(",
"hard",
"=",
"True",
")",
"except",
"Exception",
":",
"pass"
] | reset a modified file to his last commit status
This method does the same than a ::
$ git reset --hard
Keyword Arguments:
<none>
Returns:
<nothing> | [
"reset",
"a",
"modified",
"file",
"to",
"his",
"last",
"commit",
"status"
] | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L115-L133 |
39,484 | ThomasChiroux/attowiki | src/attowiki/git_tools.py | commit_history | def commit_history(filename):
"""Retrieve the commit history for a given filename.
Keyword Arguments:
:filename: (str) -- full name of the file
Returns:
list of dicts -- list of commit
if the file is not found, returns an empty list
"""
result = []
repo = Repo()... | python | def commit_history(filename):
"""Retrieve the commit history for a given filename.
Keyword Arguments:
:filename: (str) -- full name of the file
Returns:
list of dicts -- list of commit
if the file is not found, returns an empty list
"""
result = []
repo = Repo()... | [
"def",
"commit_history",
"(",
"filename",
")",
":",
"result",
"=",
"[",
"]",
"repo",
"=",
"Repo",
"(",
")",
"for",
"commit",
"in",
"repo",
".",
"head",
".",
"commit",
".",
"iter_parents",
"(",
"paths",
"=",
"_delta_dir",
"(",
")",
"+",
"filename",
")... | Retrieve the commit history for a given filename.
Keyword Arguments:
:filename: (str) -- full name of the file
Returns:
list of dicts -- list of commit
if the file is not found, returns an empty list | [
"Retrieve",
"the",
"commit",
"history",
"for",
"a",
"given",
"filename",
"."
] | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L136-L153 |
39,485 | ThomasChiroux/attowiki | src/attowiki/git_tools.py | read_committed_file | def read_committed_file(gitref, filename):
"""Retrieve the content of a file in an old commit and returns it.
Ketword Arguments:
:gitref: (str) -- full reference of the git commit
:filename: (str) -- name (full path) of the file
Returns:
str -- content of the file
"""
repo ... | python | def read_committed_file(gitref, filename):
"""Retrieve the content of a file in an old commit and returns it.
Ketword Arguments:
:gitref: (str) -- full reference of the git commit
:filename: (str) -- name (full path) of the file
Returns:
str -- content of the file
"""
repo ... | [
"def",
"read_committed_file",
"(",
"gitref",
",",
"filename",
")",
":",
"repo",
"=",
"Repo",
"(",
")",
"commitobj",
"=",
"repo",
".",
"commit",
"(",
"gitref",
")",
"blob",
"=",
"commitobj",
".",
"tree",
"[",
"_delta_dir",
"(",
")",
"+",
"filename",
"]"... | Retrieve the content of a file in an old commit and returns it.
Ketword Arguments:
:gitref: (str) -- full reference of the git commit
:filename: (str) -- name (full path) of the file
Returns:
str -- content of the file | [
"Retrieve",
"the",
"content",
"of",
"a",
"file",
"in",
"an",
"old",
"commit",
"and",
"returns",
"it",
"."
] | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L156-L170 |
39,486 | stevepeak/dictime | dictime/dictime.py | dictime.get | def get(self, key, _else=None):
"""The method to get an assets value
"""
with self._lock:
self.expired()
# see if everything expired
try:
value = self._dict[key].get()
return value
except KeyError:
re... | python | def get(self, key, _else=None):
"""The method to get an assets value
"""
with self._lock:
self.expired()
# see if everything expired
try:
value = self._dict[key].get()
return value
except KeyError:
re... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"_else",
"=",
"None",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"expired",
"(",
")",
"# see if everything expired",
"try",
":",
"value",
"=",
"self",
".",
"_dict",
"[",
"key",
"]",
".",
"g... | The method to get an assets value | [
"The",
"method",
"to",
"get",
"an",
"assets",
"value"
] | 6d8724bed5a7844e47a9c16a233f8db494c98c61 | https://github.com/stevepeak/dictime/blob/6d8724bed5a7844e47a9c16a233f8db494c98c61/dictime/dictime.py#L45-L57 |
39,487 | stevepeak/dictime | dictime/dictime.py | dictime.set | def set(self, key, value, expires=None, future=None):
"""Set a value
"""
# assert the values above
with self._lock:
try:
self._dict[key].set(value, expires=expires, future=future)
except KeyError:
self._dict[key] = moment(value, exp... | python | def set(self, key, value, expires=None, future=None):
"""Set a value
"""
# assert the values above
with self._lock:
try:
self._dict[key].set(value, expires=expires, future=future)
except KeyError:
self._dict[key] = moment(value, exp... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"expires",
"=",
"None",
",",
"future",
"=",
"None",
")",
":",
"# assert the values above",
"with",
"self",
".",
"_lock",
":",
"try",
":",
"self",
".",
"_dict",
"[",
"key",
"]",
".",
"set",
"... | Set a value | [
"Set",
"a",
"value"
] | 6d8724bed5a7844e47a9c16a233f8db494c98c61 | https://github.com/stevepeak/dictime/blob/6d8724bed5a7844e47a9c16a233f8db494c98c61/dictime/dictime.py#L65-L74 |
39,488 | stevepeak/dictime | dictime/dictime.py | dictime.values | def values(self):
"""Will only return the current values
"""
self.expired()
values = []
for key in self._dict.keys():
try:
value = self._dict[key].get()
values.append(value)
except:
continue
return va... | python | def values(self):
"""Will only return the current values
"""
self.expired()
values = []
for key in self._dict.keys():
try:
value = self._dict[key].get()
values.append(value)
except:
continue
return va... | [
"def",
"values",
"(",
"self",
")",
":",
"self",
".",
"expired",
"(",
")",
"values",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"_dict",
".",
"keys",
"(",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"_dict",
"[",
"key",
"]",
".",
"ge... | Will only return the current values | [
"Will",
"only",
"return",
"the",
"current",
"values"
] | 6d8724bed5a7844e47a9c16a233f8db494c98c61 | https://github.com/stevepeak/dictime/blob/6d8724bed5a7844e47a9c16a233f8db494c98c61/dictime/dictime.py#L110-L121 |
39,489 | stevepeak/dictime | dictime/dictime.py | dictime.has_key | def has_key(self, key):
"""Does the key exist?
This method will check to see if it has expired too.
"""
if key in self._dict:
try:
self[key]
return True
except ValueError:
return False
except KeyError:
... | python | def has_key(self, key):
"""Does the key exist?
This method will check to see if it has expired too.
"""
if key in self._dict:
try:
self[key]
return True
except ValueError:
return False
except KeyError:
... | [
"def",
"has_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_dict",
":",
"try",
":",
"self",
"[",
"key",
"]",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False",
"except",
"KeyError",
":",
"return",
"False",
"r... | Does the key exist?
This method will check to see if it has expired too. | [
"Does",
"the",
"key",
"exist?",
"This",
"method",
"will",
"check",
"to",
"see",
"if",
"it",
"has",
"expired",
"too",
"."
] | 6d8724bed5a7844e47a9c16a233f8db494c98c61 | https://github.com/stevepeak/dictime/blob/6d8724bed5a7844e47a9c16a233f8db494c98c61/dictime/dictime.py#L123-L135 |
39,490 | LREN-CHUV/data-tracking | data_tracking/dicom_import.py | dicom2db | def dicom2db(file_path, file_type, is_copy, step_id, db_conn, sid_by_patient=False, pid_in_vid=False,
visit_in_path=False, rep_in_path=False):
"""Extract some meta-data from a DICOM file and store in a DB.
Arguments:
:param file_path: File path.
:param file_type: File type (should be 'DICO... | python | def dicom2db(file_path, file_type, is_copy, step_id, db_conn, sid_by_patient=False, pid_in_vid=False,
visit_in_path=False, rep_in_path=False):
"""Extract some meta-data from a DICOM file and store in a DB.
Arguments:
:param file_path: File path.
:param file_type: File type (should be 'DICO... | [
"def",
"dicom2db",
"(",
"file_path",
",",
"file_type",
",",
"is_copy",
",",
"step_id",
",",
"db_conn",
",",
"sid_by_patient",
"=",
"False",
",",
"pid_in_vid",
"=",
"False",
",",
"visit_in_path",
"=",
"False",
",",
"rep_in_path",
"=",
"False",
")",
":",
"gl... | Extract some meta-data from a DICOM file and store in a DB.
Arguments:
:param file_path: File path.
:param file_type: File type (should be 'DICOM').
:param is_copy: Indicate if this file is a copy.
:param step_id: Step ID
:param db_conn: Database connection.
:param sid_by_patient: Rarely, a... | [
"Extract",
"some",
"meta",
"-",
"data",
"from",
"a",
"DICOM",
"file",
"and",
"store",
"in",
"a",
"DB",
"."
] | f645a0d6426e6019c92d5aaf4be225cff2864417 | https://github.com/LREN-CHUV/data-tracking/blob/f645a0d6426e6019c92d5aaf4be225cff2864417/data_tracking/dicom_import.py#L25-L77 |
39,491 | mixer/beam-interactive-python | beam_interactive/proto/rw.py | _Decoder.remaining_bytes | def remaining_bytes(self, meta=True):
"""
Returns the remaining, unread bytes from the buffer.
"""
pos, self._pos = self._pos, len(self.buffer)
return self.buffer[pos:] | python | def remaining_bytes(self, meta=True):
"""
Returns the remaining, unread bytes from the buffer.
"""
pos, self._pos = self._pos, len(self.buffer)
return self.buffer[pos:] | [
"def",
"remaining_bytes",
"(",
"self",
",",
"meta",
"=",
"True",
")",
":",
"pos",
",",
"self",
".",
"_pos",
"=",
"self",
".",
"_pos",
",",
"len",
"(",
"self",
".",
"buffer",
")",
"return",
"self",
".",
"buffer",
"[",
"pos",
":",
"]"
] | Returns the remaining, unread bytes from the buffer. | [
"Returns",
"the",
"remaining",
"unread",
"bytes",
"from",
"the",
"buffer",
"."
] | e035bc45515dea9315b77648a24b5ae8685aa5cf | https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/proto/rw.py#L28-L33 |
39,492 | mixer/beam-interactive-python | beam_interactive/proto/rw.py | _Decoder.decode | def decode(self, bytes):
"""
Decodes the packet off the byte string.
"""
self.buffer = bytes
self._pos = 0
Packet = identifier.get_packet_from_id(self._read_variunt())
# unknown packets will be None from the identifier
if Packet is None:
ret... | python | def decode(self, bytes):
"""
Decodes the packet off the byte string.
"""
self.buffer = bytes
self._pos = 0
Packet = identifier.get_packet_from_id(self._read_variunt())
# unknown packets will be None from the identifier
if Packet is None:
ret... | [
"def",
"decode",
"(",
"self",
",",
"bytes",
")",
":",
"self",
".",
"buffer",
"=",
"bytes",
"self",
".",
"_pos",
"=",
"0",
"Packet",
"=",
"identifier",
".",
"get_packet_from_id",
"(",
"self",
".",
"_read_variunt",
"(",
")",
")",
"# unknown packets will be N... | Decodes the packet off the byte string. | [
"Decodes",
"the",
"packet",
"off",
"the",
"byte",
"string",
"."
] | e035bc45515dea9315b77648a24b5ae8685aa5cf | https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/proto/rw.py#L35-L51 |
39,493 | mixer/beam-interactive-python | beam_interactive/proto/rw.py | _Encoder.encode | def encode(self, packet):
"""
Pushes a packet to the writer, encoding it on the internal
buffer.
"""
id = identifier.get_packet_id(packet)
if id is None:
raise EncoderException('unknown packet')
self._write_variunt(id)
self._write(packet.Seri... | python | def encode(self, packet):
"""
Pushes a packet to the writer, encoding it on the internal
buffer.
"""
id = identifier.get_packet_id(packet)
if id is None:
raise EncoderException('unknown packet')
self._write_variunt(id)
self._write(packet.Seri... | [
"def",
"encode",
"(",
"self",
",",
"packet",
")",
":",
"id",
"=",
"identifier",
".",
"get_packet_id",
"(",
"packet",
")",
"if",
"id",
"is",
"None",
":",
"raise",
"EncoderException",
"(",
"'unknown packet'",
")",
"self",
".",
"_write_variunt",
"(",
"id",
... | Pushes a packet to the writer, encoding it on the internal
buffer. | [
"Pushes",
"a",
"packet",
"to",
"the",
"writer",
"encoding",
"it",
"on",
"the",
"internal",
"buffer",
"."
] | e035bc45515dea9315b77648a24b5ae8685aa5cf | https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/proto/rw.py#L71-L84 |
39,494 | wuher/devil | devil/fields/factory.py | Factory.create | def create(self, data):
""" Create object from the given data.
The given data may or may not have been validated prior to calling
this function. This function will try its best in creating the object.
If the resulting object cannot be produced, raises ``ValidationError``.
The s... | python | def create(self, data):
""" Create object from the given data.
The given data may or may not have been validated prior to calling
this function. This function will try its best in creating the object.
If the resulting object cannot be produced, raises ``ValidationError``.
The s... | [
"def",
"create",
"(",
"self",
",",
"data",
")",
":",
"# todo: copy-paste code from representation.validate -> refactor",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"prototype",
"=",
"{",
"}",
"errors",
"=",
"{",
"}",
"# create and populate the prototype",
"f... | Create object from the given data.
The given data may or may not have been validated prior to calling
this function. This function will try its best in creating the object.
If the resulting object cannot be produced, raises ``ValidationError``.
The spec can affect how individual fields... | [
"Create",
"object",
"from",
"the",
"given",
"data",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/factory.py#L74-L132 |
39,495 | wuher/devil | devil/fields/factory.py | Factory.serialize | def serialize(self, entity, request=None):
""" Serialize entity into dictionary.
The spec can affect how individual fields will be serialized by
implementing ``serialize()`` for the fields needing customization.
:returns: dictionary
"""
def should_we_insert(value, fiel... | python | def serialize(self, entity, request=None):
""" Serialize entity into dictionary.
The spec can affect how individual fields will be serialized by
implementing ``serialize()`` for the fields needing customization.
:returns: dictionary
"""
def should_we_insert(value, fiel... | [
"def",
"serialize",
"(",
"self",
",",
"entity",
",",
"request",
"=",
"None",
")",
":",
"def",
"should_we_insert",
"(",
"value",
",",
"field_spec",
")",
":",
"return",
"value",
"not",
"in",
"self",
".",
"missing",
"or",
"field_spec",
".",
"required",
"err... | Serialize entity into dictionary.
The spec can affect how individual fields will be serialized by
implementing ``serialize()`` for the fields needing customization.
:returns: dictionary | [
"Serialize",
"entity",
"into",
"dictionary",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/factory.py#L134-L169 |
39,496 | wuher/devil | devil/fields/factory.py | Factory._create_value | def _create_value(self, data, name, spec):
""" Create the value for a field.
:param data: the whole data for the entity (all fields).
:param name: name of the initialized field.
:param spec: spec for the whole entity.
"""
field = getattr(self, 'create_' + name, None)
... | python | def _create_value(self, data, name, spec):
""" Create the value for a field.
:param data: the whole data for the entity (all fields).
:param name: name of the initialized field.
:param spec: spec for the whole entity.
"""
field = getattr(self, 'create_' + name, None)
... | [
"def",
"_create_value",
"(",
"self",
",",
"data",
",",
"name",
",",
"spec",
")",
":",
"field",
"=",
"getattr",
"(",
"self",
",",
"'create_'",
"+",
"name",
",",
"None",
")",
"if",
"field",
":",
"# this factory has a special creator function for this field",
"re... | Create the value for a field.
:param data: the whole data for the entity (all fields).
:param name: name of the initialized field.
:param spec: spec for the whole entity. | [
"Create",
"the",
"value",
"for",
"a",
"field",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/factory.py#L171-L184 |
39,497 | wuher/devil | devil/fields/factory.py | Factory._get_serialize_func | def _get_serialize_func(self, name, spec):
""" Return the function that is used for serialization. """
func = getattr(self, 'serialize_' + name, None)
if func:
# this factory has a special serializer function for this field
return func
func = getattr(spec.fields[n... | python | def _get_serialize_func(self, name, spec):
""" Return the function that is used for serialization. """
func = getattr(self, 'serialize_' + name, None)
if func:
# this factory has a special serializer function for this field
return func
func = getattr(spec.fields[n... | [
"def",
"_get_serialize_func",
"(",
"self",
",",
"name",
",",
"spec",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"'serialize_'",
"+",
"name",
",",
"None",
")",
"if",
"func",
":",
"# this factory has a special serializer function for this field",
"return",
... | Return the function that is used for serialization. | [
"Return",
"the",
"function",
"that",
"is",
"used",
"for",
"serialization",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/factory.py#L186-L195 |
39,498 | wuher/devil | devil/fields/factory.py | Factory._create_mappings | def _create_mappings(self, spec):
""" Create property name map based on aliases. """
ret = dict(zip(set(spec.fields), set(spec.fields)))
ret.update(dict([(n, s.alias) for n, s in spec.fields.items() if s.alias]))
return ret | python | def _create_mappings(self, spec):
""" Create property name map based on aliases. """
ret = dict(zip(set(spec.fields), set(spec.fields)))
ret.update(dict([(n, s.alias) for n, s in spec.fields.items() if s.alias]))
return ret | [
"def",
"_create_mappings",
"(",
"self",
",",
"spec",
")",
":",
"ret",
"=",
"dict",
"(",
"zip",
"(",
"set",
"(",
"spec",
".",
"fields",
")",
",",
"set",
"(",
"spec",
".",
"fields",
")",
")",
")",
"ret",
".",
"update",
"(",
"dict",
"(",
"[",
"(",... | Create property name map based on aliases. | [
"Create",
"property",
"name",
"map",
"based",
"on",
"aliases",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/factory.py#L202-L206 |
39,499 | CodyKochmann/generators | generators/all_substrings.py | all_substrings | def all_substrings(s):
''' yields all substrings of a string '''
join = ''.join
for i in range(1, len(s) + 1):
for sub in window(s, i):
yield join(sub) | python | def all_substrings(s):
''' yields all substrings of a string '''
join = ''.join
for i in range(1, len(s) + 1):
for sub in window(s, i):
yield join(sub) | [
"def",
"all_substrings",
"(",
"s",
")",
":",
"join",
"=",
"''",
".",
"join",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"s",
")",
"+",
"1",
")",
":",
"for",
"sub",
"in",
"window",
"(",
"s",
",",
"i",
")",
":",
"yield",
"join",
"(... | yields all substrings of a string | [
"yields",
"all",
"substrings",
"of",
"a",
"string"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/all_substrings.py#L12-L17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.