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 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
openspending/os-package-registry | os_package_registry/package_registry.py | PackageRegistry.get_stats | def get_stats(self):
"""
Get some stats on the packages in the registry
"""
try:
query = {
# We only care about the aggregations, so don't return the hits
'size': 0,
'aggs': {
'num_packages': {
... | python | def get_stats(self):
"""
Get some stats on the packages in the registry
"""
try:
query = {
# We only care about the aggregations, so don't return the hits
'size': 0,
'aggs': {
'num_packages': {
... | [
"def",
"get_stats",
"(",
"self",
")",
":",
"try",
":",
"query",
"=",
"{",
"'size'",
":",
"0",
",",
"'aggs'",
":",
"{",
"'num_packages'",
":",
"{",
"'value_count'",
":",
"{",
"'field'",
":",
"'id'",
",",
"}",
",",
"}",
",",
"'num_records'",
":",
"{"... | Get some stats on the packages in the registry | [
"Get",
"some",
"stats",
"on",
"the",
"packages",
"in",
"the",
"registry"
] | 02f3628340417ed7d943a6cc6c25ea0469de22cd | https://github.com/openspending/os-package-registry/blob/02f3628340417ed7d943a6cc6c25ea0469de22cd/os_package_registry/package_registry.py#L256-L290 | train |
tjcsl/cslbot | cslbot/commands/fml.py | cmd | def cmd(send, msg, args):
"""Gets a random FML post.
Syntax: {command}
"""
req = get("http://api.fmylife.com/view/random", params={'language': 'en', 'key': args['config']['api']['fmlkey']})
doc = fromstring(req.content)
send(doc.xpath('//text')[0].text) | python | def cmd(send, msg, args):
"""Gets a random FML post.
Syntax: {command}
"""
req = get("http://api.fmylife.com/view/random", params={'language': 'en', 'key': args['config']['api']['fmlkey']})
doc = fromstring(req.content)
send(doc.xpath('//text')[0].text) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"req",
"=",
"get",
"(",
"\"http://api.fmylife.com/view/random\"",
",",
"params",
"=",
"{",
"'language'",
":",
"'en'",
",",
"'key'",
":",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",... | Gets a random FML post.
Syntax: {command} | [
"Gets",
"a",
"random",
"FML",
"post",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/fml.py#L26-L34 | train |
tjcsl/cslbot | cslbot/commands/score.py | cmd | def cmd(send, msg, args):
"""Gets scores.
Syntax: {command} <--high|--low|nick>
"""
if not args['config']['feature'].getboolean('hooks'):
send("Hooks are disabled, and this command depends on hooks. Please contact the bot admin(s).")
return
session = args['db']
parser = argumen... | python | def cmd(send, msg, args):
"""Gets scores.
Syntax: {command} <--high|--low|nick>
"""
if not args['config']['feature'].getboolean('hooks'):
send("Hooks are disabled, and this command depends on hooks. Please contact the bot admin(s).")
return
session = args['db']
parser = argumen... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"args",
"[",
"'config'",
"]",
"[",
"'feature'",
"]",
".",
"getboolean",
"(",
"'hooks'",
")",
":",
"send",
"(",
"\"Hooks are disabled, and this command depends on hooks. Please contact the... | Gets scores.
Syntax: {command} <--high|--low|nick> | [
"Gets",
"scores",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/score.py#L26-L78 | train |
acutesoftware/virtual-AI-simulator | vais/envirosim.py | Params.add_affect | def add_affect(self, name, src, dest, val, condition = None ):
"""
adds how param 'src' affects param 'dest' to the list
"""
self.affects.append(ParamAffects(name, src, dest, val, condition)) | python | def add_affect(self, name, src, dest, val, condition = None ):
"""
adds how param 'src' affects param 'dest' to the list
"""
self.affects.append(ParamAffects(name, src, dest, val, condition)) | [
"def",
"add_affect",
"(",
"self",
",",
"name",
",",
"src",
",",
"dest",
",",
"val",
",",
"condition",
"=",
"None",
")",
":",
"self",
".",
"affects",
".",
"append",
"(",
"ParamAffects",
"(",
"name",
",",
"src",
",",
"dest",
",",
"val",
",",
"conditi... | adds how param 'src' affects param 'dest' to the list | [
"adds",
"how",
"param",
"src",
"affects",
"param",
"dest",
"to",
"the",
"list"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/envirosim.py#L63-L67 | train |
acutesoftware/virtual-AI-simulator | vais/envirosim.py | Params.get_by_name | def get_by_name(self, nme):
"""
searches list of all parameters and returns the first
param that matches on name
"""
for p in self.params:
if p.name == nme:
return p
return None | python | def get_by_name(self, nme):
"""
searches list of all parameters and returns the first
param that matches on name
"""
for p in self.params:
if p.name == nme:
return p
return None | [
"def",
"get_by_name",
"(",
"self",
",",
"nme",
")",
":",
"for",
"p",
"in",
"self",
".",
"params",
":",
"if",
"p",
".",
"name",
"==",
"nme",
":",
"return",
"p",
"return",
"None"
] | searches list of all parameters and returns the first
param that matches on name | [
"searches",
"list",
"of",
"all",
"parameters",
"and",
"returns",
"the",
"first",
"param",
"that",
"matches",
"on",
"name"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/envirosim.py#L69-L77 | train |
acutesoftware/virtual-AI-simulator | vais/envirosim.py | Params.get_affects_for_param | def get_affects_for_param(self, nme):
"""
searches all affects and returns a list
that affect the param named 'nme'
"""
res = []
for a in self.affects:
if a.name == nme:
res.append(a)
return res | python | def get_affects_for_param(self, nme):
"""
searches all affects and returns a list
that affect the param named 'nme'
"""
res = []
for a in self.affects:
if a.name == nme:
res.append(a)
return res | [
"def",
"get_affects_for_param",
"(",
"self",
",",
"nme",
")",
":",
"res",
"=",
"[",
"]",
"for",
"a",
"in",
"self",
".",
"affects",
":",
"if",
"a",
".",
"name",
"==",
"nme",
":",
"res",
".",
"append",
"(",
"a",
")",
"return",
"res"
] | searches all affects and returns a list
that affect the param named 'nme' | [
"searches",
"all",
"affects",
"and",
"returns",
"a",
"list",
"that",
"affect",
"the",
"param",
"named",
"nme"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/envirosim.py#L79-L88 | train |
mswart/pyopenmensa | feed.py | buildPrices | def buildPrices(data, roles=None, regex=default_price_regex,
default=None, additional={}):
''' Create a dictionary with price information. Multiple ways are
supported.
:rtype: :obj:`dict`: keys are role as str, values are the prices as
cent count'''
if isinstance(da... | python | def buildPrices(data, roles=None, regex=default_price_regex,
default=None, additional={}):
''' Create a dictionary with price information. Multiple ways are
supported.
:rtype: :obj:`dict`: keys are role as str, values are the prices as
cent count'''
if isinstance(da... | [
"def",
"buildPrices",
"(",
"data",
",",
"roles",
"=",
"None",
",",
"regex",
"=",
"default_price_regex",
",",
"default",
"=",
"None",
",",
"additional",
"=",
"{",
"}",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"[",... | Create a dictionary with price information. Multiple ways are
supported.
:rtype: :obj:`dict`: keys are role as str, values are the prices as
cent count | [
"Create",
"a",
"dictionary",
"with",
"price",
"information",
".",
"Multiple",
"ways",
"are",
"supported",
"."
] | c651da6ace33e2278349636daaa709d043dee6ff | https://github.com/mswart/pyopenmensa/blob/c651da6ace33e2278349636daaa709d043dee6ff/feed.py#L146-L180 | train |
mswart/pyopenmensa | feed.py | buildLegend | def buildLegend(legend=None, text=None, regex=None, key=lambda v: v):
''' Helper method to build or extend a legend from a text. The given regex
will be used to find legend inside the text.
:param dict legend: Initial legend data
:param str text: Text from which should legend information ex... | python | def buildLegend(legend=None, text=None, regex=None, key=lambda v: v):
''' Helper method to build or extend a legend from a text. The given regex
will be used to find legend inside the text.
:param dict legend: Initial legend data
:param str text: Text from which should legend information ex... | [
"def",
"buildLegend",
"(",
"legend",
"=",
"None",
",",
"text",
"=",
"None",
",",
"regex",
"=",
"None",
",",
"key",
"=",
"lambda",
"v",
":",
"v",
")",
":",
"if",
"legend",
"is",
"None",
":",
"legend",
"=",
"{",
"}",
"if",
"text",
"is",
"not",
"N... | Helper method to build or extend a legend from a text. The given regex
will be used to find legend inside the text.
:param dict legend: Initial legend data
:param str text: Text from which should legend information extracted.
None means do no extraction.
:param str regex: Re... | [
"Helper",
"method",
"to",
"build",
"or",
"extend",
"a",
"legend",
"from",
"a",
"text",
".",
"The",
"given",
"regex",
"will",
"be",
"used",
"to",
"find",
"legend",
"inside",
"the",
"text",
"."
] | c651da6ace33e2278349636daaa709d043dee6ff | https://github.com/mswart/pyopenmensa/blob/c651da6ace33e2278349636daaa709d043dee6ff/feed.py#L194-L212 | train |
mswart/pyopenmensa | feed.py | Feed.toTag | def toTag(self, output):
''' This methods returns all data of this feed as feed xml tag
:param output: XML Document to which the data should be added
:type output: xml.dom.DOMImplementation.createDocument
'''
feed = output.createElement('feed')
feed.setAttribute('name', ... | python | def toTag(self, output):
''' This methods returns all data of this feed as feed xml tag
:param output: XML Document to which the data should be added
:type output: xml.dom.DOMImplementation.createDocument
'''
feed = output.createElement('feed')
feed.setAttribute('name', ... | [
"def",
"toTag",
"(",
"self",
",",
"output",
")",
":",
"feed",
"=",
"output",
".",
"createElement",
"(",
"'feed'",
")",
"feed",
".",
"setAttribute",
"(",
"'name'",
",",
"self",
".",
"name",
")",
"feed",
".",
"setAttribute",
"(",
"'priority'",
",",
"str"... | This methods returns all data of this feed as feed xml tag
:param output: XML Document to which the data should be added
:type output: xml.dom.DOMImplementation.createDocument | [
"This",
"methods",
"returns",
"all",
"data",
"of",
"this",
"feed",
"as",
"feed",
"xml",
"tag"
] | c651da6ace33e2278349636daaa709d043dee6ff | https://github.com/mswart/pyopenmensa/blob/c651da6ace33e2278349636daaa709d043dee6ff/feed.py#L251-L281 | train |
mswart/pyopenmensa | feed.py | BaseBuilder.hasMealsFor | def hasMealsFor(self, date):
""" Checks whether for this day are information stored.
:param date: Date of the day
:type date: datetime.date
:rtype: bool"""
date = self._handleDate(date)
if date not in self._days or self._days[date] is False:
retur... | python | def hasMealsFor(self, date):
""" Checks whether for this day are information stored.
:param date: Date of the day
:type date: datetime.date
:rtype: bool"""
date = self._handleDate(date)
if date not in self._days or self._days[date] is False:
retur... | [
"def",
"hasMealsFor",
"(",
"self",
",",
"date",
")",
":",
"date",
"=",
"self",
".",
"_handleDate",
"(",
"date",
")",
"if",
"date",
"not",
"in",
"self",
".",
"_days",
"or",
"self",
".",
"_days",
"[",
"date",
"]",
"is",
"False",
":",
"return",
"False... | Checks whether for this day are information stored.
:param date: Date of the day
:type date: datetime.date
:rtype: bool | [
"Checks",
"whether",
"for",
"this",
"day",
"are",
"information",
"stored",
"."
] | c651da6ace33e2278349636daaa709d043dee6ff | https://github.com/mswart/pyopenmensa/blob/c651da6ace33e2278349636daaa709d043dee6ff/feed.py#L449-L458 | train |
mswart/pyopenmensa | feed.py | BaseBuilder.toXMLFeed | def toXMLFeed(self):
""" Convert this cateen information into string
which is a valid OpenMensa v2 xml feed
:rtype: str"""
feed = self.toXML()
xml_header = '<?xml version="1.0" encoding="UTF-8"?>\n'
return xml_header + feed.toprettyxml(indent=' ') | python | def toXMLFeed(self):
""" Convert this cateen information into string
which is a valid OpenMensa v2 xml feed
:rtype: str"""
feed = self.toXML()
xml_header = '<?xml version="1.0" encoding="UTF-8"?>\n'
return xml_header + feed.toprettyxml(indent=' ') | [
"def",
"toXMLFeed",
"(",
"self",
")",
":",
"feed",
"=",
"self",
".",
"toXML",
"(",
")",
"xml_header",
"=",
"'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n'",
"return",
"xml_header",
"+",
"feed",
".",
"toprettyxml",
"(",
"indent",
"=",
"' '",
")"
] | Convert this cateen information into string
which is a valid OpenMensa v2 xml feed
:rtype: str | [
"Convert",
"this",
"cateen",
"information",
"into",
"string",
"which",
"is",
"a",
"valid",
"OpenMensa",
"v2",
"xml",
"feed"
] | c651da6ace33e2278349636daaa709d043dee6ff | https://github.com/mswart/pyopenmensa/blob/c651da6ace33e2278349636daaa709d043dee6ff/feed.py#L486-L494 | train |
mswart/pyopenmensa | feed.py | BaseBuilder.toTag | def toTag(self, output):
''' This methods adds all data of this canteen as canteen xml tag
to the given xml Document.
:meth:`toXMLFeed` uses this method to create the XML Feed. So there is
normally no need to call it directly.
:param output: XML Document to which the data shoul... | python | def toTag(self, output):
''' This methods adds all data of this canteen as canteen xml tag
to the given xml Document.
:meth:`toXMLFeed` uses this method to create the XML Feed. So there is
normally no need to call it directly.
:param output: XML Document to which the data shoul... | [
"def",
"toTag",
"(",
"self",
",",
"output",
")",
":",
"canteen",
"=",
"output",
".",
"createElement",
"(",
"'canteen'",
")",
"if",
"self",
".",
"_name",
"is",
"not",
"None",
":",
"canteen",
".",
"appendChild",
"(",
"self",
".",
"_buildStringTag",
"(",
... | This methods adds all data of this canteen as canteen xml tag
to the given xml Document.
:meth:`toXMLFeed` uses this method to create the XML Feed. So there is
normally no need to call it directly.
:param output: XML Document to which the data should be added
:type output: xml.... | [
"This",
"methods",
"adds",
"all",
"data",
"of",
"this",
"canteen",
"as",
"canteen",
"xml",
"tag",
"to",
"the",
"given",
"xml",
"Document",
"."
] | c651da6ace33e2278349636daaa709d043dee6ff | https://github.com/mswart/pyopenmensa/blob/c651da6ace33e2278349636daaa709d043dee6ff/feed.py#L512-L555 | train |
shapiromatron/bmds | bmds/reporter.py | Reporter.add_session | def add_session(
self,
session,
input_dataset=True,
summary_table=True,
recommendation_details=True,
recommended_model=True,
all_models=False,
):
"""
Add an existing session to a Word report.
Parameters
----------
sessi... | python | def add_session(
self,
session,
input_dataset=True,
summary_table=True,
recommendation_details=True,
recommended_model=True,
all_models=False,
):
"""
Add an existing session to a Word report.
Parameters
----------
sessi... | [
"def",
"add_session",
"(",
"self",
",",
"session",
",",
"input_dataset",
"=",
"True",
",",
"summary_table",
"=",
"True",
",",
"recommendation_details",
"=",
"True",
",",
"recommended_model",
"=",
"True",
",",
"all_models",
"=",
"False",
",",
")",
":",
"self"... | Add an existing session to a Word report.
Parameters
----------
session : bmds.Session
BMDS session to be included in reporting
input_dataset : bool
Include input dataset data table
summary_table : bool
Include model summary table
reco... | [
"Add",
"an",
"existing",
"session",
"to",
"a",
"Word",
"report",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/reporter.py#L98-L157 | train |
shapiromatron/bmds | bmds/reporter.py | Reporter.save | def save(self, filename):
"""
Save document to a file.
Parameters
----------
filename : str
The output string filename
"""
self.doc.save(os.path.expanduser(filename)) | python | def save(self, filename):
"""
Save document to a file.
Parameters
----------
filename : str
The output string filename
"""
self.doc.save(os.path.expanduser(filename)) | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"doc",
".",
"save",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")"
] | Save document to a file.
Parameters
----------
filename : str
The output string filename | [
"Save",
"document",
"to",
"a",
"file",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/reporter.py#L159-L169 | train |
shapiromatron/bmds | bmds/reporter.py | Reporter._get_session_for_table | def _get_session_for_table(self, base_session):
"""
Only present session for modeling when doses were dropped if it's succesful;
otherwise show the original modeling session.
"""
if base_session.recommended_model is None and base_session.doses_dropped > 0:
return base... | python | def _get_session_for_table(self, base_session):
"""
Only present session for modeling when doses were dropped if it's succesful;
otherwise show the original modeling session.
"""
if base_session.recommended_model is None and base_session.doses_dropped > 0:
return base... | [
"def",
"_get_session_for_table",
"(",
"self",
",",
"base_session",
")",
":",
"if",
"base_session",
".",
"recommended_model",
"is",
"None",
"and",
"base_session",
".",
"doses_dropped",
">",
"0",
":",
"return",
"base_session",
".",
"doses_dropped_sessions",
"[",
"0"... | Only present session for modeling when doses were dropped if it's succesful;
otherwise show the original modeling session. | [
"Only",
"present",
"session",
"for",
"modeling",
"when",
"doses",
"were",
"dropped",
"if",
"it",
"s",
"succesful",
";",
"otherwise",
"show",
"the",
"original",
"modeling",
"session",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/reporter.py#L312-L319 | train |
jmbeach/KEP.py | src/keppy/device.py | Device.set_driver_simulated | def set_driver_simulated(self):
"""Sets the device driver type to simulated"""
self._device_dict["servermain.MULTIPLE_TYPES_DEVICE_DRIVER"] = "Simulator"
if self._is_sixteen_bit:
self._device_dict["servermain.DEVICE_MODEL"] = 0
else:
self._device_dict["servermain.... | python | def set_driver_simulated(self):
"""Sets the device driver type to simulated"""
self._device_dict["servermain.MULTIPLE_TYPES_DEVICE_DRIVER"] = "Simulator"
if self._is_sixteen_bit:
self._device_dict["servermain.DEVICE_MODEL"] = 0
else:
self._device_dict["servermain.... | [
"def",
"set_driver_simulated",
"(",
"self",
")",
":",
"self",
".",
"_device_dict",
"[",
"\"servermain.MULTIPLE_TYPES_DEVICE_DRIVER\"",
"]",
"=",
"\"Simulator\"",
"if",
"self",
".",
"_is_sixteen_bit",
":",
"self",
".",
"_device_dict",
"[",
"\"servermain.DEVICE_MODEL\"",
... | Sets the device driver type to simulated | [
"Sets",
"the",
"device",
"driver",
"type",
"to",
"simulated"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/device.py#L15-L22 | train |
jmbeach/KEP.py | src/keppy/device.py | Device.parse_tag_groups | def parse_tag_groups(self):
"""Gets an array of TagGroup objects in the Kepware device"""
tag_groups = []
if 'tag_groups' not in self._device_dict:
return tag_groups
to_remove = []
for tag_group in self._device_dict['tag_groups']:
if tag_group['common.ALLT... | python | def parse_tag_groups(self):
"""Gets an array of TagGroup objects in the Kepware device"""
tag_groups = []
if 'tag_groups' not in self._device_dict:
return tag_groups
to_remove = []
for tag_group in self._device_dict['tag_groups']:
if tag_group['common.ALLT... | [
"def",
"parse_tag_groups",
"(",
"self",
")",
":",
"tag_groups",
"=",
"[",
"]",
"if",
"'tag_groups'",
"not",
"in",
"self",
".",
"_device_dict",
":",
"return",
"tag_groups",
"to_remove",
"=",
"[",
"]",
"for",
"tag_group",
"in",
"self",
".",
"_device_dict",
"... | Gets an array of TagGroup objects in the Kepware device | [
"Gets",
"an",
"array",
"of",
"TagGroup",
"objects",
"in",
"the",
"Kepware",
"device"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/device.py#L24-L38 | train |
jmbeach/KEP.py | src/keppy/device.py | Device.update | def update(self):
"""Updates the dictionary of the device"""
if "tag_groups" not in self._device_dict:
return
for group in self.tag_groups:
group.update()
for i in range(len(self._device_dict["tag_groups"])):
tag_group_dict = self._device_dict["tag_gro... | python | def update(self):
"""Updates the dictionary of the device"""
if "tag_groups" not in self._device_dict:
return
for group in self.tag_groups:
group.update()
for i in range(len(self._device_dict["tag_groups"])):
tag_group_dict = self._device_dict["tag_gro... | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"\"tag_groups\"",
"not",
"in",
"self",
".",
"_device_dict",
":",
"return",
"for",
"group",
"in",
"self",
".",
"tag_groups",
":",
"group",
".",
"update",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(... | Updates the dictionary of the device | [
"Updates",
"the",
"dictionary",
"of",
"the",
"device"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/device.py#L71-L81 | train |
drericstrong/pyedna | pyedna/serv.py | AddAnalogShortIdMsecRecord | def AddAnalogShortIdMsecRecord(site_service, tag, time_value, msec, value,
low_warn=False, high_warn=False, low_alarm=False, high_alarm=False,
oor_low=False, oor_high=False, unreliable=False, manual=False):
"""
This function will add an analog value to the specified eDNA service and
tag, with many o... | python | def AddAnalogShortIdMsecRecord(site_service, tag, time_value, msec, value,
low_warn=False, high_warn=False, low_alarm=False, high_alarm=False,
oor_low=False, oor_high=False, unreliable=False, manual=False):
"""
This function will add an analog value to the specified eDNA service and
tag, with many o... | [
"def",
"AddAnalogShortIdMsecRecord",
"(",
"site_service",
",",
"tag",
",",
"time_value",
",",
"msec",
",",
"value",
",",
"low_warn",
"=",
"False",
",",
"high_warn",
"=",
"False",
",",
"low_alarm",
"=",
"False",
",",
"high_alarm",
"=",
"False",
",",
"oor_low"... | This function will add an analog value to the specified eDNA service and
tag, with many optional status definitions.
:param site_service: The site.service where data will be pushed
:param tag: The eDNA tag to push data. Tag only (e.g. ADE1CA01)
:param time_value: The time of the point, which MUST be in... | [
"This",
"function",
"will",
"add",
"an",
"analog",
"value",
"to",
"the",
"specified",
"eDNA",
"service",
"and",
"tag",
"with",
"many",
"optional",
"status",
"definitions",
"."
] | b8f8f52def4f26bb4f3a993ce3400769518385f6 | https://github.com/drericstrong/pyedna/blob/b8f8f52def4f26bb4f3a993ce3400769518385f6/pyedna/serv.py#L171-L214 | train |
drericstrong/pyedna | pyedna/serv.py | FlushShortIdRecords | def FlushShortIdRecords(site_service):
"""
Flush all the queued records.
:param site_service: The site.service where data was pushed
:return: message whether function was successful
"""
# Define all required variables in the correct ctypes format
szService = c_char_p(site_service.encode('ut... | python | def FlushShortIdRecords(site_service):
"""
Flush all the queued records.
:param site_service: The site.service where data was pushed
:return: message whether function was successful
"""
# Define all required variables in the correct ctypes format
szService = c_char_p(site_service.encode('ut... | [
"def",
"FlushShortIdRecords",
"(",
"site_service",
")",
":",
"szService",
"=",
"c_char_p",
"(",
"site_service",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"szMessage",
"=",
"create_string_buffer",
"(",
"b\" \"",
")",
"nMessage",
"=",
"c_ushort",
"... | Flush all the queued records.
:param site_service: The site.service where data was pushed
:return: message whether function was successful | [
"Flush",
"all",
"the",
"queued",
"records",
"."
] | b8f8f52def4f26bb4f3a993ce3400769518385f6 | https://github.com/drericstrong/pyedna/blob/b8f8f52def4f26bb4f3a993ce3400769518385f6/pyedna/serv.py#L283-L298 | train |
tethysplatform/condorpy | condorpy/htcondor_object_base.py | HTCondorObjectBase.set_scheduler | def set_scheduler(self, host, username='root', password=None, private_key=None, private_key_pass=None):
"""
Defines the remote scheduler
Args:
host (str): the hostname or ip address of the remote scheduler
username (str, optional): the username used to connect to the rem... | python | def set_scheduler(self, host, username='root', password=None, private_key=None, private_key_pass=None):
"""
Defines the remote scheduler
Args:
host (str): the hostname or ip address of the remote scheduler
username (str, optional): the username used to connect to the rem... | [
"def",
"set_scheduler",
"(",
"self",
",",
"host",
",",
"username",
"=",
"'root'",
",",
"password",
"=",
"None",
",",
"private_key",
"=",
"None",
",",
"private_key_pass",
"=",
"None",
")",
":",
"self",
".",
"_remote",
"=",
"RemoteClient",
"(",
"host",
","... | Defines the remote scheduler
Args:
host (str): the hostname or ip address of the remote scheduler
username (str, optional): the username used to connect to the remote scheduler. Default is 'root'
password (str, optional): the password for username on the remote scheduler. Ei... | [
"Defines",
"the",
"remote",
"scheduler"
] | a5aaaef0d73198f7d9756dda7abe98b4e209f1f4 | https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/htcondor_object_base.py#L68-L83 | train |
tethysplatform/condorpy | condorpy/htcondor_object_base.py | HTCondorObjectBase.set_cwd | def set_cwd(fn):
"""
Decorator to set the specified working directory to execute the function, and then restore the previous cwd.
"""
def wrapped(self, *args, **kwargs):
log.info('Calling function: %s with args=%s', fn, args if args else [])
cwd = os.getcwd()
... | python | def set_cwd(fn):
"""
Decorator to set the specified working directory to execute the function, and then restore the previous cwd.
"""
def wrapped(self, *args, **kwargs):
log.info('Calling function: %s with args=%s', fn, args if args else [])
cwd = os.getcwd()
... | [
"def",
"set_cwd",
"(",
"fn",
")",
":",
"def",
"wrapped",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"log",
".",
"info",
"(",
"'Calling function: %s with args=%s'",
",",
"fn",
",",
"args",
"if",
"args",
"else",
"[",
"]",
")",
"cwd",... | Decorator to set the specified working directory to execute the function, and then restore the previous cwd. | [
"Decorator",
"to",
"set",
"the",
"specified",
"working",
"directory",
"to",
"execute",
"the",
"function",
"and",
"then",
"restore",
"the",
"previous",
"cwd",
"."
] | a5aaaef0d73198f7d9756dda7abe98b4e209f1f4 | https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/htcondor_object_base.py#L108-L124 | train |
tethysplatform/condorpy | condorpy/htcondor_object_base.py | HTCondorObjectBase.remove | def remove(self, options=[], sub_job_num=None):
"""Removes a job from the job queue, or from being executed.
Args:
options (list of str, optional): A list of command line options for the condor_rm command. For
details on valid options see: http://research.cs.wisc.edu/htcondo... | python | def remove(self, options=[], sub_job_num=None):
"""Removes a job from the job queue, or from being executed.
Args:
options (list of str, optional): A list of command line options for the condor_rm command. For
details on valid options see: http://research.cs.wisc.edu/htcondo... | [
"def",
"remove",
"(",
"self",
",",
"options",
"=",
"[",
"]",
",",
"sub_job_num",
"=",
"None",
")",
":",
"args",
"=",
"[",
"'condor_rm'",
"]",
"args",
".",
"extend",
"(",
"options",
")",
"job_id",
"=",
"'%s.%s'",
"%",
"(",
"self",
".",
"cluster_id",
... | Removes a job from the job queue, or from being executed.
Args:
options (list of str, optional): A list of command line options for the condor_rm command. For
details on valid options see: http://research.cs.wisc.edu/htcondor/manual/current/condor_rm.html.
Defaults t... | [
"Removes",
"a",
"job",
"from",
"the",
"job",
"queue",
"or",
"from",
"being",
"executed",
"."
] | a5aaaef0d73198f7d9756dda7abe98b4e209f1f4 | https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/htcondor_object_base.py#L144-L159 | train |
tethysplatform/condorpy | condorpy/htcondor_object_base.py | HTCondorObjectBase.close_remote | def close_remote(self):
"""Cleans up and closes connection to remote server if defined.
"""
if self._remote:
try:
# first see if remote dir is still there
self._remote.execute('ls %s' % (self._remote_id,))
if self.status != 'Completed'... | python | def close_remote(self):
"""Cleans up and closes connection to remote server if defined.
"""
if self._remote:
try:
# first see if remote dir is still there
self._remote.execute('ls %s' % (self._remote_id,))
if self.status != 'Completed'... | [
"def",
"close_remote",
"(",
"self",
")",
":",
"if",
"self",
".",
"_remote",
":",
"try",
":",
"self",
".",
"_remote",
".",
"execute",
"(",
"'ls %s'",
"%",
"(",
"self",
".",
"_remote_id",
",",
")",
")",
"if",
"self",
".",
"status",
"!=",
"'Completed'",... | Cleans up and closes connection to remote server if defined. | [
"Cleans",
"up",
"and",
"closes",
"connection",
"to",
"remote",
"server",
"if",
"defined",
"."
] | a5aaaef0d73198f7d9756dda7abe98b4e209f1f4 | https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/htcondor_object_base.py#L167-L181 | train |
VIVelev/PyDojoML | dojo/tree/utils/impurity_measurements.py | gini_impurity | def gini_impurity(s):
"""Calculate the Gini Impurity for a list of samples.
See:
https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity
"""
return 1 - sum(prop(s[i], s)**2 for i in range(len(s))) | python | def gini_impurity(s):
"""Calculate the Gini Impurity for a list of samples.
See:
https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity
"""
return 1 - sum(prop(s[i], s)**2 for i in range(len(s))) | [
"def",
"gini_impurity",
"(",
"s",
")",
":",
"return",
"1",
"-",
"sum",
"(",
"prop",
"(",
"s",
"[",
"i",
"]",
",",
"s",
")",
"**",
"2",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"s",
")",
")",
")"
] | Calculate the Gini Impurity for a list of samples.
See:
https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity | [
"Calculate",
"the",
"Gini",
"Impurity",
"for",
"a",
"list",
"of",
"samples",
"."
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/impurity_measurements.py#L18-L24 | train |
VIVelev/PyDojoML | dojo/tree/utils/impurity_measurements.py | entropy | def entropy(s):
"""Calculate the Entropy Impurity for a list of samples.
"""
return -sum(
p*np.log(p) for i in range(len(s)) for p in [prop(s[i], s)]
) | python | def entropy(s):
"""Calculate the Entropy Impurity for a list of samples.
"""
return -sum(
p*np.log(p) for i in range(len(s)) for p in [prop(s[i], s)]
) | [
"def",
"entropy",
"(",
"s",
")",
":",
"return",
"-",
"sum",
"(",
"p",
"*",
"np",
".",
"log",
"(",
"p",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"s",
")",
")",
"for",
"p",
"in",
"[",
"prop",
"(",
"s",
"[",
"i",
"]",
",",
"s",
")"... | Calculate the Entropy Impurity for a list of samples. | [
"Calculate",
"the",
"Entropy",
"Impurity",
"for",
"a",
"list",
"of",
"samples",
"."
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/impurity_measurements.py#L28-L33 | train |
VIVelev/PyDojoML | dojo/tree/utils/impurity_measurements.py | info_gain | def info_gain(current_impurity, true_branch, false_branch, criterion):
"""Information Gain.
The uncertainty of the starting node, minus the weighted impurity of
two child nodes.
"""
measure_impurity = gini_impurity if criterion == "gini" else entropy
p = float(len(true_branch)) / (len(true... | python | def info_gain(current_impurity, true_branch, false_branch, criterion):
"""Information Gain.
The uncertainty of the starting node, minus the weighted impurity of
two child nodes.
"""
measure_impurity = gini_impurity if criterion == "gini" else entropy
p = float(len(true_branch)) / (len(true... | [
"def",
"info_gain",
"(",
"current_impurity",
",",
"true_branch",
",",
"false_branch",
",",
"criterion",
")",
":",
"measure_impurity",
"=",
"gini_impurity",
"if",
"criterion",
"==",
"\"gini\"",
"else",
"entropy",
"p",
"=",
"float",
"(",
"len",
"(",
"true_branch",... | Information Gain.
The uncertainty of the starting node, minus the weighted impurity of
two child nodes. | [
"Information",
"Gain",
".",
"The",
"uncertainty",
"of",
"the",
"starting",
"node",
"minus",
"the",
"weighted",
"impurity",
"of",
"two",
"child",
"nodes",
"."
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/impurity_measurements.py#L37-L47 | train |
tethysplatform/condorpy | condorpy/workflow.py | Workflow._update_statuses | def _update_statuses(self, sub_job_num=None):
"""
Update statuses of jobs nodes in workflow.
"""
# initialize status dictionary
status_dict = dict()
for val in CONDOR_JOB_STATUSES.values():
status_dict[val] = 0
for node in self.node_set:
... | python | def _update_statuses(self, sub_job_num=None):
"""
Update statuses of jobs nodes in workflow.
"""
# initialize status dictionary
status_dict = dict()
for val in CONDOR_JOB_STATUSES.values():
status_dict[val] = 0
for node in self.node_set:
... | [
"def",
"_update_statuses",
"(",
"self",
",",
"sub_job_num",
"=",
"None",
")",
":",
"status_dict",
"=",
"dict",
"(",
")",
"for",
"val",
"in",
"CONDOR_JOB_STATUSES",
".",
"values",
"(",
")",
":",
"status_dict",
"[",
"val",
"]",
"=",
"0",
"for",
"node",
"... | Update statuses of jobs nodes in workflow. | [
"Update",
"statuses",
"of",
"jobs",
"nodes",
"in",
"workflow",
"."
] | a5aaaef0d73198f7d9756dda7abe98b4e209f1f4 | https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/workflow.py#L180-L198 | train |
tethysplatform/condorpy | condorpy/workflow.py | Workflow.update_node_ids | def update_node_ids(self, sub_job_num=None):
"""
Associate Jobs with respective cluster ids.
"""
# Build condor_q and condor_history commands
dag_id = '%s.%s' % (self.cluster_id, sub_job_num) if sub_job_num else str(self.cluster_id)
job_delimiter = '+++'
attr_deli... | python | def update_node_ids(self, sub_job_num=None):
"""
Associate Jobs with respective cluster ids.
"""
# Build condor_q and condor_history commands
dag_id = '%s.%s' % (self.cluster_id, sub_job_num) if sub_job_num else str(self.cluster_id)
job_delimiter = '+++'
attr_deli... | [
"def",
"update_node_ids",
"(",
"self",
",",
"sub_job_num",
"=",
"None",
")",
":",
"dag_id",
"=",
"'%s.%s'",
"%",
"(",
"self",
".",
"cluster_id",
",",
"sub_job_num",
")",
"if",
"sub_job_num",
"else",
"str",
"(",
"self",
".",
"cluster_id",
")",
"job_delimite... | Associate Jobs with respective cluster ids. | [
"Associate",
"Jobs",
"with",
"respective",
"cluster",
"ids",
"."
] | a5aaaef0d73198f7d9756dda7abe98b4e209f1f4 | https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/workflow.py#L200-L269 | train |
tethysplatform/condorpy | condorpy/workflow.py | Workflow.submit | def submit(self, options=[]):
"""
ensures that all relatives of nodes in node_set are also added to the set before submitting
"""
self.complete_node_set()
self._write_job_file()
args = ['condor_submit_dag']
args.extend(options)
args.append(self.dag_file)
... | python | def submit(self, options=[]):
"""
ensures that all relatives of nodes in node_set are also added to the set before submitting
"""
self.complete_node_set()
self._write_job_file()
args = ['condor_submit_dag']
args.extend(options)
args.append(self.dag_file)
... | [
"def",
"submit",
"(",
"self",
",",
"options",
"=",
"[",
"]",
")",
":",
"self",
".",
"complete_node_set",
"(",
")",
"self",
".",
"_write_job_file",
"(",
")",
"args",
"=",
"[",
"'condor_submit_dag'",
"]",
"args",
".",
"extend",
"(",
"options",
")",
"args... | ensures that all relatives of nodes in node_set are also added to the set before submitting | [
"ensures",
"that",
"all",
"relatives",
"of",
"nodes",
"in",
"node_set",
"are",
"also",
"added",
"to",
"the",
"set",
"before",
"submitting"
] | a5aaaef0d73198f7d9756dda7abe98b4e209f1f4 | https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/workflow.py#L287-L299 | train |
tjcsl/cslbot | cslbot/helpers/modutils.py | safe_reload | def safe_reload(modname: types.ModuleType) -> Union[None, str]:
"""Catch and log any errors that arise from reimporting a module, but do not die.
:return: None when import was successful. String is the first line of the error message
"""
try:
importlib.reload(modname)
return None
e... | python | def safe_reload(modname: types.ModuleType) -> Union[None, str]:
"""Catch and log any errors that arise from reimporting a module, but do not die.
:return: None when import was successful. String is the first line of the error message
"""
try:
importlib.reload(modname)
return None
e... | [
"def",
"safe_reload",
"(",
"modname",
":",
"types",
".",
"ModuleType",
")",
"->",
"Union",
"[",
"None",
",",
"str",
"]",
":",
"try",
":",
"importlib",
".",
"reload",
"(",
"modname",
")",
"return",
"None",
"except",
"Exception",
"as",
"e",
":",
"logging... | Catch and log any errors that arise from reimporting a module, but do not die.
:return: None when import was successful. String is the first line of the error message | [
"Catch",
"and",
"log",
"any",
"errors",
"that",
"arise",
"from",
"reimporting",
"a",
"module",
"but",
"do",
"not",
"die",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/modutils.py#L139-L151 | train |
tjcsl/cslbot | cslbot/helpers/modutils.py | safe_load | def safe_load(modname: str) -> Union[None, str]:
"""Load a module, logging errors instead of dying if it fails to load.
:return: None when import was successful. String is the first line of the error message
"""
try:
importlib.import_module(modname)
return None
except Exception as ... | python | def safe_load(modname: str) -> Union[None, str]:
"""Load a module, logging errors instead of dying if it fails to load.
:return: None when import was successful. String is the first line of the error message
"""
try:
importlib.import_module(modname)
return None
except Exception as ... | [
"def",
"safe_load",
"(",
"modname",
":",
"str",
")",
"->",
"Union",
"[",
"None",
",",
"str",
"]",
":",
"try",
":",
"importlib",
".",
"import_module",
"(",
"modname",
")",
"return",
"None",
"except",
"Exception",
"as",
"ex",
":",
"logging",
".",
"error"... | Load a module, logging errors instead of dying if it fails to load.
:return: None when import was successful. String is the first line of the error message | [
"Load",
"a",
"module",
"logging",
"errors",
"instead",
"of",
"dying",
"if",
"it",
"fails",
"to",
"load",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/modutils.py#L154-L166 | train |
tjcsl/cslbot | cslbot/helpers/modutils.py | scan_and_reimport | def scan_and_reimport(mod_type: str) -> List[Tuple[str, str]]:
"""Scans folder for modules."""
mod_enabled, mod_disabled = get_modules(mod_type)
errors = []
for mod in mod_enabled + mod_disabled:
if mod in sys.modules:
msg = safe_reload(sys.modules[mod])
else:
msg... | python | def scan_and_reimport(mod_type: str) -> List[Tuple[str, str]]:
"""Scans folder for modules."""
mod_enabled, mod_disabled = get_modules(mod_type)
errors = []
for mod in mod_enabled + mod_disabled:
if mod in sys.modules:
msg = safe_reload(sys.modules[mod])
else:
msg... | [
"def",
"scan_and_reimport",
"(",
"mod_type",
":",
"str",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"mod_enabled",
",",
"mod_disabled",
"=",
"get_modules",
"(",
"mod_type",
")",
"errors",
"=",
"[",
"]",
"for",
"mod",
"in",
... | Scans folder for modules. | [
"Scans",
"folder",
"for",
"modules",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/modutils.py#L169-L180 | train |
Yipit/pyeqs | pyeqs/dsl/aggregations.py | Aggregations._ranging | def _ranging(self):
"""
Should be a list of values to designate the buckets
"""
agg_ranges = []
for i, val in enumerate(self.range_list):
if i == 0:
agg_ranges.append({"to": val})
else:
previous = self.range_list[i - 1]
... | python | def _ranging(self):
"""
Should be a list of values to designate the buckets
"""
agg_ranges = []
for i, val in enumerate(self.range_list):
if i == 0:
agg_ranges.append({"to": val})
else:
previous = self.range_list[i - 1]
... | [
"def",
"_ranging",
"(",
"self",
")",
":",
"agg_ranges",
"=",
"[",
"]",
"for",
"i",
",",
"val",
"in",
"enumerate",
"(",
"self",
".",
"range_list",
")",
":",
"if",
"i",
"==",
"0",
":",
"agg_ranges",
".",
"append",
"(",
"{",
"\"to\"",
":",
"val",
"}... | Should be a list of values to designate the buckets | [
"Should",
"be",
"a",
"list",
"of",
"values",
"to",
"designate",
"the",
"buckets"
] | 2e385c0a5d113af0e20be4d9393add2aabdd9565 | https://github.com/Yipit/pyeqs/blob/2e385c0a5d113af0e20be4d9393add2aabdd9565/pyeqs/dsl/aggregations.py#L81-L95 | train |
Keda87/python-quran-odoa | odoa.py | ODOA.get_random_surah | def get_random_surah(self, lang='id'):
"""
Perform http request to get random surah.
Parameter:
:lang -- String contains language code.
Return:
:dict -- Paired ayat, sound, description and the translation.
"""
# Ensure the language ... | python | def get_random_surah(self, lang='id'):
"""
Perform http request to get random surah.
Parameter:
:lang -- String contains language code.
Return:
:dict -- Paired ayat, sound, description and the translation.
"""
# Ensure the language ... | [
"def",
"get_random_surah",
"(",
"self",
",",
"lang",
"=",
"'id'",
")",
":",
"if",
"lang",
"not",
"in",
"self",
".",
"SUPPORTED_LANGUAGES",
":",
"message",
"=",
"'Currently your selected language not yet supported.'",
"raise",
"ODOAException",
"(",
"message",
")",
... | Perform http request to get random surah.
Parameter:
:lang -- String contains language code.
Return:
:dict -- Paired ayat, sound, description and the translation. | [
"Perform",
"http",
"request",
"to",
"get",
"random",
"surah",
"."
] | 1bf58feeef0355f5ca6c9ad678e54a8195f33eb8 | https://github.com/Keda87/python-quran-odoa/blob/1bf58feeef0355f5ca6c9ad678e54a8195f33eb8/odoa.py#L54-L92 | train |
Keda87/python-quran-odoa | odoa.py | ODOA.__get_translation | def __get_translation(self, surah, ayah, lang):
"""
Perform http request to get translation from given surah, ayah and
language.
Parameter:
:surah -- Surah index from API pages.
:ayat -- Ayat key.
:lang -- Language code.
R... | python | def __get_translation(self, surah, ayah, lang):
"""
Perform http request to get translation from given surah, ayah and
language.
Parameter:
:surah -- Surah index from API pages.
:ayat -- Ayat key.
:lang -- Language code.
R... | [
"def",
"__get_translation",
"(",
"self",
",",
"surah",
",",
"ayah",
",",
"lang",
")",
":",
"url",
"=",
"'{base}/translations/{lang}/{lang}_translation_{surah}.json'",
".",
"format",
"(",
"base",
"=",
"self",
".",
"BASE_API",
",",
"lang",
"=",
"lang",
",",
"sur... | Perform http request to get translation from given surah, ayah and
language.
Parameter:
:surah -- Surah index from API pages.
:ayat -- Ayat key.
:lang -- Language code.
Return:
:string -- Translation from given surah and ... | [
"Perform",
"http",
"request",
"to",
"get",
"translation",
"from",
"given",
"surah",
"ayah",
"and",
"language",
"."
] | 1bf58feeef0355f5ca6c9ad678e54a8195f33eb8 | https://github.com/Keda87/python-quran-odoa/blob/1bf58feeef0355f5ca6c9ad678e54a8195f33eb8/odoa.py#L94-L118 | train |
Keda87/python-quran-odoa | odoa.py | ODOA.__get_sound | def __get_sound(self, surah, ayah):
"""
Perform http request to get sound from given surah and ayah.
Parameter:
:surah -- Surah index from API pages.
:ayat -- Ayat key.
Return:
:string -- URL for mp3 sound.
"""
# For... | python | def __get_sound(self, surah, ayah):
"""
Perform http request to get sound from given surah and ayah.
Parameter:
:surah -- Surah index from API pages.
:ayat -- Ayat key.
Return:
:string -- URL for mp3 sound.
"""
# For... | [
"def",
"__get_sound",
"(",
"self",
",",
"surah",
",",
"ayah",
")",
":",
"format_ayah",
"=",
"'{0:0>3}'",
".",
"format",
"(",
"ayah",
")",
"sound_url",
"=",
"'{base}/sounds/{surah}/{ayah}.mp3'",
".",
"format",
"(",
"base",
"=",
"self",
".",
"BASE_API",
",",
... | Perform http request to get sound from given surah and ayah.
Parameter:
:surah -- Surah index from API pages.
:ayat -- Ayat key.
Return:
:string -- URL for mp3 sound. | [
"Perform",
"http",
"request",
"to",
"get",
"sound",
"from",
"given",
"surah",
"and",
"ayah",
"."
] | 1bf58feeef0355f5ca6c9ad678e54a8195f33eb8 | https://github.com/Keda87/python-quran-odoa/blob/1bf58feeef0355f5ca6c9ad678e54a8195f33eb8/odoa.py#L120-L137 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/votes.py | VotesSerializer.get_fipscode | def get_fipscode(self, obj):
"""County FIPS code"""
if obj.division.level.name == DivisionLevel.COUNTY:
return obj.division.code
return None | python | def get_fipscode(self, obj):
"""County FIPS code"""
if obj.division.level.name == DivisionLevel.COUNTY:
return obj.division.code
return None | [
"def",
"get_fipscode",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"COUNTY",
":",
"return",
"obj",
".",
"division",
".",
"code",
"return",
"None"
] | County FIPS code | [
"County",
"FIPS",
"code"
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/votes.py#L63-L67 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/votes.py | VotesSerializer.get_statepostal | def get_statepostal(self, obj):
"""State postal abbreviation if county or state else ``None``."""
if obj.division.level.name == DivisionLevel.STATE:
return us.states.lookup(obj.division.code).abbr
elif obj.division.level.name == DivisionLevel.COUNTY:
return us.states.look... | python | def get_statepostal(self, obj):
"""State postal abbreviation if county or state else ``None``."""
if obj.division.level.name == DivisionLevel.STATE:
return us.states.lookup(obj.division.code).abbr
elif obj.division.level.name == DivisionLevel.COUNTY:
return us.states.look... | [
"def",
"get_statepostal",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"STATE",
":",
"return",
"us",
".",
"states",
".",
"lookup",
"(",
"obj",
".",
"division",
".",
"code",
")... | State postal abbreviation if county or state else ``None``. | [
"State",
"postal",
"abbreviation",
"if",
"county",
"or",
"state",
"else",
"None",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/votes.py#L69-L75 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/votes.py | VotesSerializer.get_polid | def get_polid(self, obj):
"""AP polid minus 'polid' prefix if polid else ``None``."""
ap_id = obj.candidate_election.candidate.ap_candidate_id
if 'polid-' in ap_id:
return ap_id.replace('polid-', '')
return None | python | def get_polid(self, obj):
"""AP polid minus 'polid' prefix if polid else ``None``."""
ap_id = obj.candidate_election.candidate.ap_candidate_id
if 'polid-' in ap_id:
return ap_id.replace('polid-', '')
return None | [
"def",
"get_polid",
"(",
"self",
",",
"obj",
")",
":",
"ap_id",
"=",
"obj",
".",
"candidate_election",
".",
"candidate",
".",
"ap_candidate_id",
"if",
"'polid-'",
"in",
"ap_id",
":",
"return",
"ap_id",
".",
"replace",
"(",
"'polid-'",
",",
"''",
")",
"re... | AP polid minus 'polid' prefix if polid else ``None``. | [
"AP",
"polid",
"minus",
"polid",
"prefix",
"if",
"polid",
"else",
"None",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/votes.py#L77-L82 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/votes.py | VotesSerializer.get_polnum | def get_polnum(self, obj):
"""AP polnum minus 'polnum' prefix if polnum else ``None``."""
ap_id = obj.candidate_election.candidate.ap_candidate_id
if 'polnum-' in ap_id:
return ap_id.replace('polnum-', '')
return None | python | def get_polnum(self, obj):
"""AP polnum minus 'polnum' prefix if polnum else ``None``."""
ap_id = obj.candidate_election.candidate.ap_candidate_id
if 'polnum-' in ap_id:
return ap_id.replace('polnum-', '')
return None | [
"def",
"get_polnum",
"(",
"self",
",",
"obj",
")",
":",
"ap_id",
"=",
"obj",
".",
"candidate_election",
".",
"candidate",
".",
"ap_candidate_id",
"if",
"'polnum-'",
"in",
"ap_id",
":",
"return",
"ap_id",
".",
"replace",
"(",
"'polnum-'",
",",
"''",
")",
... | AP polnum minus 'polnum' prefix if polnum else ``None``. | [
"AP",
"polnum",
"minus",
"polnum",
"prefix",
"if",
"polnum",
"else",
"None",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/votes.py#L84-L89 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/votes.py | VotesSerializer.get_precinctsreporting | def get_precinctsreporting(self, obj):
"""Precincts reporting if vote is top level result else ``None``."""
if obj.division.level == \
obj.candidate_election.election.division.level:
return obj.candidate_election.election.meta.precincts_reporting
return None | python | def get_precinctsreporting(self, obj):
"""Precincts reporting if vote is top level result else ``None``."""
if obj.division.level == \
obj.candidate_election.election.division.level:
return obj.candidate_election.election.meta.precincts_reporting
return None | [
"def",
"get_precinctsreporting",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"division",
".",
"level",
"==",
"obj",
".",
"candidate_election",
".",
"election",
".",
"division",
".",
"level",
":",
"return",
"obj",
".",
"candidate_election",
".",
"e... | Precincts reporting if vote is top level result else ``None``. | [
"Precincts",
"reporting",
"if",
"vote",
"is",
"top",
"level",
"result",
"else",
"None",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/votes.py#L91-L96 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/votes.py | VotesSerializer.get_precinctsreportingpct | def get_precinctsreportingpct(self, obj):
"""
Precincts reporting percent if vote is top level result else ``None``.
"""
if obj.division.level == \
obj.candidate_election.election.division.level:
return obj.candidate_election.election.meta.precincts_reporting_... | python | def get_precinctsreportingpct(self, obj):
"""
Precincts reporting percent if vote is top level result else ``None``.
"""
if obj.division.level == \
obj.candidate_election.election.division.level:
return obj.candidate_election.election.meta.precincts_reporting_... | [
"def",
"get_precinctsreportingpct",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"division",
".",
"level",
"==",
"obj",
".",
"candidate_election",
".",
"election",
".",
"division",
".",
"level",
":",
"return",
"obj",
".",
"candidate_election",
".",
... | Precincts reporting percent if vote is top level result else ``None``. | [
"Precincts",
"reporting",
"percent",
"if",
"vote",
"is",
"top",
"level",
"result",
"else",
"None",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/votes.py#L98-L105 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/votes.py | VotesSerializer.get_precinctstotal | def get_precinctstotal(self, obj):
"""Precincts total if vote is top level result else ``None``."""
if obj.division.level == \
obj.candidate_election.election.division.level:
return obj.candidate_election.election.meta.precincts_total
return None | python | def get_precinctstotal(self, obj):
"""Precincts total if vote is top level result else ``None``."""
if obj.division.level == \
obj.candidate_election.election.division.level:
return obj.candidate_election.election.meta.precincts_total
return None | [
"def",
"get_precinctstotal",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"division",
".",
"level",
"==",
"obj",
".",
"candidate_election",
".",
"election",
".",
"division",
".",
"level",
":",
"return",
"obj",
".",
"candidate_election",
".",
"elect... | Precincts total if vote is top level result else ``None``. | [
"Precincts",
"total",
"if",
"vote",
"is",
"top",
"level",
"result",
"else",
"None",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/votes.py#L107-L112 | train |
CI-WATER/mapkit | mapkit/RasterLoader.py | RasterLoader.load | def load(self, tableName='rasters', rasters=[]):
'''
Accepts a list of paths to raster files to load into the database.
Returns the ids of the rasters loaded successfully in the same order
as the list passed in.
'''
# Create table if necessary
Base.metadata.create... | python | def load(self, tableName='rasters', rasters=[]):
'''
Accepts a list of paths to raster files to load into the database.
Returns the ids of the rasters loaded successfully in the same order
as the list passed in.
'''
# Create table if necessary
Base.metadata.create... | [
"def",
"load",
"(",
"self",
",",
"tableName",
"=",
"'rasters'",
",",
"rasters",
"=",
"[",
"]",
")",
":",
"Base",
".",
"metadata",
".",
"create_all",
"(",
"self",
".",
"_engine",
")",
"Session",
"=",
"sessionmaker",
"(",
"bind",
"=",
"self",
".",
"_en... | Accepts a list of paths to raster files to load into the database.
Returns the ids of the rasters loaded successfully in the same order
as the list passed in. | [
"Accepts",
"a",
"list",
"of",
"paths",
"to",
"raster",
"files",
"to",
"load",
"into",
"the",
"database",
".",
"Returns",
"the",
"ids",
"of",
"the",
"rasters",
"loaded",
"successfully",
"in",
"the",
"same",
"order",
"as",
"the",
"list",
"passed",
"in",
".... | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterLoader.py#L35-L80 | train |
CI-WATER/mapkit | mapkit/RasterLoader.py | RasterLoader.rasterToWKB | def rasterToWKB(cls, rasterPath, srid, noData, raster2pgsql):
"""
Accepts a raster file and converts it to Well Known Binary text using the raster2pgsql
executable that comes with PostGIS. This is the format that rasters are stored in a
PostGIS database.
"""
raster2pgsqlP... | python | def rasterToWKB(cls, rasterPath, srid, noData, raster2pgsql):
"""
Accepts a raster file and converts it to Well Known Binary text using the raster2pgsql
executable that comes with PostGIS. This is the format that rasters are stored in a
PostGIS database.
"""
raster2pgsqlP... | [
"def",
"rasterToWKB",
"(",
"cls",
",",
"rasterPath",
",",
"srid",
",",
"noData",
",",
"raster2pgsql",
")",
":",
"raster2pgsqlProcess",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"raster2pgsql",
",",
"'-s'",
",",
"srid",
",",
"'-N'",
",",
"noData",
",",
"... | Accepts a raster file and converts it to Well Known Binary text using the raster2pgsql
executable that comes with PostGIS. This is the format that rasters are stored in a
PostGIS database. | [
"Accepts",
"a",
"raster",
"file",
"and",
"converts",
"it",
"to",
"Well",
"Known",
"Binary",
"text",
"using",
"the",
"raster2pgsql",
"executable",
"that",
"comes",
"with",
"PostGIS",
".",
"This",
"is",
"the",
"format",
"that",
"rasters",
"are",
"stored",
"in"... | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterLoader.py#L83-L111 | train |
CI-WATER/mapkit | mapkit/RasterLoader.py | RasterLoader.grassAsciiRasterToWKB | def grassAsciiRasterToWKB(cls, session, grassRasterPath, srid, noData=0):
"""
Load GRASS ASCII rasters directly using the makeSingleBandWKBRaster method. Do this to eliminate the raster2pgsql
dependency.
"""
# Constants
NUM_HEADER_LINES = 6
# Defaults
nor... | python | def grassAsciiRasterToWKB(cls, session, grassRasterPath, srid, noData=0):
"""
Load GRASS ASCII rasters directly using the makeSingleBandWKBRaster method. Do this to eliminate the raster2pgsql
dependency.
"""
# Constants
NUM_HEADER_LINES = 6
# Defaults
nor... | [
"def",
"grassAsciiRasterToWKB",
"(",
"cls",
",",
"session",
",",
"grassRasterPath",
",",
"srid",
",",
"noData",
"=",
"0",
")",
":",
"NUM_HEADER_LINES",
"=",
"6",
"north",
"=",
"0.0",
"east",
"=",
"0.0",
"west",
"=",
"0.0",
"rows",
"=",
"0",
"columns",
... | Load GRASS ASCII rasters directly using the makeSingleBandWKBRaster method. Do this to eliminate the raster2pgsql
dependency. | [
"Load",
"GRASS",
"ASCII",
"rasters",
"directly",
"using",
"the",
"makeSingleBandWKBRaster",
"method",
".",
"Do",
"this",
"to",
"eliminate",
"the",
"raster2pgsql",
"dependency",
"."
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterLoader.py#L114-L178 | train |
tjcsl/cslbot | cslbot/commands/defersay.py | cmd | def cmd(send, msg, args):
"""Says something at a later time.
Syntax: {command} <delay> <msg>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('delay')
parser.add_argument('msg', nargs='+')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentExcept... | python | def cmd(send, msg, args):
"""Says something at a later time.
Syntax: {command} <delay> <msg>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('delay')
parser.add_argument('msg', nargs='+')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentExcept... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'delay'",
")",
"parser",
".",
"add_argument",
"(",
"'msg'",
",",
... | Says something at a later time.
Syntax: {command} <delay> <msg> | [
"Says",
"something",
"at",
"a",
"later",
"time",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/defersay.py#L24-L47 | train |
marrow/util | marrow/util/tuple.py | NamedTuple._replace | def _replace(self, **kwds):
'Return a new NamedTuple object replacing specified fields with new values'
result = self._make(map(kwds.pop, self._fields, self))
if kwds:
raise ValueError('Got unexpected field names: %r' % kwds.keys())
return result | python | def _replace(self, **kwds):
'Return a new NamedTuple object replacing specified fields with new values'
result = self._make(map(kwds.pop, self._fields, self))
if kwds:
raise ValueError('Got unexpected field names: %r' % kwds.keys())
return result | [
"def",
"_replace",
"(",
"self",
",",
"**",
"kwds",
")",
":",
"'Return a new NamedTuple object replacing specified fields with new values'",
"result",
"=",
"self",
".",
"_make",
"(",
"map",
"(",
"kwds",
".",
"pop",
",",
"self",
".",
"_fields",
",",
"self",
")",
... | Return a new NamedTuple object replacing specified fields with new values | [
"Return",
"a",
"new",
"NamedTuple",
"object",
"replacing",
"specified",
"fields",
"with",
"new",
"values"
] | abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/tuple.py#L63-L70 | train |
rraadd88/rohan | rohan/dandage/io_dfs.py | concat_cols | def concat_cols(df1,df2,idx_col,df1_cols,df2_cols,
df1_suffix,df2_suffix,wc_cols=[],suffix_all=False):
"""
Concatenates two pandas tables
:param df1: dataframe 1
:param df2: dataframe 2
:param idx_col: column name which will be used as a common index
"""
df1=df1.set_index... | python | def concat_cols(df1,df2,idx_col,df1_cols,df2_cols,
df1_suffix,df2_suffix,wc_cols=[],suffix_all=False):
"""
Concatenates two pandas tables
:param df1: dataframe 1
:param df2: dataframe 2
:param idx_col: column name which will be used as a common index
"""
df1=df1.set_index... | [
"def",
"concat_cols",
"(",
"df1",
",",
"df2",
",",
"idx_col",
",",
"df1_cols",
",",
"df2_cols",
",",
"df1_suffix",
",",
"df2_suffix",
",",
"wc_cols",
"=",
"[",
"]",
",",
"suffix_all",
"=",
"False",
")",
":",
"df1",
"=",
"df1",
".",
"set_index",
"(",
... | Concatenates two pandas tables
:param df1: dataframe 1
:param df2: dataframe 2
:param idx_col: column name which will be used as a common index | [
"Concatenates",
"two",
"pandas",
"tables"
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_dfs.py#L174-L206 | train |
rraadd88/rohan | rohan/dandage/io_dfs.py | get_colmin | def get_colmin(data):
"""
Get rowwise column names with minimum values
:param data: pandas dataframe
"""
data=data.T
colmins=[]
for col in data:
colmins.append(data[col].idxmin())
return colmins | python | def get_colmin(data):
"""
Get rowwise column names with minimum values
:param data: pandas dataframe
"""
data=data.T
colmins=[]
for col in data:
colmins.append(data[col].idxmin())
return colmins | [
"def",
"get_colmin",
"(",
"data",
")",
":",
"data",
"=",
"data",
".",
"T",
"colmins",
"=",
"[",
"]",
"for",
"col",
"in",
"data",
":",
"colmins",
".",
"append",
"(",
"data",
"[",
"col",
"]",
".",
"idxmin",
"(",
")",
")",
"return",
"colmins"
] | Get rowwise column names with minimum values
:param data: pandas dataframe | [
"Get",
"rowwise",
"column",
"names",
"with",
"minimum",
"values"
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_dfs.py#L208-L218 | train |
rraadd88/rohan | rohan/dandage/io_dfs.py | fhs2data_combo_appended | def fhs2data_combo_appended(fhs, cols=None,labels=None,labels_coln='labels',sep=',',
error_bad_lines=True):
"""
to be deprecated
Collates data from multiple csv files vertically
:param fhs: list of paths to csv files
:param cols: list of column names to concatenate
""... | python | def fhs2data_combo_appended(fhs, cols=None,labels=None,labels_coln='labels',sep=',',
error_bad_lines=True):
"""
to be deprecated
Collates data from multiple csv files vertically
:param fhs: list of paths to csv files
:param cols: list of column names to concatenate
""... | [
"def",
"fhs2data_combo_appended",
"(",
"fhs",
",",
"cols",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"labels_coln",
"=",
"'labels'",
",",
"sep",
"=",
"','",
",",
"error_bad_lines",
"=",
"True",
")",
":",
"if",
"labels",
"is",
"None",
":",
"labels",
... | to be deprecated
Collates data from multiple csv files vertically
:param fhs: list of paths to csv files
:param cols: list of column names to concatenate | [
"to",
"be",
"deprecated",
"Collates",
"data",
"from",
"multiple",
"csv",
"files",
"vertically"
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_dfs.py#L248-L272 | train |
rraadd88/rohan | rohan/dandage/io_dfs.py | rename_cols | def rename_cols(df,names,renames=None,prefix=None,suffix=None):
"""
rename columns of a pandas table
:param df: pandas dataframe
:param names: list of new column names
"""
if not prefix is None:
renames=[ "%s%s" % (prefix,s) for s in names]
if not suffix is None:
renames... | python | def rename_cols(df,names,renames=None,prefix=None,suffix=None):
"""
rename columns of a pandas table
:param df: pandas dataframe
:param names: list of new column names
"""
if not prefix is None:
renames=[ "%s%s" % (prefix,s) for s in names]
if not suffix is None:
renames... | [
"def",
"rename_cols",
"(",
"df",
",",
"names",
",",
"renames",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"suffix",
"=",
"None",
")",
":",
"if",
"not",
"prefix",
"is",
"None",
":",
"renames",
"=",
"[",
"\"%s%s\"",
"%",
"(",
"prefix",
",",
"s",
... | rename columns of a pandas table
:param df: pandas dataframe
:param names: list of new column names | [
"rename",
"columns",
"of",
"a",
"pandas",
"table"
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_dfs.py#L275-L292 | train |
rraadd88/rohan | rohan/dandage/io_dfs.py | reorderbydf | def reorderbydf(df2,df1):
"""
Reorder rows of a dataframe by other dataframe
:param df2: input dataframe
:param df1: template dataframe
"""
df3=pd.DataFrame()
for idx,row in df1.iterrows():
df3=df3.append(df2.loc[idx,:])
return df3 | python | def reorderbydf(df2,df1):
"""
Reorder rows of a dataframe by other dataframe
:param df2: input dataframe
:param df1: template dataframe
"""
df3=pd.DataFrame()
for idx,row in df1.iterrows():
df3=df3.append(df2.loc[idx,:])
return df3 | [
"def",
"reorderbydf",
"(",
"df2",
",",
"df1",
")",
":",
"df3",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"for",
"idx",
",",
"row",
"in",
"df1",
".",
"iterrows",
"(",
")",
":",
"df3",
"=",
"df3",
".",
"append",
"(",
"df2",
".",
"loc",
"[",
"idx",
... | Reorder rows of a dataframe by other dataframe
:param df2: input dataframe
:param df1: template dataframe | [
"Reorder",
"rows",
"of",
"a",
"dataframe",
"by",
"other",
"dataframe"
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_dfs.py#L295-L305 | train |
rraadd88/rohan | rohan/dandage/io_dfs.py | df2unstack | def df2unstack(df,coln='columns',idxn='index',col='value'):
"""
will be deprecated
"""
return dmap2lin(df,idxn=idxn,coln=coln,colvalue_name=col) | python | def df2unstack(df,coln='columns',idxn='index',col='value'):
"""
will be deprecated
"""
return dmap2lin(df,idxn=idxn,coln=coln,colvalue_name=col) | [
"def",
"df2unstack",
"(",
"df",
",",
"coln",
"=",
"'columns'",
",",
"idxn",
"=",
"'index'",
",",
"col",
"=",
"'value'",
")",
":",
"return",
"dmap2lin",
"(",
"df",
",",
"idxn",
"=",
"idxn",
",",
"coln",
"=",
"coln",
",",
"colvalue_name",
"=",
"col",
... | will be deprecated | [
"will",
"be",
"deprecated"
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_dfs.py#L325-L329 | train |
rraadd88/rohan | rohan/dandage/io_dfs.py | get_offdiag_vals | def get_offdiag_vals(dcorr):
"""
for lin dcorr i guess
"""
del_indexes=[]
for spc1 in np.unique(dcorr.index.get_level_values(0)):
for spc2 in np.unique(dcorr.index.get_level_values(0)):
if (not (spc1,spc2) in del_indexes) and (not (spc2,spc1) in del_indexes):
del_... | python | def get_offdiag_vals(dcorr):
"""
for lin dcorr i guess
"""
del_indexes=[]
for spc1 in np.unique(dcorr.index.get_level_values(0)):
for spc2 in np.unique(dcorr.index.get_level_values(0)):
if (not (spc1,spc2) in del_indexes) and (not (spc2,spc1) in del_indexes):
del_... | [
"def",
"get_offdiag_vals",
"(",
"dcorr",
")",
":",
"del_indexes",
"=",
"[",
"]",
"for",
"spc1",
"in",
"np",
".",
"unique",
"(",
"dcorr",
".",
"index",
".",
"get_level_values",
"(",
"0",
")",
")",
":",
"for",
"spc2",
"in",
"np",
".",
"unique",
"(",
... | for lin dcorr i guess | [
"for",
"lin",
"dcorr",
"i",
"guess"
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_dfs.py#L490-L505 | train |
ymyzk/python-gyazo | gyazo/image.py | Image.from_dict | def from_dict(data):
"""Create a new instance from dict
:param data: A JSON dict
"""
data = deepcopy(data)
created_at = data.get('created_at', None)
if created_at is not None:
data['created_at'] = dateutil.parser.parse(created_at)
return Image(**dat... | python | def from_dict(data):
"""Create a new instance from dict
:param data: A JSON dict
"""
data = deepcopy(data)
created_at = data.get('created_at', None)
if created_at is not None:
data['created_at'] = dateutil.parser.parse(created_at)
return Image(**dat... | [
"def",
"from_dict",
"(",
"data",
")",
":",
"data",
"=",
"deepcopy",
"(",
"data",
")",
"created_at",
"=",
"data",
".",
"get",
"(",
"'created_at'",
",",
"None",
")",
"if",
"created_at",
"is",
"not",
"None",
":",
"data",
"[",
"'created_at'",
"]",
"=",
"... | Create a new instance from dict
:param data: A JSON dict | [
"Create",
"a",
"new",
"instance",
"from",
"dict"
] | 52893118899ed308ff75245b55f73d745c98ed1d | https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/image.py#L31-L42 | train |
ymyzk/python-gyazo | gyazo/image.py | Image.to_json | def to_json(self, indent=None, sort_keys=True):
"""Return a JSON string representation of this instance
:param indent: specify an indent level or a string used to indent each
level
:param sort_keys: the output is sorted by key
"""
return json.dumps(self.to... | python | def to_json(self, indent=None, sort_keys=True):
"""Return a JSON string representation of this instance
:param indent: specify an indent level or a string used to indent each
level
:param sort_keys: the output is sorted by key
"""
return json.dumps(self.to... | [
"def",
"to_json",
"(",
"self",
",",
"indent",
"=",
"None",
",",
"sort_keys",
"=",
"True",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"to_dict",
"(",
")",
",",
"indent",
"=",
"indent",
",",
"sort_keys",
"=",
"sort_keys",
")"
] | Return a JSON string representation of this instance
:param indent: specify an indent level or a string used to indent each
level
:param sort_keys: the output is sorted by key | [
"Return",
"a",
"JSON",
"string",
"representation",
"of",
"this",
"instance"
] | 52893118899ed308ff75245b55f73d745c98ed1d | https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/image.py#L102-L109 | train |
ymyzk/python-gyazo | gyazo/image.py | Image.to_dict | def to_dict(self):
"""Return a dict representation of this instance"""
data = {}
if self.created_at:
data['created_at'] = self.created_at.strftime(
'%Y-%m-%dT%H:%M:%S%z')
if self.image_id:
data['image_id'] = self.image_id
if self.permalink... | python | def to_dict(self):
"""Return a dict representation of this instance"""
data = {}
if self.created_at:
data['created_at'] = self.created_at.strftime(
'%Y-%m-%dT%H:%M:%S%z')
if self.image_id:
data['image_id'] = self.image_id
if self.permalink... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"if",
"self",
".",
"created_at",
":",
"data",
"[",
"'created_at'",
"]",
"=",
"self",
".",
"created_at",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%S%z'",
")",
"if",
"self",
".",
"image_id",
"... | Return a dict representation of this instance | [
"Return",
"a",
"dict",
"representation",
"of",
"this",
"instance"
] | 52893118899ed308ff75245b55f73d745c98ed1d | https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/image.py#L111-L129 | train |
ymyzk/python-gyazo | gyazo/image.py | Image.download | def download(self):
"""Download an image file if it exists
:raise GyazoError:
"""
if self.url:
try:
return requests.get(self.url).content
except requests.RequestException as e:
raise GyazoError(str(e))
return None | python | def download(self):
"""Download an image file if it exists
:raise GyazoError:
"""
if self.url:
try:
return requests.get(self.url).content
except requests.RequestException as e:
raise GyazoError(str(e))
return None | [
"def",
"download",
"(",
"self",
")",
":",
"if",
"self",
".",
"url",
":",
"try",
":",
"return",
"requests",
".",
"get",
"(",
"self",
".",
"url",
")",
".",
"content",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"raise",
"GyazoError",
... | Download an image file if it exists
:raise GyazoError: | [
"Download",
"an",
"image",
"file",
"if",
"it",
"exists"
] | 52893118899ed308ff75245b55f73d745c98ed1d | https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/image.py#L131-L141 | train |
ymyzk/python-gyazo | gyazo/image.py | Image.download_thumb | def download_thumb(self):
"""Download a thumbnail image file
:raise GyazoError:
"""
try:
return requests.get(self.thumb_url).content
except requests.RequestException as e:
raise GyazoError(str(e)) | python | def download_thumb(self):
"""Download a thumbnail image file
:raise GyazoError:
"""
try:
return requests.get(self.thumb_url).content
except requests.RequestException as e:
raise GyazoError(str(e)) | [
"def",
"download_thumb",
"(",
"self",
")",
":",
"try",
":",
"return",
"requests",
".",
"get",
"(",
"self",
".",
"thumb_url",
")",
".",
"content",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"raise",
"GyazoError",
"(",
"str",
"(",
"e",
... | Download a thumbnail image file
:raise GyazoError: | [
"Download",
"a",
"thumbnail",
"image",
"file"
] | 52893118899ed308ff75245b55f73d745c98ed1d | https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/image.py#L143-L151 | train |
ymyzk/python-gyazo | gyazo/image.py | ImageList.has_next_page | def has_next_page(self):
"""Whether there is a next page or not
:getter: Return true if there is a next page
"""
return self.current_page < math.ceil(self.total_count / self.per_page) | python | def has_next_page(self):
"""Whether there is a next page or not
:getter: Return true if there is a next page
"""
return self.current_page < math.ceil(self.total_count / self.per_page) | [
"def",
"has_next_page",
"(",
"self",
")",
":",
"return",
"self",
".",
"current_page",
"<",
"math",
".",
"ceil",
"(",
"self",
".",
"total_count",
"/",
"self",
".",
"per_page",
")"
] | Whether there is a next page or not
:getter: Return true if there is a next page | [
"Whether",
"there",
"is",
"a",
"next",
"page",
"or",
"not"
] | 52893118899ed308ff75245b55f73d745c98ed1d | https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/image.py#L198-L203 | train |
ymyzk/python-gyazo | gyazo/image.py | ImageList.set_attributes_from_headers | def set_attributes_from_headers(self, headers):
"""Set instance attributes with HTTP header
:param headers: HTTP header
"""
self.total_count = headers.get('x-total-count', None)
self.current_page = headers.get('x-current-page', None)
self.per_page = headers.get('x-per-pa... | python | def set_attributes_from_headers(self, headers):
"""Set instance attributes with HTTP header
:param headers: HTTP header
"""
self.total_count = headers.get('x-total-count', None)
self.current_page = headers.get('x-current-page', None)
self.per_page = headers.get('x-per-pa... | [
"def",
"set_attributes_from_headers",
"(",
"self",
",",
"headers",
")",
":",
"self",
".",
"total_count",
"=",
"headers",
".",
"get",
"(",
"'x-total-count'",
",",
"None",
")",
"self",
".",
"current_page",
"=",
"headers",
".",
"get",
"(",
"'x-current-page'",
"... | Set instance attributes with HTTP header
:param headers: HTTP header | [
"Set",
"instance",
"attributes",
"with",
"HTTP",
"header"
] | 52893118899ed308ff75245b55f73d745c98ed1d | https://github.com/ymyzk/python-gyazo/blob/52893118899ed308ff75245b55f73d745c98ed1d/gyazo/image.py#L212-L227 | train |
Xion/taipan | taipan/objective/base.py | ObjectMetaclass._validate_base_classes | def _validate_base_classes(meta, bases):
"""Validate the base classes of the new class to be created,
making sure none of them are ``@final``.
"""
for base in bases:
if meta._is_final(base):
raise ClassError(
"cannot inherit from @final cla... | python | def _validate_base_classes(meta, bases):
"""Validate the base classes of the new class to be created,
making sure none of them are ``@final``.
"""
for base in bases:
if meta._is_final(base):
raise ClassError(
"cannot inherit from @final cla... | [
"def",
"_validate_base_classes",
"(",
"meta",
",",
"bases",
")",
":",
"for",
"base",
"in",
"bases",
":",
"if",
"meta",
".",
"_is_final",
"(",
"base",
")",
":",
"raise",
"ClassError",
"(",
"\"cannot inherit from @final class %s\"",
"%",
"(",
"base",
".",
"__n... | Validate the base classes of the new class to be created,
making sure none of them are ``@final``. | [
"Validate",
"the",
"base",
"classes",
"of",
"the",
"new",
"class",
"to",
"be",
"created",
"making",
"sure",
"none",
"of",
"them",
"are"
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/base.py#L50-L57 | train |
Xion/taipan | taipan/objective/base.py | ObjectMetaclass._validate_method_decoration | def _validate_method_decoration(meta, class_):
"""Validate the usage of ``@override`` and ``@final`` modifiers
on methods of the given ``class_``.
"""
# TODO(xion): employ some code inspection tricks to serve ClassErrors
# as if they were thrown at the offending class's/method's ... | python | def _validate_method_decoration(meta, class_):
"""Validate the usage of ``@override`` and ``@final`` modifiers
on methods of the given ``class_``.
"""
# TODO(xion): employ some code inspection tricks to serve ClassErrors
# as if they were thrown at the offending class's/method's ... | [
"def",
"_validate_method_decoration",
"(",
"meta",
",",
"class_",
")",
":",
"super_mro",
"=",
"class_",
".",
"__mro__",
"[",
"1",
":",
"]",
"own_methods",
"=",
"(",
"(",
"name",
",",
"member",
")",
"for",
"name",
",",
"member",
"in",
"class_",
".",
"__... | Validate the usage of ``@override`` and ``@final`` modifiers
on methods of the given ``class_``. | [
"Validate",
"the",
"usage",
"of"
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/base.py#L60-L114 | train |
Xion/taipan | taipan/objective/base.py | ObjectMetaclass._is_final | def _is_final(meta, arg):
"""Checks whether given class or method has been marked
with the ``@final`` decorator.
"""
if inspect.isclass(arg) and not isinstance(arg, ObjectMetaclass):
return False # of classes, only subclasses of Object can be final
# account for met... | python | def _is_final(meta, arg):
"""Checks whether given class or method has been marked
with the ``@final`` decorator.
"""
if inspect.isclass(arg) and not isinstance(arg, ObjectMetaclass):
return False # of classes, only subclasses of Object can be final
# account for met... | [
"def",
"_is_final",
"(",
"meta",
",",
"arg",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"arg",
")",
"and",
"not",
"isinstance",
"(",
"arg",
",",
"ObjectMetaclass",
")",
":",
"return",
"False",
"from",
"taipan",
".",
"objective",
".",
"modifiers",
... | Checks whether given class or method has been marked
with the ``@final`` decorator. | [
"Checks",
"whether",
"given",
"class",
"or",
"method",
"has",
"been",
"marked",
"with",
"the"
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/base.py#L117-L129 | train |
Xion/taipan | taipan/objective/base.py | ObjectMetaclass._is_override | def _is_override(meta, method):
"""Checks whether given class or instance method has been marked
with the ``@override`` decorator.
"""
from taipan.objective.modifiers import _OverriddenMethod
return isinstance(method, _OverriddenMethod) | python | def _is_override(meta, method):
"""Checks whether given class or instance method has been marked
with the ``@override`` decorator.
"""
from taipan.objective.modifiers import _OverriddenMethod
return isinstance(method, _OverriddenMethod) | [
"def",
"_is_override",
"(",
"meta",
",",
"method",
")",
":",
"from",
"taipan",
".",
"objective",
".",
"modifiers",
"import",
"_OverriddenMethod",
"return",
"isinstance",
"(",
"method",
",",
"_OverriddenMethod",
")"
] | Checks whether given class or instance method has been marked
with the ``@override`` decorator. | [
"Checks",
"whether",
"given",
"class",
"or",
"instance",
"method",
"has",
"been",
"marked",
"with",
"the"
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/base.py#L132-L137 | train |
fangpenlin/gluttony | gluttony/dependency.py | trace_dependencies | def trace_dependencies(req, requirement_set, dependencies, _visited=None):
"""Trace all dependency relationship
@param req: requirements to trace
@param requirement_set: RequirementSet
@param dependencies: list for storing dependencies relationships
@param _visited: visited requirement se... | python | def trace_dependencies(req, requirement_set, dependencies, _visited=None):
"""Trace all dependency relationship
@param req: requirements to trace
@param requirement_set: RequirementSet
@param dependencies: list for storing dependencies relationships
@param _visited: visited requirement se... | [
"def",
"trace_dependencies",
"(",
"req",
",",
"requirement_set",
",",
"dependencies",
",",
"_visited",
"=",
"None",
")",
":",
"_visited",
"=",
"_visited",
"or",
"set",
"(",
")",
"if",
"req",
"in",
"_visited",
":",
"return",
"_visited",
".",
"add",
"(",
"... | Trace all dependency relationship
@param req: requirements to trace
@param requirement_set: RequirementSet
@param dependencies: list for storing dependencies relationships
@param _visited: visited requirement set | [
"Trace",
"all",
"dependency",
"relationship"
] | 86c24c7555dbc8de073aee66edb07a030f77275e | https://github.com/fangpenlin/gluttony/blob/86c24c7555dbc8de073aee66edb07a030f77275e/gluttony/dependency.py#L7-L28 | train |
jmbeach/KEP.py | src/keppy/register.py | pad_zeroes | def pad_zeroes(addr, n_zeroes):
"""Padds the address with zeroes"""
if len(addr) < n_zeroes:
return pad_zeroes("0" + addr, n_zeroes)
return addr | python | def pad_zeroes(addr, n_zeroes):
"""Padds the address with zeroes"""
if len(addr) < n_zeroes:
return pad_zeroes("0" + addr, n_zeroes)
return addr | [
"def",
"pad_zeroes",
"(",
"addr",
",",
"n_zeroes",
")",
":",
"if",
"len",
"(",
"addr",
")",
"<",
"n_zeroes",
":",
"return",
"pad_zeroes",
"(",
"\"0\"",
"+",
"addr",
",",
"n_zeroes",
")",
"return",
"addr"
] | Padds the address with zeroes | [
"Padds",
"the",
"address",
"with",
"zeroes"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/register.py#L2-L6 | train |
jmbeach/KEP.py | src/keppy/register.py | next_addr | def next_addr(addr, i):
"""Gets address after the current + i"""
str_addr = pad_zeroes(str(int_addr(addr) + i), len(addr[1:]))
return addr[0] + str_addr | python | def next_addr(addr, i):
"""Gets address after the current + i"""
str_addr = pad_zeroes(str(int_addr(addr) + i), len(addr[1:]))
return addr[0] + str_addr | [
"def",
"next_addr",
"(",
"addr",
",",
"i",
")",
":",
"str_addr",
"=",
"pad_zeroes",
"(",
"str",
"(",
"int_addr",
"(",
"addr",
")",
"+",
"i",
")",
",",
"len",
"(",
"addr",
"[",
"1",
":",
"]",
")",
")",
"return",
"addr",
"[",
"0",
"]",
"+",
"st... | Gets address after the current + i | [
"Gets",
"address",
"after",
"the",
"current",
"+",
"i"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/register.py#L12-L15 | train |
jmbeach/KEP.py | src/keppy/register.py | Register.mark_address | def mark_address(self, addr, size):
"""Marks address as being used in simulator"""
i = 0
while i < size:
self._register_map[addr] = True
i += 1 | python | def mark_address(self, addr, size):
"""Marks address as being used in simulator"""
i = 0
while i < size:
self._register_map[addr] = True
i += 1 | [
"def",
"mark_address",
"(",
"self",
",",
"addr",
",",
"size",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"size",
":",
"self",
".",
"_register_map",
"[",
"addr",
"]",
"=",
"True",
"i",
"+=",
"1"
] | Marks address as being used in simulator | [
"Marks",
"address",
"as",
"being",
"used",
"in",
"simulator"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/register.py#L53-L58 | train |
jmbeach/KEP.py | src/keppy/register.py | Register.next_address_avoid_collision | def next_address_avoid_collision(self, start_addr):
"""Finds the next address recursively which does not collide with any other address"""
i = 1
while self.is_address_in_use(next_addr(start_addr, i)):
i += 1
return next_addr(start_addr, i) | python | def next_address_avoid_collision(self, start_addr):
"""Finds the next address recursively which does not collide with any other address"""
i = 1
while self.is_address_in_use(next_addr(start_addr, i)):
i += 1
return next_addr(start_addr, i) | [
"def",
"next_address_avoid_collision",
"(",
"self",
",",
"start_addr",
")",
":",
"i",
"=",
"1",
"while",
"self",
".",
"is_address_in_use",
"(",
"next_addr",
"(",
"start_addr",
",",
"i",
")",
")",
":",
"i",
"+=",
"1",
"return",
"next_addr",
"(",
"start_addr... | Finds the next address recursively which does not collide with any other address | [
"Finds",
"the",
"next",
"address",
"recursively",
"which",
"does",
"not",
"collide",
"with",
"any",
"other",
"address"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/register.py#L64-L69 | train |
jmbeach/KEP.py | src/keppy/register.py | Register.move_to_next_bit_address | def move_to_next_bit_address(self):
"""Moves to next available bit address position"""
self._current_bit_address = self.next_bit_address()
self.mark_address(self._current_bit_address.split('.')[0], self._size_of_current_register_address) | python | def move_to_next_bit_address(self):
"""Moves to next available bit address position"""
self._current_bit_address = self.next_bit_address()
self.mark_address(self._current_bit_address.split('.')[0], self._size_of_current_register_address) | [
"def",
"move_to_next_bit_address",
"(",
"self",
")",
":",
"self",
".",
"_current_bit_address",
"=",
"self",
".",
"next_bit_address",
"(",
")",
"self",
".",
"mark_address",
"(",
"self",
".",
"_current_bit_address",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]"... | Moves to next available bit address position | [
"Moves",
"to",
"next",
"available",
"bit",
"address",
"position"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/register.py#L82-L85 | train |
jmbeach/KEP.py | src/keppy/register.py | Register.next_bit_address | def next_bit_address(self):
"""Gets the next boolean address"""
if self._current_bit_address == "":
if self._is_16bit:
return "{0}.{1}".format(
self.next_address(),
"00")
return "{0}.{1}".format(
self.next_ad... | python | def next_bit_address(self):
"""Gets the next boolean address"""
if self._current_bit_address == "":
if self._is_16bit:
return "{0}.{1}".format(
self.next_address(),
"00")
return "{0}.{1}".format(
self.next_ad... | [
"def",
"next_bit_address",
"(",
"self",
")",
":",
"if",
"self",
".",
"_current_bit_address",
"==",
"\"\"",
":",
"if",
"self",
".",
"_is_16bit",
":",
"return",
"\"{0}.{1}\"",
".",
"format",
"(",
"self",
".",
"next_address",
"(",
")",
",",
"\"00\"",
")",
"... | Gets the next boolean address | [
"Gets",
"the",
"next",
"boolean",
"address"
] | 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/register.py#L91-L121 | train |
The-Politico/politico-civic-election-night | electionnight/management/commands/bootstrap_electionnight_content.py | Command.route_election | def route_election(self, election):
"""
Legislative or executive office?
"""
if (
election.election_type.slug == ElectionType.GENERAL
or ElectionType.GENERAL_RUNOFF
):
self.bootstrap_general_election(election)
elif election.race.special... | python | def route_election(self, election):
"""
Legislative or executive office?
"""
if (
election.election_type.slug == ElectionType.GENERAL
or ElectionType.GENERAL_RUNOFF
):
self.bootstrap_general_election(election)
elif election.race.special... | [
"def",
"route_election",
"(",
"self",
",",
"election",
")",
":",
"if",
"(",
"election",
".",
"election_type",
".",
"slug",
"==",
"ElectionType",
".",
"GENERAL",
"or",
"ElectionType",
".",
"GENERAL_RUNOFF",
")",
":",
"self",
".",
"bootstrap_general_election",
"... | Legislative or executive office? | [
"Legislative",
"or",
"executive",
"office?"
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/management/commands/bootstrap_electionnight_content.py#L23-L38 | train |
venthur/python-debianbts | debianbts/debianbts.py | get_status | def get_status(*nrs):
"""Returns a list of Bugreport objects.
Given a list of bugnumbers this method returns a list of Bugreport
objects.
Parameters
----------
nrs : int or list of ints
the bugnumbers
Returns
-------
bugs : list of Bugreport objects
"""
# If we ca... | python | def get_status(*nrs):
"""Returns a list of Bugreport objects.
Given a list of bugnumbers this method returns a list of Bugreport
objects.
Parameters
----------
nrs : int or list of ints
the bugnumbers
Returns
-------
bugs : list of Bugreport objects
"""
# If we ca... | [
"def",
"get_status",
"(",
"*",
"nrs",
")",
":",
"bugs",
"=",
"[",
"]",
"list_",
"=",
"[",
"]",
"for",
"nr",
"in",
"nrs",
":",
"if",
"isinstance",
"(",
"nr",
",",
"list",
")",
":",
"list_",
".",
"extend",
"(",
"nr",
")",
"else",
":",
"list_",
... | Returns a list of Bugreport objects.
Given a list of bugnumbers this method returns a list of Bugreport
objects.
Parameters
----------
nrs : int or list of ints
the bugnumbers
Returns
-------
bugs : list of Bugreport objects | [
"Returns",
"a",
"list",
"of",
"Bugreport",
"objects",
"."
] | 72cf11ae3458a8544142e9f365aaafe25634dd4f | https://github.com/venthur/python-debianbts/blob/72cf11ae3458a8544142e9f365aaafe25634dd4f/debianbts/debianbts.py#L208-L246 | train |
venthur/python-debianbts | debianbts/debianbts.py | get_usertag | def get_usertag(email, *tags):
"""Get buglists by usertags.
Parameters
----------
email : str
tags : tuple of strings
If tags are given the dictionary is limited to the matching
tags, if no tags are given all available tags are returned.
Returns
-------
mapping : dict
... | python | def get_usertag(email, *tags):
"""Get buglists by usertags.
Parameters
----------
email : str
tags : tuple of strings
If tags are given the dictionary is limited to the matching
tags, if no tags are given all available tags are returned.
Returns
-------
mapping : dict
... | [
"def",
"get_usertag",
"(",
"email",
",",
"*",
"tags",
")",
":",
"reply",
"=",
"_soap_client_call",
"(",
"'get_usertag'",
",",
"email",
",",
"*",
"tags",
")",
"map_el",
"=",
"reply",
"(",
"'s-gensym3'",
")",
"mapping",
"=",
"{",
"}",
"type_attr",
"=",
"... | Get buglists by usertags.
Parameters
----------
email : str
tags : tuple of strings
If tags are given the dictionary is limited to the matching
tags, if no tags are given all available tags are returned.
Returns
-------
mapping : dict
a mapping of usertag -> buglist | [
"Get",
"buglists",
"by",
"usertags",
"."
] | 72cf11ae3458a8544142e9f365aaafe25634dd4f | https://github.com/venthur/python-debianbts/blob/72cf11ae3458a8544142e9f365aaafe25634dd4f/debianbts/debianbts.py#L249-L282 | train |
venthur/python-debianbts | debianbts/debianbts.py | get_bug_log | def get_bug_log(nr):
"""Get Buglogs.
A buglog is a dictionary with the following mappings:
* "header" => string
* "body" => string
* "attachments" => list
* "msg_num" => int
* "message" => email.message.Message
Parameters
----------
nr : int
the bugn... | python | def get_bug_log(nr):
"""Get Buglogs.
A buglog is a dictionary with the following mappings:
* "header" => string
* "body" => string
* "attachments" => list
* "msg_num" => int
* "message" => email.message.Message
Parameters
----------
nr : int
the bugn... | [
"def",
"get_bug_log",
"(",
"nr",
")",
":",
"reply",
"=",
"_soap_client_call",
"(",
"'get_bug_log'",
",",
"nr",
")",
"items_el",
"=",
"reply",
"(",
"'soapenc:Array'",
")",
"buglogs",
"=",
"[",
"]",
"for",
"buglog_el",
"in",
"items_el",
".",
"children",
"(",... | Get Buglogs.
A buglog is a dictionary with the following mappings:
* "header" => string
* "body" => string
* "attachments" => list
* "msg_num" => int
* "message" => email.message.Message
Parameters
----------
nr : int
the bugnumber
Returns
-----... | [
"Get",
"Buglogs",
"."
] | 72cf11ae3458a8544142e9f365aaafe25634dd4f | https://github.com/venthur/python-debianbts/blob/72cf11ae3458a8544142e9f365aaafe25634dd4f/debianbts/debianbts.py#L285-L323 | train |
venthur/python-debianbts | debianbts/debianbts.py | newest_bugs | def newest_bugs(amount):
"""Returns the newest bugs.
This method can be used to query the BTS for the n newest bugs.
Parameters
----------
amount : int
the number of desired bugs. E.g. if `amount` is 10 the method
will return the 10 latest bugs.
Returns
-------
bugs : ... | python | def newest_bugs(amount):
"""Returns the newest bugs.
This method can be used to query the BTS for the n newest bugs.
Parameters
----------
amount : int
the number of desired bugs. E.g. if `amount` is 10 the method
will return the 10 latest bugs.
Returns
-------
bugs : ... | [
"def",
"newest_bugs",
"(",
"amount",
")",
":",
"reply",
"=",
"_soap_client_call",
"(",
"'newest_bugs'",
",",
"amount",
")",
"items_el",
"=",
"reply",
"(",
"'soapenc:Array'",
")",
"return",
"[",
"int",
"(",
"item_el",
")",
"for",
"item_el",
"in",
"items_el",
... | Returns the newest bugs.
This method can be used to query the BTS for the n newest bugs.
Parameters
----------
amount : int
the number of desired bugs. E.g. if `amount` is 10 the method
will return the 10 latest bugs.
Returns
-------
bugs : list of int
the bugnumbe... | [
"Returns",
"the",
"newest",
"bugs",
"."
] | 72cf11ae3458a8544142e9f365aaafe25634dd4f | https://github.com/venthur/python-debianbts/blob/72cf11ae3458a8544142e9f365aaafe25634dd4f/debianbts/debianbts.py#L326-L345 | train |
venthur/python-debianbts | debianbts/debianbts.py | get_bugs | def get_bugs(*key_value):
"""Get list of bugs matching certain criteria.
The conditions are defined by key value pairs.
Possible keys are:
* "package": bugs for the given package
* "submitter": bugs from the submitter
* "maint": bugs belonging to a maintainer
* "src": bugs ... | python | def get_bugs(*key_value):
"""Get list of bugs matching certain criteria.
The conditions are defined by key value pairs.
Possible keys are:
* "package": bugs for the given package
* "submitter": bugs from the submitter
* "maint": bugs belonging to a maintainer
* "src": bugs ... | [
"def",
"get_bugs",
"(",
"*",
"key_value",
")",
":",
"if",
"len",
"(",
"key_value",
")",
"==",
"1",
"and",
"isinstance",
"(",
"key_value",
"[",
"0",
"]",
",",
"list",
")",
":",
"key_value",
"=",
"tuple",
"(",
"key_value",
"[",
"0",
"]",
")",
"method... | Get list of bugs matching certain criteria.
The conditions are defined by key value pairs.
Possible keys are:
* "package": bugs for the given package
* "submitter": bugs from the submitter
* "maint": bugs belonging to a maintainer
* "src": bugs belonging to a source package
... | [
"Get",
"list",
"of",
"bugs",
"matching",
"certain",
"criteria",
"."
] | 72cf11ae3458a8544142e9f365aaafe25634dd4f | https://github.com/venthur/python-debianbts/blob/72cf11ae3458a8544142e9f365aaafe25634dd4f/debianbts/debianbts.py#L348-L403 | train |
venthur/python-debianbts | debianbts/debianbts.py | _parse_status | def _parse_status(bug_el):
"""Return a bugreport object from a given status xml element"""
bug = Bugreport()
# plain fields
for field in ('originator', 'subject', 'msgid', 'package', 'severity',
'owner', 'summary', 'location', 'source', 'pending',
'forwarded'):
... | python | def _parse_status(bug_el):
"""Return a bugreport object from a given status xml element"""
bug = Bugreport()
# plain fields
for field in ('originator', 'subject', 'msgid', 'package', 'severity',
'owner', 'summary', 'location', 'source', 'pending',
'forwarded'):
... | [
"def",
"_parse_status",
"(",
"bug_el",
")",
":",
"bug",
"=",
"Bugreport",
"(",
")",
"for",
"field",
"in",
"(",
"'originator'",
",",
"'subject'",
",",
"'msgid'",
",",
"'package'",
",",
"'severity'",
",",
"'owner'",
",",
"'summary'",
",",
"'location'",
",",
... | Return a bugreport object from a given status xml element | [
"Return",
"a",
"bugreport",
"object",
"from",
"a",
"given",
"status",
"xml",
"element"
] | 72cf11ae3458a8544142e9f365aaafe25634dd4f | https://github.com/venthur/python-debianbts/blob/72cf11ae3458a8544142e9f365aaafe25634dd4f/debianbts/debianbts.py#L406-L442 | train |
venthur/python-debianbts | debianbts/debianbts.py | _convert_soap_method_args | def _convert_soap_method_args(*args):
"""Convert arguments to be consumed by a SoapClient method
Soap client required a list of named arguments:
>>> _convert_soap_method_args('a', 1)
[('arg0', 'a'), ('arg1', 1)]
"""
soap_args = []
for arg_n, arg in enumerate(args):
soap_args.append... | python | def _convert_soap_method_args(*args):
"""Convert arguments to be consumed by a SoapClient method
Soap client required a list of named arguments:
>>> _convert_soap_method_args('a', 1)
[('arg0', 'a'), ('arg1', 1)]
"""
soap_args = []
for arg_n, arg in enumerate(args):
soap_args.append... | [
"def",
"_convert_soap_method_args",
"(",
"*",
"args",
")",
":",
"soap_args",
"=",
"[",
"]",
"for",
"arg_n",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"soap_args",
".",
"append",
"(",
"(",
"'arg'",
"+",
"str",
"(",
"arg_n",
")",
",",
"arg"... | Convert arguments to be consumed by a SoapClient method
Soap client required a list of named arguments:
>>> _convert_soap_method_args('a', 1)
[('arg0', 'a'), ('arg1', 1)] | [
"Convert",
"arguments",
"to",
"be",
"consumed",
"by",
"a",
"SoapClient",
"method"
] | 72cf11ae3458a8544142e9f365aaafe25634dd4f | https://github.com/venthur/python-debianbts/blob/72cf11ae3458a8544142e9f365aaafe25634dd4f/debianbts/debianbts.py#L497-L508 | train |
venthur/python-debianbts | debianbts/debianbts.py | _soap_client_call | def _soap_client_call(method_name, *args):
"""Wrapper to call SoapClient method"""
# a new client instance is built for threading issues
soap_client = _build_soap_client()
soap_args = _convert_soap_method_args(*args)
# if pysimplesoap version requires it, apply a workaround for
# https://github.... | python | def _soap_client_call(method_name, *args):
"""Wrapper to call SoapClient method"""
# a new client instance is built for threading issues
soap_client = _build_soap_client()
soap_args = _convert_soap_method_args(*args)
# if pysimplesoap version requires it, apply a workaround for
# https://github.... | [
"def",
"_soap_client_call",
"(",
"method_name",
",",
"*",
"args",
")",
":",
"soap_client",
"=",
"_build_soap_client",
"(",
")",
"soap_args",
"=",
"_convert_soap_method_args",
"(",
"*",
"args",
")",
"if",
"PYSIMPLESOAP_1_16_2",
":",
"return",
"getattr",
"(",
"soa... | Wrapper to call SoapClient method | [
"Wrapper",
"to",
"call",
"SoapClient",
"method"
] | 72cf11ae3458a8544142e9f365aaafe25634dd4f | https://github.com/venthur/python-debianbts/blob/72cf11ae3458a8544142e9f365aaafe25634dd4f/debianbts/debianbts.py#L511-L521 | train |
venthur/python-debianbts | debianbts/debianbts.py | _parse_string_el | def _parse_string_el(el):
"""read a string element, maybe encoded in base64"""
value = str(el)
el_type = el.attributes().get('xsi:type')
if el_type and el_type.value == 'xsd:base64Binary':
value = base64.b64decode(value)
if not PY2:
value = value.decode('utf-8', errors='repla... | python | def _parse_string_el(el):
"""read a string element, maybe encoded in base64"""
value = str(el)
el_type = el.attributes().get('xsi:type')
if el_type and el_type.value == 'xsd:base64Binary':
value = base64.b64decode(value)
if not PY2:
value = value.decode('utf-8', errors='repla... | [
"def",
"_parse_string_el",
"(",
"el",
")",
":",
"value",
"=",
"str",
"(",
"el",
")",
"el_type",
"=",
"el",
".",
"attributes",
"(",
")",
".",
"get",
"(",
"'xsi:type'",
")",
"if",
"el_type",
"and",
"el_type",
".",
"value",
"==",
"'xsd:base64Binary'",
":"... | read a string element, maybe encoded in base64 | [
"read",
"a",
"string",
"element",
"maybe",
"encoded",
"in",
"base64"
] | 72cf11ae3458a8544142e9f365aaafe25634dd4f | https://github.com/venthur/python-debianbts/blob/72cf11ae3458a8544142e9f365aaafe25634dd4f/debianbts/debianbts.py#L544-L553 | train |
omisego/py-solc-simple | solc_simple/builder.py | Builder.get_solc_input | def get_solc_input(self):
"""Walks the contract directory and returns a Solidity input dict
Learn more about Solidity input JSON here: https://goo.gl/7zKBvj
Returns:
dict: A Solidity input JSON object as a dict
"""
def legal(r, file_name):
hidden = file... | python | def get_solc_input(self):
"""Walks the contract directory and returns a Solidity input dict
Learn more about Solidity input JSON here: https://goo.gl/7zKBvj
Returns:
dict: A Solidity input JSON object as a dict
"""
def legal(r, file_name):
hidden = file... | [
"def",
"get_solc_input",
"(",
"self",
")",
":",
"def",
"legal",
"(",
"r",
",",
"file_name",
")",
":",
"hidden",
"=",
"file_name",
"[",
"0",
"]",
"==",
"'.'",
"dotsol",
"=",
"len",
"(",
"file_name",
")",
">",
"3",
"and",
"file_name",
"[",
"-",
"4",
... | Walks the contract directory and returns a Solidity input dict
Learn more about Solidity input JSON here: https://goo.gl/7zKBvj
Returns:
dict: A Solidity input JSON object as a dict | [
"Walks",
"the",
"contract",
"directory",
"and",
"returns",
"a",
"Solidity",
"input",
"dict"
] | 770116fdaa5aae01c2a247e2477f80621e98f0cc | https://github.com/omisego/py-solc-simple/blob/770116fdaa5aae01c2a247e2477f80621e98f0cc/solc_simple/builder.py#L17-L64 | train |
omisego/py-solc-simple | solc_simple/builder.py | Builder.compile_all | def compile_all(self):
"""Compiles all of the contracts in the self.contracts_dir directory
Creates {contract name}.json files in self.output_dir that contain
the build output for each contract.
"""
# Solidity input JSON
solc_input = self.get_solc_input()
# Com... | python | def compile_all(self):
"""Compiles all of the contracts in the self.contracts_dir directory
Creates {contract name}.json files in self.output_dir that contain
the build output for each contract.
"""
# Solidity input JSON
solc_input = self.get_solc_input()
# Com... | [
"def",
"compile_all",
"(",
"self",
")",
":",
"solc_input",
"=",
"self",
".",
"get_solc_input",
"(",
")",
"real_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"self",
".",
"contracts_dir",
")",
"compilation_result",
"=",
"compile_standard",
"(",
"solc_i... | Compiles all of the contracts in the self.contracts_dir directory
Creates {contract name}.json files in self.output_dir that contain
the build output for each contract. | [
"Compiles",
"all",
"of",
"the",
"contracts",
"in",
"the",
"self",
".",
"contracts_dir",
"directory"
] | 770116fdaa5aae01c2a247e2477f80621e98f0cc | https://github.com/omisego/py-solc-simple/blob/770116fdaa5aae01c2a247e2477f80621e98f0cc/solc_simple/builder.py#L66-L92 | train |
omisego/py-solc-simple | solc_simple/builder.py | Builder.get_contract_data | def get_contract_data(self, contract_name):
"""Returns the contract data for a given contract
Args:
contract_name (str): Name of the contract to return.
Returns:
str, str: ABI and bytecode of the contract
"""
contract_data_path = self.output_dir + '/{0}... | python | def get_contract_data(self, contract_name):
"""Returns the contract data for a given contract
Args:
contract_name (str): Name of the contract to return.
Returns:
str, str: ABI and bytecode of the contract
"""
contract_data_path = self.output_dir + '/{0}... | [
"def",
"get_contract_data",
"(",
"self",
",",
"contract_name",
")",
":",
"contract_data_path",
"=",
"self",
".",
"output_dir",
"+",
"'/{0}.json'",
".",
"format",
"(",
"contract_name",
")",
"with",
"open",
"(",
"contract_data_path",
",",
"'r'",
")",
"as",
"cont... | Returns the contract data for a given contract
Args:
contract_name (str): Name of the contract to return.
Returns:
str, str: ABI and bytecode of the contract | [
"Returns",
"the",
"contract",
"data",
"for",
"a",
"given",
"contract"
] | 770116fdaa5aae01c2a247e2477f80621e98f0cc | https://github.com/omisego/py-solc-simple/blob/770116fdaa5aae01c2a247e2477f80621e98f0cc/solc_simple/builder.py#L94-L111 | train |
marrow/util | marrow/util/compat.py | exception | def exception(maxTBlevel=None):
"""Retrieve useful information about an exception.
Returns a bunch (attribute-access dict) with the following information:
* name: exception class name
* cls: the exception class
* exception: the exception instance
* trace: the traceback instance
* formatted... | python | def exception(maxTBlevel=None):
"""Retrieve useful information about an exception.
Returns a bunch (attribute-access dict) with the following information:
* name: exception class name
* cls: the exception class
* exception: the exception instance
* trace: the traceback instance
* formatted... | [
"def",
"exception",
"(",
"maxTBlevel",
"=",
"None",
")",
":",
"try",
":",
"from",
"marrow",
".",
"util",
".",
"bunch",
"import",
"Bunch",
"cls",
",",
"exc",
",",
"trbk",
"=",
"sys",
".",
"exc_info",
"(",
")",
"excName",
"=",
"cls",
".",
"__name__",
... | Retrieve useful information about an exception.
Returns a bunch (attribute-access dict) with the following information:
* name: exception class name
* cls: the exception class
* exception: the exception instance
* trace: the traceback instance
* formatted: formatted traceback
* args: argum... | [
"Retrieve",
"useful",
"information",
"about",
"an",
"exception",
"."
] | abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/compat.py#L55-L90 | train |
marrow/util | marrow/util/compat.py | native | def native(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a given string into a native string."""
if isinstance(s, str):
return s
if str is unicode: # Python 3.x ->
return unicodestr(s, encoding, fallback)
return bytestring(s, encoding, fallback) | python | def native(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a given string into a native string."""
if isinstance(s, str):
return s
if str is unicode: # Python 3.x ->
return unicodestr(s, encoding, fallback)
return bytestring(s, encoding, fallback) | [
"def",
"native",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"fallback",
"=",
"'iso-8859-1'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"return",
"s",
"if",
"str",
"is",
"unicode",
":",
"return",
"unicodestr",
"(",
"s",
",",
... | Convert a given string into a native string. | [
"Convert",
"a",
"given",
"string",
"into",
"a",
"native",
"string",
"."
] | abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/compat.py#L106-L115 | train |
marrow/util | marrow/util/compat.py | unicodestr | def unicodestr(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a string to unicode if it isn't already."""
if isinstance(s, unicode):
return s
try:
return s.decode(encoding)
except UnicodeError:
return s.decode(fallback) | python | def unicodestr(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a string to unicode if it isn't already."""
if isinstance(s, unicode):
return s
try:
return s.decode(encoding)
except UnicodeError:
return s.decode(fallback) | [
"def",
"unicodestr",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"fallback",
"=",
"'iso-8859-1'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"return",
"s",
"try",
":",
"return",
"s",
".",
"decode",
"(",
"encoding",
")",
"ex... | Convert a string to unicode if it isn't already. | [
"Convert",
"a",
"string",
"to",
"unicode",
"if",
"it",
"isn",
"t",
"already",
"."
] | abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/compat.py#L118-L127 | train |
marrow/util | marrow/util/compat.py | uvalues | def uvalues(a, encoding='utf-8', fallback='iso-8859-1'):
"""Return a list of decoded values from an iterator.
If any of the values fail to decode, re-decode all values using the
fallback.
"""
try:
return encoding, [s.decode(encoding) for s in a]
except UnicodeError:
return fal... | python | def uvalues(a, encoding='utf-8', fallback='iso-8859-1'):
"""Return a list of decoded values from an iterator.
If any of the values fail to decode, re-decode all values using the
fallback.
"""
try:
return encoding, [s.decode(encoding) for s in a]
except UnicodeError:
return fal... | [
"def",
"uvalues",
"(",
"a",
",",
"encoding",
"=",
"'utf-8'",
",",
"fallback",
"=",
"'iso-8859-1'",
")",
":",
"try",
":",
"return",
"encoding",
",",
"[",
"s",
".",
"decode",
"(",
"encoding",
")",
"for",
"s",
"in",
"a",
"]",
"except",
"UnicodeError",
"... | Return a list of decoded values from an iterator.
If any of the values fail to decode, re-decode all values using the
fallback. | [
"Return",
"a",
"list",
"of",
"decoded",
"values",
"from",
"an",
"iterator",
"."
] | abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/compat.py#L130-L141 | train |
Yipit/pyeqs | pyeqs/query_builder.py | QueryBuilder._build_query | def _build_query(self):
"""
Build the base query dictionary
"""
if isinstance(self._query_string, QueryString):
self._query_dsl = self._query_string
elif isinstance(self._query_string, string_types):
self._query_dsl = QueryString(self._query_string)
... | python | def _build_query(self):
"""
Build the base query dictionary
"""
if isinstance(self._query_string, QueryString):
self._query_dsl = self._query_string
elif isinstance(self._query_string, string_types):
self._query_dsl = QueryString(self._query_string)
... | [
"def",
"_build_query",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_query_string",
",",
"QueryString",
")",
":",
"self",
".",
"_query_dsl",
"=",
"self",
".",
"_query_string",
"elif",
"isinstance",
"(",
"self",
".",
"_query_string",
",",
"... | Build the base query dictionary | [
"Build",
"the",
"base",
"query",
"dictionary"
] | 2e385c0a5d113af0e20be4d9393add2aabdd9565 | https://github.com/Yipit/pyeqs/blob/2e385c0a5d113af0e20be4d9393add2aabdd9565/pyeqs/query_builder.py#L30-L39 | train |
Yipit/pyeqs | pyeqs/query_builder.py | QueryBuilder._build_filtered_query | def _build_filtered_query(self, f, operator):
"""
Create the root of the filter tree
"""
self._filtered = True
if isinstance(f, Filter):
filter_object = f
else:
filter_object = Filter(operator).filter(f)
self._filter_dsl = filter_object | python | def _build_filtered_query(self, f, operator):
"""
Create the root of the filter tree
"""
self._filtered = True
if isinstance(f, Filter):
filter_object = f
else:
filter_object = Filter(operator).filter(f)
self._filter_dsl = filter_object | [
"def",
"_build_filtered_query",
"(",
"self",
",",
"f",
",",
"operator",
")",
":",
"self",
".",
"_filtered",
"=",
"True",
"if",
"isinstance",
"(",
"f",
",",
"Filter",
")",
":",
"filter_object",
"=",
"f",
"else",
":",
"filter_object",
"=",
"Filter",
"(",
... | Create the root of the filter tree | [
"Create",
"the",
"root",
"of",
"the",
"filter",
"tree"
] | 2e385c0a5d113af0e20be4d9393add2aabdd9565 | https://github.com/Yipit/pyeqs/blob/2e385c0a5d113af0e20be4d9393add2aabdd9565/pyeqs/query_builder.py#L41-L50 | train |
Yipit/pyeqs | pyeqs/query_builder.py | QueryBuilder.filter | def filter(self, f, operator="and"):
"""
Add a filter to the query
Takes a Filter object, or a filterable DSL object.
"""
if self._filtered:
self._filter_dsl.filter(f)
else:
self._build_filtered_query(f, operator)
return self | python | def filter(self, f, operator="and"):
"""
Add a filter to the query
Takes a Filter object, or a filterable DSL object.
"""
if self._filtered:
self._filter_dsl.filter(f)
else:
self._build_filtered_query(f, operator)
return self | [
"def",
"filter",
"(",
"self",
",",
"f",
",",
"operator",
"=",
"\"and\"",
")",
":",
"if",
"self",
".",
"_filtered",
":",
"self",
".",
"_filter_dsl",
".",
"filter",
"(",
"f",
")",
"else",
":",
"self",
".",
"_build_filtered_query",
"(",
"f",
",",
"opera... | Add a filter to the query
Takes a Filter object, or a filterable DSL object. | [
"Add",
"a",
"filter",
"to",
"the",
"query"
] | 2e385c0a5d113af0e20be4d9393add2aabdd9565 | https://github.com/Yipit/pyeqs/blob/2e385c0a5d113af0e20be4d9393add2aabdd9565/pyeqs/query_builder.py#L52-L62 | train |
brandjon/simplestruct | simplestruct/fields.py | TypedField.check | def check(self, inst, value):
"""Raise TypeError if value doesn't satisfy the constraints
for use on instance inst.
"""
if not (self.or_none and value is None):
if self.seq:
self.checktype_seq(value, self.kind,
unique=self.un... | python | def check(self, inst, value):
"""Raise TypeError if value doesn't satisfy the constraints
for use on instance inst.
"""
if not (self.or_none and value is None):
if self.seq:
self.checktype_seq(value, self.kind,
unique=self.un... | [
"def",
"check",
"(",
"self",
",",
"inst",
",",
"value",
")",
":",
"if",
"not",
"(",
"self",
".",
"or_none",
"and",
"value",
"is",
"None",
")",
":",
"if",
"self",
".",
"seq",
":",
"self",
".",
"checktype_seq",
"(",
"value",
",",
"self",
".",
"kind... | Raise TypeError if value doesn't satisfy the constraints
for use on instance inst. | [
"Raise",
"TypeError",
"if",
"value",
"doesn",
"t",
"satisfy",
"the",
"constraints",
"for",
"use",
"on",
"instance",
"inst",
"."
] | f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/fields.py#L49-L58 | train |
brandjon/simplestruct | simplestruct/fields.py | TypedField.normalize | def normalize(self, inst, value):
"""Return value or a normalized form of it for use on
instance inst.
"""
if (not (self.or_none and value is None) and
self.seq):
value = tuple(value)
return value | python | def normalize(self, inst, value):
"""Return value or a normalized form of it for use on
instance inst.
"""
if (not (self.or_none and value is None) and
self.seq):
value = tuple(value)
return value | [
"def",
"normalize",
"(",
"self",
",",
"inst",
",",
"value",
")",
":",
"if",
"(",
"not",
"(",
"self",
".",
"or_none",
"and",
"value",
"is",
"None",
")",
"and",
"self",
".",
"seq",
")",
":",
"value",
"=",
"tuple",
"(",
"value",
")",
"return",
"valu... | Return value or a normalized form of it for use on
instance inst. | [
"Return",
"value",
"or",
"a",
"normalized",
"form",
"of",
"it",
"for",
"use",
"on",
"instance",
"inst",
"."
] | f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/fields.py#L60-L67 | train |
VIVelev/PyDojoML | dojo/plot/decision.py | plot_decision_boundary | def plot_decision_boundary(model, X, y, step=0.1, figsize=(10, 8), alpha=0.4, size=20):
"""Plots the classification decision boundary of `model` on `X` with labels `y`.
Using numpy and matplotlib.
"""
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max(... | python | def plot_decision_boundary(model, X, y, step=0.1, figsize=(10, 8), alpha=0.4, size=20):
"""Plots the classification decision boundary of `model` on `X` with labels `y`.
Using numpy and matplotlib.
"""
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max(... | [
"def",
"plot_decision_boundary",
"(",
"model",
",",
"X",
",",
"y",
",",
"step",
"=",
"0.1",
",",
"figsize",
"=",
"(",
"10",
",",
"8",
")",
",",
"alpha",
"=",
"0.4",
",",
"size",
"=",
"20",
")",
":",
"x_min",
",",
"x_max",
"=",
"X",
"[",
":",
... | Plots the classification decision boundary of `model` on `X` with labels `y`.
Using numpy and matplotlib. | [
"Plots",
"the",
"classification",
"decision",
"boundary",
"of",
"model",
"on",
"X",
"with",
"labels",
"y",
".",
"Using",
"numpy",
"and",
"matplotlib",
"."
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/plot/decision.py#L9-L25 | train |
Xion/taipan | taipan/functional/__init__.py | ensure_argcount | def ensure_argcount(args, min_=None, max_=None):
"""Checks whether iterable of positional arguments satisfies conditions.
:param args: Iterable of positional arguments, received via ``*args``
:param min_: Minimum number of arguments
:param max_: Maximum number of arguments
:return: ``args`` if the... | python | def ensure_argcount(args, min_=None, max_=None):
"""Checks whether iterable of positional arguments satisfies conditions.
:param args: Iterable of positional arguments, received via ``*args``
:param min_: Minimum number of arguments
:param max_: Maximum number of arguments
:return: ``args`` if the... | [
"def",
"ensure_argcount",
"(",
"args",
",",
"min_",
"=",
"None",
",",
"max_",
"=",
"None",
")",
":",
"ensure_sequence",
"(",
"args",
")",
"has_min",
"=",
"min_",
"is",
"not",
"None",
"has_max",
"=",
"max_",
"is",
"not",
"None",
"if",
"not",
"(",
"has... | Checks whether iterable of positional arguments satisfies conditions.
:param args: Iterable of positional arguments, received via ``*args``
:param min_: Minimum number of arguments
:param max_: Maximum number of arguments
:return: ``args`` if the conditions are met
:raise TypeError: When condition... | [
"Checks",
"whether",
"iterable",
"of",
"positional",
"arguments",
"satisfies",
"conditions",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/__init__.py#L17-L45 | train |
Xion/taipan | taipan/functional/__init__.py | ensure_keyword_args | def ensure_keyword_args(kwargs, mandatory=(), optional=()):
"""Checks whether dictionary of keyword arguments satisfies conditions.
:param kwargs: Dictionary of keyword arguments, received via ``*kwargs``
:param mandatory: Iterable of mandatory argument names
:param optional: Iterable of optional argum... | python | def ensure_keyword_args(kwargs, mandatory=(), optional=()):
"""Checks whether dictionary of keyword arguments satisfies conditions.
:param kwargs: Dictionary of keyword arguments, received via ``*kwargs``
:param mandatory: Iterable of mandatory argument names
:param optional: Iterable of optional argum... | [
"def",
"ensure_keyword_args",
"(",
"kwargs",
",",
"mandatory",
"=",
"(",
")",
",",
"optional",
"=",
"(",
")",
")",
":",
"from",
"taipan",
".",
"strings",
"import",
"ensure_string",
"ensure_mapping",
"(",
"kwargs",
")",
"mandatory",
"=",
"list",
"(",
"map",... | Checks whether dictionary of keyword arguments satisfies conditions.
:param kwargs: Dictionary of keyword arguments, received via ``*kwargs``
:param mandatory: Iterable of mandatory argument names
:param optional: Iterable of optional argument names
:return: ``kwargs`` if the conditions are met:
... | [
"Checks",
"whether",
"dictionary",
"of",
"keyword",
"arguments",
"satisfies",
"conditions",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/__init__.py#L48-L86 | train |
intuition-io/insights | insights/plugins/hipchat.py | Bot._api_call | def _api_call(self, path, data={}, http_method=requests.get):
''' Process an http call against the hipchat api '''
log.info('performing api request', path=path)
response = http_method('/'.join([self.api_url, path]),
params={'auth_token': self.api_key},
... | python | def _api_call(self, path, data={}, http_method=requests.get):
''' Process an http call against the hipchat api '''
log.info('performing api request', path=path)
response = http_method('/'.join([self.api_url, path]),
params={'auth_token': self.api_key},
... | [
"def",
"_api_call",
"(",
"self",
",",
"path",
",",
"data",
"=",
"{",
"}",
",",
"http_method",
"=",
"requests",
".",
"get",
")",
":",
"log",
".",
"info",
"(",
"'performing api request'",
",",
"path",
"=",
"path",
")",
"response",
"=",
"http_method",
"("... | Process an http call against the hipchat api | [
"Process",
"an",
"http",
"call",
"against",
"the",
"hipchat",
"api"
] | a4eae53a1886164db96751d2b0964aa2acb7c2d7 | https://github.com/intuition-io/insights/blob/a4eae53a1886164db96751d2b0964aa2acb7c2d7/insights/plugins/hipchat.py#L43-L51 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.