repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L133-L148 | def _getNearestMappingIndexList(fromValList, toValList):
'''
Finds the indicies for data points that are closest to each other.
The inputs should be in relative time, scaled from 0 to 1
e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]
will output [0, 1, 1, 2]
'''
indexList = []
for... | [
"def",
"_getNearestMappingIndexList",
"(",
"fromValList",
",",
"toValList",
")",
":",
"indexList",
"=",
"[",
"]",
"for",
"fromTimestamp",
"in",
"fromValList",
":",
"smallestDiff",
"=",
"_getSmallestDifference",
"(",
"toValList",
",",
"fromTimestamp",
")",
"i",
"="... | Finds the indicies for data points that are closest to each other.
The inputs should be in relative time, scaled from 0 to 1
e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]
will output [0, 1, 1, 2] | [
"Finds",
"the",
"indicies",
"for",
"data",
"points",
"that",
"are",
"closest",
"to",
"each",
"other",
"."
] | python | train | 31.1875 |
zmqless/python-zeroless | zeroless/zeroless.py | https://github.com/zmqless/python-zeroless/blob/bff8ce0d12aae36537f41b57b2bd4ee087ed70e2/zeroless/zeroless.py#L189-L201 | def request(self):
"""
Returns a callable and an iterable respectively. Those can be used to
both transmit a message and/or iterate over incoming messages,
that were replied by a reply socket. Note that the iterable returns
as many parts as sent by repliers. Also, the sender func... | [
"def",
"request",
"(",
"self",
")",
":",
"sock",
"=",
"self",
".",
"__sock",
"(",
"zmq",
".",
"REQ",
")",
"return",
"self",
".",
"__send_function",
"(",
"sock",
")",
",",
"self",
".",
"__recv_generator",
"(",
"sock",
")"
] | Returns a callable and an iterable respectively. Those can be used to
both transmit a message and/or iterate over incoming messages,
that were replied by a reply socket. Note that the iterable returns
as many parts as sent by repliers. Also, the sender function has a
``print`` like signa... | [
"Returns",
"a",
"callable",
"and",
"an",
"iterable",
"respectively",
".",
"Those",
"can",
"be",
"used",
"to",
"both",
"transmit",
"a",
"message",
"and",
"/",
"or",
"iterate",
"over",
"incoming",
"messages",
"that",
"were",
"replied",
"by",
"a",
"reply",
"s... | python | train | 46.384615 |
jbrudvik/yahooscraper | yahooscraper/fantasy/team.py | https://github.com/jbrudvik/yahooscraper/blob/e880323fea0dd25f03410eea9d088760ba7c3528/yahooscraper/fantasy/team.py#L47-L57 | def date(page):
"""
Return the date, nicely-formatted
"""
soup = BeautifulSoup(page)
try:
page_date = soup.find('input', attrs={'name': 'date'})['value']
parsed_date = datetime.strptime(page_date, '%Y-%m-%d')
return parsed_date.strftime('%a, %b %d, %Y')
except:
re... | [
"def",
"date",
"(",
"page",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"page",
")",
"try",
":",
"page_date",
"=",
"soup",
".",
"find",
"(",
"'input'",
",",
"attrs",
"=",
"{",
"'name'",
":",
"'date'",
"}",
")",
"[",
"'value'",
"]",
"parsed_date",
... | Return the date, nicely-formatted | [
"Return",
"the",
"date",
"nicely",
"-",
"formatted"
] | python | train | 29 |
kristianfoerster/melodist | melodist/radiation.py | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L96-L177 | def potential_radiation(dates, lon, lat, timezone, terrain_slope=0, terrain_slope_azimuth=0,
cloud_fraction=0, split=False):
"""
Calculate potential shortwave radiation for a specific location and time.
This routine calculates global radiation as described in:
Liston, G. E... | [
"def",
"potential_radiation",
"(",
"dates",
",",
"lon",
",",
"lat",
",",
"timezone",
",",
"terrain_slope",
"=",
"0",
",",
"terrain_slope_azimuth",
"=",
"0",
",",
"cloud_fraction",
"=",
"0",
",",
"split",
"=",
"False",
")",
":",
"solar_constant",
"=",
"1367... | Calculate potential shortwave radiation for a specific location and time.
This routine calculates global radiation as described in:
Liston, G. E. and Elder, K. (2006): A Meteorological Distribution System for
High-Resolution Terrestrial Modeling (MicroMet), J. Hydrometeorol., 7, 217–234.
Correct... | [
"Calculate",
"potential",
"shortwave",
"radiation",
"for",
"a",
"specific",
"location",
"and",
"time",
".",
"This",
"routine",
"calculates",
"global",
"radiation",
"as",
"described",
"in",
":",
"Liston",
"G",
".",
"E",
".",
"and",
"Elder",
"K",
".",
"(",
"... | python | train | 44.804878 |
ldo/dbussy | dbussy.py | https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2187-L2197 | def send(self, message) :
"puts a message in the outgoing queue."
if not isinstance(message, Message) :
raise TypeError("message must be a Message")
#end if
serial = ct.c_uint()
if not dbus.dbus_connection_send(self._dbobj, message._dbobj, ct.byref(serial)) :
... | [
"def",
"send",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"Message",
")",
":",
"raise",
"TypeError",
"(",
"\"message must be a Message\"",
")",
"#end if",
"serial",
"=",
"ct",
".",
"c_uint",
"(",
")",
"if",
"no... | puts a message in the outgoing queue. | [
"puts",
"a",
"message",
"in",
"the",
"outgoing",
"queue",
"."
] | python | train | 37.454545 |
JoelBender/bacpypes | py25/bacpypes/capability.py | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/capability.py#L44-L57 | def _search_capability(self, base):
"""Given a class, return a list of all of the derived classes that
are themselves derived from Capability."""
if _debug: Collector._debug("_search_capability %r", base)
rslt = []
for cls in base.__bases__:
if issubclass(cls, Collec... | [
"def",
"_search_capability",
"(",
"self",
",",
"base",
")",
":",
"if",
"_debug",
":",
"Collector",
".",
"_debug",
"(",
"\"_search_capability %r\"",
",",
"base",
")",
"rslt",
"=",
"[",
"]",
"for",
"cls",
"in",
"base",
".",
"__bases__",
":",
"if",
"issubcl... | Given a class, return a list of all of the derived classes that
are themselves derived from Capability. | [
"Given",
"a",
"class",
"return",
"a",
"list",
"of",
"all",
"of",
"the",
"derived",
"classes",
"that",
"are",
"themselves",
"derived",
"from",
"Capability",
"."
] | python | train | 38.285714 |
zhanglab/psamm | psamm/formula.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/formula.py#L425-L510 | def _parse_formula(s):
"""Parse formula string."""
scanner = re.compile(r'''
(\s+) | # whitespace
(\(|\)) | # group
([A-Z][a-z]*) | # element
(\d+) | # number
([a-z]) | # variable
(\Z) | # end
(.) # error
... | [
"def",
"_parse_formula",
"(",
"s",
")",
":",
"scanner",
"=",
"re",
".",
"compile",
"(",
"r'''\n (\\s+) | # whitespace\n (\\(|\\)) | # group\n ([A-Z][a-z]*) | # element\n (\\d+) | # number\n ([a-z]) | # variable\n (\\Z) | ... | Parse formula string. | [
"Parse",
"formula",
"string",
"."
] | python | train | 34.174419 |
bitlabstudio/django-outlets | outlets/models.py | https://github.com/bitlabstudio/django-outlets/blob/eaecc1e8ef8fb48d6dc5886b321d9e3b0359b228/outlets/models.py#L14-L26 | def active(self):
"""Returns all outlets that are currently active and have sales."""
qs = self.get_queryset()
return qs.filter(
models.Q(
models.Q(start_date__isnull=True) |
models.Q(start_date__lte=now().date())
) &
models.Q(
... | [
"def",
"active",
"(",
"self",
")",
":",
"qs",
"=",
"self",
".",
"get_queryset",
"(",
")",
"return",
"qs",
".",
"filter",
"(",
"models",
".",
"Q",
"(",
"models",
".",
"Q",
"(",
"start_date__isnull",
"=",
"True",
")",
"|",
"models",
".",
"Q",
"(",
... | Returns all outlets that are currently active and have sales. | [
"Returns",
"all",
"outlets",
"that",
"are",
"currently",
"active",
"and",
"have",
"sales",
"."
] | python | train | 34.230769 |
pvlib/pvlib-python | pvlib/tracking.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/tracking.py#L153-L214 | def get_irradiance(self, surface_tilt, surface_azimuth,
solar_zenith, solar_azimuth, dni, ghi, dhi,
dni_extra=None, airmass=None, model='haydavies',
**kwargs):
"""
Uses the :func:`irradiance.get_total_irradiance` function to
ca... | [
"def",
"get_irradiance",
"(",
"self",
",",
"surface_tilt",
",",
"surface_azimuth",
",",
"solar_zenith",
",",
"solar_azimuth",
",",
"dni",
",",
"ghi",
",",
"dhi",
",",
"dni_extra",
"=",
"None",
",",
"airmass",
"=",
"None",
",",
"model",
"=",
"'haydavies'",
... | Uses the :func:`irradiance.get_total_irradiance` function to
calculate the plane of array irradiance components on a tilted
surface defined by the input data and ``self.albedo``.
For a given set of solar zenith and azimuth angles, the
surface tilt and azimuth parameters are typically de... | [
"Uses",
"the",
":",
"func",
":",
"irradiance",
".",
"get_total_irradiance",
"function",
"to",
"calculate",
"the",
"plane",
"of",
"array",
"irradiance",
"components",
"on",
"a",
"tilted",
"surface",
"defined",
"by",
"the",
"input",
"data",
"and",
"self",
".",
... | python | train | 39.225806 |
mariano/pyfire | pyfire/room.py | https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/room.py#L30-L41 | def get_stream(self, error_callback=None, live=True):
""" Get room stream to listen for messages.
Kwargs:
error_callback (func): Callback to call when an error occurred (parameters: exception)
live (bool): If True, issue a live stream, otherwise an offline stream
Return... | [
"def",
"get_stream",
"(",
"self",
",",
"error_callback",
"=",
"None",
",",
"live",
"=",
"True",
")",
":",
"self",
".",
"join",
"(",
")",
"return",
"Stream",
"(",
"self",
",",
"error_callback",
"=",
"error_callback",
",",
"live",
"=",
"live",
")"
] | Get room stream to listen for messages.
Kwargs:
error_callback (func): Callback to call when an error occurred (parameters: exception)
live (bool): If True, issue a live stream, otherwise an offline stream
Returns:
:class:`Stream`. Stream | [
"Get",
"room",
"stream",
"to",
"listen",
"for",
"messages",
"."
] | python | valid | 37.416667 |
saltstack/salt | salt/states/docker_image.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_image.py#L65-L375 | def present(name,
tag=None,
build=None,
load=None,
force=False,
insecure_registry=False,
client_timeout=salt.utils.docker.CLIENT_TIMEOUT,
dockerfile=None,
sls=None,
base='opensuse/python',
saltenv='ba... | [
"def",
"present",
"(",
"name",
",",
"tag",
"=",
"None",
",",
"build",
"=",
"None",
",",
"load",
"=",
"None",
",",
"force",
"=",
"False",
",",
"insecure_registry",
"=",
"False",
",",
"client_timeout",
"=",
"salt",
".",
"utils",
".",
"docker",
".",
"CL... | .. versionchanged:: 2018.3.0
The ``tag`` argument has been added. It is now required unless pulling
from a registry.
Ensure that an image is present. The image can either be pulled from a
Docker registry, built from a Dockerfile, loaded from a saved image, or
built by running SLS files agai... | [
"..",
"versionchanged",
"::",
"2018",
".",
"3",
".",
"0",
"The",
"tag",
"argument",
"has",
"been",
"added",
".",
"It",
"is",
"now",
"required",
"unless",
"pulling",
"from",
"a",
"registry",
"."
] | python | train | 34.311897 |
cherrypy/cheroot | cheroot/makefile.py | https://github.com/cherrypy/cheroot/blob/2af3b1798d66da697957480d3a8b4831a405770b/cheroot/makefile.py#L84-L88 | def send(self, data):
"""Send some part of message to the socket."""
bytes_sent = self._sock.send(extract_bytes(data))
self.bytes_written += bytes_sent
return bytes_sent | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"bytes_sent",
"=",
"self",
".",
"_sock",
".",
"send",
"(",
"extract_bytes",
"(",
"data",
")",
")",
"self",
".",
"bytes_written",
"+=",
"bytes_sent",
"return",
"bytes_sent"
] | Send some part of message to the socket. | [
"Send",
"some",
"part",
"of",
"message",
"to",
"the",
"socket",
"."
] | python | train | 39.4 |
googleads/googleads-python-lib | examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py#L174-L238 | def _UpdateCampaignDSASetting(client, campaign_id, feed_id):
"""Updates the campaign DSA setting to DSA pagefeeds.
Args:
client: an AdWordsClient instance.
campaign_id: a str Campaign ID.
feed_id: a str page Feed ID.
Raises:
ValueError: If the given campaign is found not to be a dynamic search a... | [
"def",
"_UpdateCampaignDSASetting",
"(",
"client",
",",
"campaign_id",
",",
"feed_id",
")",
":",
"# Get the CampaignService.",
"campaign_service",
"=",
"client",
".",
"GetService",
"(",
"'CampaignService'",
",",
"version",
"=",
"'v201809'",
")",
"selector",
"=",
"{"... | Updates the campaign DSA setting to DSA pagefeeds.
Args:
client: an AdWordsClient instance.
campaign_id: a str Campaign ID.
feed_id: a str page Feed ID.
Raises:
ValueError: If the given campaign is found not to be a dynamic search ad
campaign. | [
"Updates",
"the",
"campaign",
"DSA",
"setting",
"to",
"DSA",
"pagefeeds",
"."
] | python | train | 25 |
numba/llvmlite | llvmlite/ir/builder.py | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L880-L888 | def insert_element(self, vector, value, idx, name=''):
"""
Returns vector with vector[idx] replaced by value.
The result is undefined if the idx is larger or equal the vector length.
"""
instr = instructions.InsertElement(self.block, vector, value, idx,
... | [
"def",
"insert_element",
"(",
"self",
",",
"vector",
",",
"value",
",",
"idx",
",",
"name",
"=",
"''",
")",
":",
"instr",
"=",
"instructions",
".",
"InsertElement",
"(",
"self",
".",
"block",
",",
"vector",
",",
"value",
",",
"idx",
",",
"name",
"=",... | Returns vector with vector[idx] replaced by value.
The result is undefined if the idx is larger or equal the vector length. | [
"Returns",
"vector",
"with",
"vector",
"[",
"idx",
"]",
"replaced",
"by",
"value",
".",
"The",
"result",
"is",
"undefined",
"if",
"the",
"idx",
"is",
"larger",
"or",
"equal",
"the",
"vector",
"length",
"."
] | python | train | 43.111111 |
allenai/allennlp | allennlp/training/metric_tracker.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L97-L113 | def add_metric(self, metric: float) -> None:
"""
Record a new value of the metric and update the various things that depend on it.
"""
new_best = ((self._best_so_far is None) or
(self._should_decrease and metric < self._best_so_far) or
(not self._s... | [
"def",
"add_metric",
"(",
"self",
",",
"metric",
":",
"float",
")",
"->",
"None",
":",
"new_best",
"=",
"(",
"(",
"self",
".",
"_best_so_far",
"is",
"None",
")",
"or",
"(",
"self",
".",
"_should_decrease",
"and",
"metric",
"<",
"self",
".",
"_best_so_f... | Record a new value of the metric and update the various things that depend on it. | [
"Record",
"a",
"new",
"value",
"of",
"the",
"metric",
"and",
"update",
"the",
"various",
"things",
"that",
"depend",
"on",
"it",
"."
] | python | train | 40.411765 |
leancloud/python-sdk | leancloud/query.py | https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/query.py#L674-L684 | def select(self, *keys):
"""
指定查询返回结果中只包含某些字段。可以重复调用,每次调用的包含内容都将会被返回。
:param keys: 包含字段名
:rtype: Query
"""
if len(keys) == 1 and isinstance(keys[0], (list, tuple)):
keys = keys[0]
self._select += keys
return self | [
"def",
"select",
"(",
"self",
",",
"*",
"keys",
")",
":",
"if",
"len",
"(",
"keys",
")",
"==",
"1",
"and",
"isinstance",
"(",
"keys",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"keys",
"=",
"keys",
"[",
"0",
"]",
"self",
... | 指定查询返回结果中只包含某些字段。可以重复调用,每次调用的包含内容都将会被返回。
:param keys: 包含字段名
:rtype: Query | [
"指定查询返回结果中只包含某些字段。可以重复调用,每次调用的包含内容都将会被返回。"
] | python | train | 25.363636 |
google/grumpy | third_party/stdlib/difflib.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L1888-L1914 | def _line_wrapper(self,diffs):
"""Returns iterator that splits (wraps) mdiff text lines"""
# pull from/to data and flags from mdiff iterator
for fromdata,todata,flag in diffs:
# check for context separators and pass them through
if flag is None:
yield fro... | [
"def",
"_line_wrapper",
"(",
"self",
",",
"diffs",
")",
":",
"# pull from/to data and flags from mdiff iterator",
"for",
"fromdata",
",",
"todata",
",",
"flag",
"in",
"diffs",
":",
"# check for context separators and pass them through",
"if",
"flag",
"is",
"None",
":",
... | Returns iterator that splits (wraps) mdiff text lines | [
"Returns",
"iterator",
"that",
"splits",
"(",
"wraps",
")",
"mdiff",
"text",
"lines"
] | python | valid | 41.814815 |
pypa/pipenv | pipenv/vendor/distlib/_backport/sysconfig.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L388-L416 | def parse_config_h(fp, vars=None):
"""Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
if vars is None:
vars = {}
define_rx = re.compile("#de... | [
"def",
"parse_config_h",
"(",
"fp",
",",
"vars",
"=",
"None",
")",
":",
"if",
"vars",
"is",
"None",
":",
"vars",
"=",
"{",
"}",
"define_rx",
"=",
"re",
".",
"compile",
"(",
"\"#define ([A-Z][A-Za-z0-9_]+) (.*)\\n\"",
")",
"undef_rx",
"=",
"re",
".",
"com... | Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary. | [
"Parse",
"a",
"config",
".",
"h",
"-",
"style",
"file",
"."
] | python | train | 27.689655 |
rgs1/zk_shell | zk_shell/shell.py | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/shell.py#L692-L720 | def do_tree(self, params):
"""
\x1b[1mNAME\x1b[0m
tree - Print the tree under a given path
\x1b[1mSYNOPSIS\x1b[0m
tree [path] [max_depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
... | [
"def",
"do_tree",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"show_output",
"(",
"\".\"",
")",
"for",
"child",
",",
"level",
"in",
"self",
".",
"_zk",
".",
"tree",
"(",
"params",
".",
"path",
",",
"params",
".",
"max_depth",
")",
":",
"self... | \x1b[1mNAME\x1b[0m
tree - Print the tree under a given path
\x1b[1mSYNOPSIS\x1b[0m
tree [path] [max_depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
> tree
.
├── zo... | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"tree",
"-",
"Print",
"the",
"tree",
"under",
"a",
"given",
"path"
] | python | train | 22.344828 |
googleapis/oauth2client | oauth2client/_openssl_crypt.py | https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_openssl_crypt.py#L87-L97 | def sign(self, message):
"""Signs a message.
Args:
message: bytes, Message to be signed.
Returns:
string, The signature of the message for the given key.
"""
message = _helpers._to_bytes(message, encoding='utf-8')
return crypto.sign(self._key, me... | [
"def",
"sign",
"(",
"self",
",",
"message",
")",
":",
"message",
"=",
"_helpers",
".",
"_to_bytes",
"(",
"message",
",",
"encoding",
"=",
"'utf-8'",
")",
"return",
"crypto",
".",
"sign",
"(",
"self",
".",
"_key",
",",
"message",
",",
"'sha256'",
")"
] | Signs a message.
Args:
message: bytes, Message to be signed.
Returns:
string, The signature of the message for the given key. | [
"Signs",
"a",
"message",
"."
] | python | valid | 29.636364 |
scanny/python-pptx | pptx/chart/datalabel.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/datalabel.py#L174-L187 | def has_text_frame(self):
"""
Return |True| if this data label has a text frame (implying it has
custom data label text), and |False| otherwise. Assigning |True|
causes a text frame to be added if not already present. Assigning
|False| causes any existing text frame to be removed... | [
"def",
"has_text_frame",
"(",
"self",
")",
":",
"dLbl",
"=",
"self",
".",
"_dLbl",
"if",
"dLbl",
"is",
"None",
":",
"return",
"False",
"if",
"dLbl",
".",
"xpath",
"(",
"'c:tx/c:rich'",
")",
":",
"return",
"True",
"return",
"False"
] | Return |True| if this data label has a text frame (implying it has
custom data label text), and |False| otherwise. Assigning |True|
causes a text frame to be added if not already present. Assigning
|False| causes any existing text frame to be removed along with any
text contained in the ... | [
"Return",
"|True|",
"if",
"this",
"data",
"label",
"has",
"a",
"text",
"frame",
"(",
"implying",
"it",
"has",
"custom",
"data",
"label",
"text",
")",
"and",
"|False|",
"otherwise",
".",
"Assigning",
"|True|",
"causes",
"a",
"text",
"frame",
"to",
"be",
"... | python | train | 38.214286 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/utils/Crypt.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/utils/Crypt.py#L20-L43 | def gen_random_key(size=32):
"""
Generate a cryptographically-secure random key. This is done by using
Python 2.4's os.urandom, or PyCrypto.
"""
import os
if hasattr(os, "urandom"): # Python 2.4+
return os.urandom(size)
# Try using PyCrypto if available
try:
from Crypto.... | [
"def",
"gen_random_key",
"(",
"size",
"=",
"32",
")",
":",
"import",
"os",
"if",
"hasattr",
"(",
"os",
",",
"\"urandom\"",
")",
":",
"# Python 2.4+",
"return",
"os",
".",
"urandom",
"(",
"size",
")",
"# Try using PyCrypto if available",
"try",
":",
"from",
... | Generate a cryptographically-secure random key. This is done by using
Python 2.4's os.urandom, or PyCrypto. | [
"Generate",
"a",
"cryptographically",
"-",
"secure",
"random",
"key",
".",
"This",
"is",
"done",
"by",
"using",
"Python",
"2",
".",
"4",
"s",
"os",
".",
"urandom",
"or",
"PyCrypto",
"."
] | python | train | 33.083333 |
PredixDev/predixpy | predix/admin/cf/services.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/services.py#L82-L95 | def get_service_key(self, service_name, key_name):
"""
Returns the service key details.
Similar to `cf service-key`.
"""
for key in self._get_service_keys(service_name)['resources']:
if key_name == key['entity']['name']:
guid = key['metadata']['guid']... | [
"def",
"get_service_key",
"(",
"self",
",",
"service_name",
",",
"key_name",
")",
":",
"for",
"key",
"in",
"self",
".",
"_get_service_keys",
"(",
"service_name",
")",
"[",
"'resources'",
"]",
":",
"if",
"key_name",
"==",
"key",
"[",
"'entity'",
"]",
"[",
... | Returns the service key details.
Similar to `cf service-key`. | [
"Returns",
"the",
"service",
"key",
"details",
"."
] | python | train | 30.214286 |
django-fluent/django-fluent-blogs | fluent_blogs/pagetypes/blogpage/models.py | https://github.com/django-fluent/django-fluent-blogs/blob/86b148549a010eaca9a2ea987fe43be250e06c50/fluent_blogs/pagetypes/blogpage/models.py#L31-L41 | def get_entry_url(self, entry):
"""
Return the URL of a blog entry, relative to this page.
"""
# It could be possible this page is fetched as fallback, while the 'entry' does have a translation.
# - Currently django-fluent-pages 1.0b3 `Page.objects.get_for_path()` assigns the lan... | [
"def",
"get_entry_url",
"(",
"self",
",",
"entry",
")",
":",
"# It could be possible this page is fetched as fallback, while the 'entry' does have a translation.",
"# - Currently django-fluent-pages 1.0b3 `Page.objects.get_for_path()` assigns the language of retrieval",
"# as current object la... | Return the URL of a blog entry, relative to this page. | [
"Return",
"the",
"URL",
"of",
"a",
"blog",
"entry",
"relative",
"to",
"this",
"page",
"."
] | python | train | 69.272727 |
proteanhq/protean | src/protean/core/entity.py | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L443-L489 | def create(cls, *args, **kwargs) -> 'Entity':
"""Create a new record in the repository.
Also performs unique validations before creating the entity
:param args: positional arguments for the entity
:param kwargs: keyword arguments for the entity
"""
logger.debug(
... | [
"def",
"create",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"'Entity'",
":",
"logger",
".",
"debug",
"(",
"f'Creating new `{cls.__name__}` object using data {kwargs}'",
")",
"model_cls",
"=",
"repo_factory",
".",
"get_model",
"(",
"cls",
... | Create a new record in the repository.
Also performs unique validations before creating the entity
:param args: positional arguments for the entity
:param kwargs: keyword arguments for the entity | [
"Create",
"a",
"new",
"record",
"in",
"the",
"repository",
"."
] | python | train | 34.468085 |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L333-L360 | def getArticles(self,
page=1,
count=100,
sortBy = "rel",
sortByAsc = False,
returnInfo=ReturnInfo()):
"""
return a list of articles that match the topic page
@param page: which page of the results to return (default:... | [
"def",
"getArticles",
"(",
"self",
",",
"page",
"=",
"1",
",",
"count",
"=",
"100",
",",
"sortBy",
"=",
"\"rel\"",
",",
"sortByAsc",
"=",
"False",
",",
"returnInfo",
"=",
"ReturnInfo",
"(",
")",
")",
":",
"assert",
"page",
">=",
"1",
"assert",
"count... | return a list of articles that match the topic page
@param page: which page of the results to return (default: 1)
@param count: number of articles to return (default: 100)
@param sortBy: how are articles sorted. Options: id (internal id), date (publishing date), cosSim (closeness to the event ce... | [
"return",
"a",
"list",
"of",
"articles",
"that",
"match",
"the",
"topic",
"page"
] | python | train | 58 |
CxAalto/gtfspy | gtfspy/routing/node_profile_simple.py | https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/node_profile_simple.py#L18-L44 | def update_pareto_optimal_tuples(self, new_pareto_tuple):
"""
# this function should be optimized
Parameters
----------
new_pareto_tuple: LabelTimeSimple
Returns
-------
added: bool
whether new_pareto_tuple was added to the set of pareto-opti... | [
"def",
"update_pareto_optimal_tuples",
"(",
"self",
",",
"new_pareto_tuple",
")",
":",
"if",
"new_pareto_tuple",
".",
"duration",
"(",
")",
">",
"self",
".",
"_walk_to_target_duration",
":",
"direct_walk_label",
"=",
"self",
".",
"_label_class",
".",
"direct_walk_la... | # this function should be optimized
Parameters
----------
new_pareto_tuple: LabelTimeSimple
Returns
-------
added: bool
whether new_pareto_tuple was added to the set of pareto-optimal tuples | [
"#",
"this",
"function",
"should",
"be",
"optimized"
] | python | valid | 41.777778 |
kgori/treeCl | treeCl/collection.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/collection.py#L868-L875 | def get_changed(self, p1, p2):
"""
Return the loci that are in clusters that have changed between
partitions p1 and p2
"""
if p1 is None or p2 is None:
return list(range(len(self.insts)))
return set(flatten_list(set(p1) - set(p2))) | [
"def",
"get_changed",
"(",
"self",
",",
"p1",
",",
"p2",
")",
":",
"if",
"p1",
"is",
"None",
"or",
"p2",
"is",
"None",
":",
"return",
"list",
"(",
"range",
"(",
"len",
"(",
"self",
".",
"insts",
")",
")",
")",
"return",
"set",
"(",
"flatten_list"... | Return the loci that are in clusters that have changed between
partitions p1 and p2 | [
"Return",
"the",
"loci",
"that",
"are",
"in",
"clusters",
"that",
"have",
"changed",
"between",
"partitions",
"p1",
"and",
"p2"
] | python | train | 35.75 |
pypyr/pypyr-cli | pypyr/parser/json.py | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/parser/json.py#L10-L22 | def get_parsed_context(context_arg):
"""Parse input context string and returns context as dictionary."""
if not context_arg:
logger.debug("pipeline invoked without context arg set. For "
"this json parser you're looking for something "
"like: "
... | [
"def",
"get_parsed_context",
"(",
"context_arg",
")",
":",
"if",
"not",
"context_arg",
":",
"logger",
".",
"debug",
"(",
"\"pipeline invoked without context arg set. For \"",
"\"this json parser you're looking for something \"",
"\"like: \"",
"\"pypyr pipelinename '{\\\"key1\\\":\\... | Parse input context string and returns context as dictionary. | [
"Parse",
"input",
"context",
"string",
"and",
"returns",
"context",
"as",
"dictionary",
"."
] | python | train | 41.461538 |
rosenbrockc/fortpy | fortpy/scripts/analyze.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/scripts/analyze.py#L594-L610 | def do_rmdep(self, args):
"""Removes dependent variables currently set for plotting/tabulating etc."""
for arg in args.split():
if arg in self.curargs["dependents"]:
self.curargs["dependents"].remove(arg)
if arg in self.curargs["plottypes"]:
del se... | [
"def",
"do_rmdep",
"(",
"self",
",",
"args",
")",
":",
"for",
"arg",
"in",
"args",
".",
"split",
"(",
")",
":",
"if",
"arg",
"in",
"self",
".",
"curargs",
"[",
"\"dependents\"",
"]",
":",
"self",
".",
"curargs",
"[",
"\"dependents\"",
"]",
".",
"re... | Removes dependent variables currently set for plotting/tabulating etc. | [
"Removes",
"dependent",
"variables",
"currently",
"set",
"for",
"plotting",
"/",
"tabulating",
"etc",
"."
] | python | train | 47.529412 |
chaoss/grimoirelab-perceval | perceval/backends/core/jenkins.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/jenkins.py#L230-L241 | def get_builds(self, job_name):
""" Retrieve all builds from a job"""
if self.blacklist_jobs and job_name in self.blacklist_jobs:
logger.warning("Not getting blacklisted job: %s", job_name)
return
payload = {'depth': self.detail_depth}
url_build = urijoin(self.b... | [
"def",
"get_builds",
"(",
"self",
",",
"job_name",
")",
":",
"if",
"self",
".",
"blacklist_jobs",
"and",
"job_name",
"in",
"self",
".",
"blacklist_jobs",
":",
"logger",
".",
"warning",
"(",
"\"Not getting blacklisted job: %s\"",
",",
"job_name",
")",
"return",
... | Retrieve all builds from a job | [
"Retrieve",
"all",
"builds",
"from",
"a",
"job"
] | python | test | 36.416667 |
gwww/elkm1 | elkm1_lib/message.py | https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/message.py#L74-L85 | def _cr_decode(self, msg):
"""CR: Custom values"""
if int(msg[4:6]) > 0:
index = int(msg[4:6])-1
return {'values': [self._cr_one_custom_value_decode(index, msg[6:12])]}
else:
part = 6
ret = []
for i in range(Max.SETTINGS.value):
... | [
"def",
"_cr_decode",
"(",
"self",
",",
"msg",
")",
":",
"if",
"int",
"(",
"msg",
"[",
"4",
":",
"6",
"]",
")",
">",
"0",
":",
"index",
"=",
"int",
"(",
"msg",
"[",
"4",
":",
"6",
"]",
")",
"-",
"1",
"return",
"{",
"'values'",
":",
"[",
"s... | CR: Custom values | [
"CR",
":",
"Custom",
"values"
] | python | train | 37 |
upsight/doctor | doctor/schema.py | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L138-L150 | def resolve(self, ref, document=None):
"""Resolve a ref within the schema.
This is just a convenience method, since RefResolver returns both a URI
and the resolved value, and we usually just need the resolved value.
:param str ref: URI to resolve.
:param dict document: Optional... | [
"def",
"resolve",
"(",
"self",
",",
"ref",
",",
"document",
"=",
"None",
")",
":",
"_",
",",
"resolved",
"=",
"self",
".",
"resolver",
".",
"resolve",
"(",
"ref",
",",
"document",
"=",
"document",
")",
"return",
"resolved"
] | Resolve a ref within the schema.
This is just a convenience method, since RefResolver returns both a URI
and the resolved value, and we usually just need the resolved value.
:param str ref: URI to resolve.
:param dict document: Optional schema in which to resolve the URI.
:retu... | [
"Resolve",
"a",
"ref",
"within",
"the",
"schema",
"."
] | python | train | 43.461538 |
mpg-age-bioinformatics/AGEpy | AGEpy/gtf.py | https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/gtf.py#L42-L69 | def attributesGTF(inGTF):
"""
List the type of attributes in a the attribute section of a GTF file
:param inGTF: GTF dataframe to be analysed
:returns: a list of attributes present in the attribute section
"""
df=pd.DataFrame(inGTF['attribute'].str.split(";").tolist())
desc=[]
for i in... | [
"def",
"attributesGTF",
"(",
"inGTF",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"inGTF",
"[",
"'attribute'",
"]",
".",
"str",
".",
"split",
"(",
"\";\"",
")",
".",
"tolist",
"(",
")",
")",
"desc",
"=",
"[",
"]",
"for",
"i",
"in",
"df",
... | List the type of attributes in a the attribute section of a GTF file
:param inGTF: GTF dataframe to be analysed
:returns: a list of attributes present in the attribute section | [
"List",
"the",
"type",
"of",
"attributes",
"in",
"a",
"the",
"attribute",
"section",
"of",
"a",
"GTF",
"file"
] | python | train | 28 |
singularityhub/sregistry-cli | sregistry/client/backend.py | https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/client/backend.py#L94-L104 | def status(backend):
'''print the status for all or one of the backends.
'''
print('[backend status]')
settings = read_client_secrets()
print('There are %s clients found in secrets.' %len(settings))
if 'SREGISTRY_CLIENT' in settings:
print('active: %s' %settings['SREGISTRY_CLIENT'])
... | [
"def",
"status",
"(",
"backend",
")",
":",
"print",
"(",
"'[backend status]'",
")",
"settings",
"=",
"read_client_secrets",
"(",
")",
"print",
"(",
"'There are %s clients found in secrets.'",
"%",
"len",
"(",
"settings",
")",
")",
"if",
"'SREGISTRY_CLIENT'",
"in",... | print the status for all or one of the backends. | [
"print",
"the",
"status",
"for",
"all",
"or",
"one",
"of",
"the",
"backends",
"."
] | python | test | 35.636364 |
bartTC/django-attachments | attachments/models.py | https://github.com/bartTC/django-attachments/blob/012b7168f9342e07683a54ceab57696e0072962e/attachments/models.py#L13-L20 | def attachment_upload(instance, filename):
"""Stores the attachment in a "per module/appname/primary key" folder"""
return 'attachments/{app}_{model}/{pk}/{filename}'.format(
app=instance.content_object._meta.app_label,
model=instance.content_object._meta.object_name.lower(),
pk=instance... | [
"def",
"attachment_upload",
"(",
"instance",
",",
"filename",
")",
":",
"return",
"'attachments/{app}_{model}/{pk}/{filename}'",
".",
"format",
"(",
"app",
"=",
"instance",
".",
"content_object",
".",
"_meta",
".",
"app_label",
",",
"model",
"=",
"instance",
".",
... | Stores the attachment in a "per module/appname/primary key" folder | [
"Stores",
"the",
"attachment",
"in",
"a",
"per",
"module",
"/",
"appname",
"/",
"primary",
"key",
"folder"
] | python | train | 45.625 |
saltstack/salt | salt/modules/boto_ec2.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L428-L485 | def assign_private_ip_addresses(network_interface_name=None, network_interface_id=None,
private_ip_addresses=None, secondary_private_ip_address_count=None,
allow_reassignment=False, region=None, key=None,
keyid=None, profile... | [
"def",
"assign_private_ip_addresses",
"(",
"network_interface_name",
"=",
"None",
",",
"network_interface_id",
"=",
"None",
",",
"private_ip_addresses",
"=",
"None",
",",
"secondary_private_ip_address_count",
"=",
"None",
",",
"allow_reassignment",
"=",
"False",
",",
"r... | Assigns one or more secondary private IP addresses to a network interface.
network_interface_id
(string) - ID of the network interface to associate the IP with (exclusive with 'network_interface_name')
network_interface_name
(string) - Name of the network interface to associate the IP with (exc... | [
"Assigns",
"one",
"or",
"more",
"secondary",
"private",
"IP",
"addresses",
"to",
"a",
"network",
"interface",
"."
] | python | train | 49.965517 |
hirokiky/uiro | uiro/view.py | https://github.com/hirokiky/uiro/blob/8436976b21ac9b0eac4243768f5ada12479b9e00/uiro/view.py#L14-L22 | def get_base_wrappers(method='get', template_name='', predicates=(), wrappers=()):
""" basic View Wrappers used by view_config.
"""
wrappers += (preserve_view(MethodPredicate(method), *predicates),)
if template_name:
wrappers += (render_template(template_name),)
return wrappers | [
"def",
"get_base_wrappers",
"(",
"method",
"=",
"'get'",
",",
"template_name",
"=",
"''",
",",
"predicates",
"=",
"(",
")",
",",
"wrappers",
"=",
"(",
")",
")",
":",
"wrappers",
"+=",
"(",
"preserve_view",
"(",
"MethodPredicate",
"(",
"method",
")",
",",... | basic View Wrappers used by view_config. | [
"basic",
"View",
"Wrappers",
"used",
"by",
"view_config",
"."
] | python | train | 33.333333 |
maxalbert/tohu | tohu/v2/custom_generator.py | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L39-L59 | def set_item_class_name(cls_obj):
"""
Return the first part of the class name of this custom generator.
This will be used for the class name of the items produced by this
generator.
Examples:
FoobarGenerator -> Foobar
QuuxGenerator -> Quux
"""
if '__tohu__items__name__' in... | [
"def",
"set_item_class_name",
"(",
"cls_obj",
")",
":",
"if",
"'__tohu__items__name__'",
"in",
"cls_obj",
".",
"__dict__",
":",
"logger",
".",
"debug",
"(",
"f\"Using item class name '{cls_obj.__tohu_items_name__}' (derived from attribute '__tohu_items_name__')\"",
")",
"else",... | Return the first part of the class name of this custom generator.
This will be used for the class name of the items produced by this
generator.
Examples:
FoobarGenerator -> Foobar
QuuxGenerator -> Quux | [
"Return",
"the",
"first",
"part",
"of",
"the",
"class",
"name",
"of",
"this",
"custom",
"generator",
".",
"This",
"will",
"be",
"used",
"for",
"the",
"class",
"name",
"of",
"the",
"items",
"produced",
"by",
"this",
"generator",
"."
] | python | train | 48.857143 |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/directory.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L1631-L1645 | def json_2_nic(json_obj):
"""
transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 NIC object
"""
LOGGER.debug("NIC.json_2_nic")
return NIC(nic_id=json_obj['nicID'],
... | [
"def",
"json_2_nic",
"(",
"json_obj",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"NIC.json_2_nic\"",
")",
"return",
"NIC",
"(",
"nic_id",
"=",
"json_obj",
"[",
"'nicID'",
"]",
",",
"mac_address",
"=",
"json_obj",
"[",
"'nicMacAddress'",
"]",
",",
"name",
"="... | transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 NIC object | [
"transform",
"JSON",
"obj",
"coming",
"from",
"Ariane",
"to",
"ariane_clip3",
"object",
":",
"param",
"json_obj",
":",
"the",
"JSON",
"obj",
"coming",
"from",
"Ariane",
":",
"return",
":",
"ariane_clip3",
"NIC",
"object"
] | python | train | 43 |
gabstopper/smc-python | smc/examples/ospf_routing.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ospf_routing.py#L25-L57 | def create_ospf_area_with_message_digest_auth():
"""
If you require message-digest authentication for your OSPFArea, you must
create an OSPF key chain configuration.
"""
OSPFKeyChain.create(name='secure-keychain',
key_chain_entry=[{'key': 'fookey',
... | [
"def",
"create_ospf_area_with_message_digest_auth",
"(",
")",
":",
"OSPFKeyChain",
".",
"create",
"(",
"name",
"=",
"'secure-keychain'",
",",
"key_chain_entry",
"=",
"[",
"{",
"'key'",
":",
"'fookey'",
",",
"'key_id'",
":",
"10",
",",
"'send_key'",
":",
"True",
... | If you require message-digest authentication for your OSPFArea, you must
create an OSPF key chain configuration. | [
"If",
"you",
"require",
"message",
"-",
"digest",
"authentication",
"for",
"your",
"OSPFArea",
"you",
"must",
"create",
"an",
"OSPF",
"key",
"chain",
"configuration",
"."
] | python | train | 44.121212 |
bspaans/python-mingus | mingus/midi/sequencer.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L219-L294 | def play_Bars(self, bars, channels, bpm=120):
"""Play several bars (a list of Bar objects) at the same time.
A list of channels should also be provided. The tempo can be changed
by providing one or more of the NoteContainers with a bpm argument.
"""
self.notify_listeners(self.MS... | [
"def",
"play_Bars",
"(",
"self",
",",
"bars",
",",
"channels",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_BARS",
",",
"{",
"'bars'",
":",
"bars",
",",
"'channels'",
":",
"channels",
",",
"'bpm'",
":",... | Play several bars (a list of Bar objects) at the same time.
A list of channels should also be provided. The tempo can be changed
by providing one or more of the NoteContainers with a bpm argument. | [
"Play",
"several",
"bars",
"(",
"a",
"list",
"of",
"Bar",
"objects",
")",
"at",
"the",
"same",
"time",
"."
] | python | train | 44.789474 |
awslabs/sockeye | sockeye/loss.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/loss.py#L108-L116 | def get_loss(self, logits: mx.sym.Symbol, labels: mx.sym.Symbol) -> mx.sym.Symbol:
"""
Returns loss and softmax output symbols given logits and integer-coded labels.
:param logits: Shape: (batch_size * target_seq_len, target_vocab_size).
:param labels: Shape: (batch_size * target_seq_le... | [
"def",
"get_loss",
"(",
"self",
",",
"logits",
":",
"mx",
".",
"sym",
".",
"Symbol",
",",
"labels",
":",
"mx",
".",
"sym",
".",
"Symbol",
")",
"->",
"mx",
".",
"sym",
".",
"Symbol",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Returns loss and softmax output symbols given logits and integer-coded labels.
:param logits: Shape: (batch_size * target_seq_len, target_vocab_size).
:param labels: Shape: (batch_size * target_seq_len,).
:return: Loss symbol. | [
"Returns",
"loss",
"and",
"softmax",
"output",
"symbols",
"given",
"logits",
"and",
"integer",
"-",
"coded",
"labels",
"."
] | python | train | 43.777778 |
ianmiell/shutit | shutit_pexpect.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L2938-L2951 | def quick_send(self, send, echo=None, loglevel=logging.INFO):
"""Quick and dirty send that ignores background tasks. Intended for internal use.
"""
shutit = self.shutit
shutit.log('Quick send: ' + send, level=loglevel)
res = self.sendline(ShutItSendSpec(self,
send=send,
... | [
"def",
"quick_send",
"(",
"self",
",",
"send",
",",
"echo",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"INFO",
")",
":",
"shutit",
"=",
"self",
".",
"shutit",
"shutit",
".",
"log",
"(",
"'Quick send: '",
"+",
"send",
",",
"level",
"=",
"logle... | Quick and dirty send that ignores background tasks. Intended for internal use. | [
"Quick",
"and",
"dirty",
"send",
"that",
"ignores",
"background",
"tasks",
".",
"Intended",
"for",
"internal",
"use",
"."
] | python | train | 46.357143 |
automl/HpBandSter | hpbandster/core/nameserver.py | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/nameserver.py#L82-L92 | def shutdown(self):
"""
clean shutdown of the nameserver and the config file (if written)
"""
if not self.pyro_ns is None:
self.pyro_ns.shutdown()
self.pyro_ns = None
if not self.conf_fn is None:
os.remove(self.conf_fn)
self.conf_fn = None | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"pyro_ns",
"is",
"None",
":",
"self",
".",
"pyro_ns",
".",
"shutdown",
"(",
")",
"self",
".",
"pyro_ns",
"=",
"None",
"if",
"not",
"self",
".",
"conf_fn",
"is",
"None",
":",
"os",
... | clean shutdown of the nameserver and the config file (if written) | [
"clean",
"shutdown",
"of",
"the",
"nameserver",
"and",
"the",
"config",
"file",
"(",
"if",
"written",
")"
] | python | train | 23.181818 |
anjos/rrbob | rr/analysis.py | https://github.com/anjos/rrbob/blob/d32d35bab2aa2698d3caa923fd02afb6d67f3235/rr/analysis.py#L6-L23 | def CER(prediction, true_labels):
"""
Calculates the classification error rate for an N-class classification problem
Parameters:
prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your
prediction
true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray`
containing the ground t... | [
"def",
"CER",
"(",
"prediction",
",",
"true_labels",
")",
":",
"errors",
"=",
"(",
"prediction",
"!=",
"true_labels",
")",
".",
"sum",
"(",
")",
"return",
"float",
"(",
"errors",
")",
"/",
"len",
"(",
"prediction",
")"
] | Calculates the classification error rate for an N-class classification problem
Parameters:
prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your
prediction
true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray`
containing the ground truth labels for the input array, organized... | [
"Calculates",
"the",
"classification",
"error",
"rate",
"for",
"an",
"N",
"-",
"class",
"classification",
"problem"
] | python | train | 25.555556 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1443-L1476 | def _as_published_topic(self):
"""This stream as a PublishedTopic if it is published otherwise None
"""
oop = self.get_operator_output_port()
if not hasattr(oop, 'export'):
return
export = oop.export
if export['type'] != 'properties':
return
... | [
"def",
"_as_published_topic",
"(",
"self",
")",
":",
"oop",
"=",
"self",
".",
"get_operator_output_port",
"(",
")",
"if",
"not",
"hasattr",
"(",
"oop",
",",
"'export'",
")",
":",
"return",
"export",
"=",
"oop",
".",
"export",
"if",
"export",
"[",
"'type'... | This stream as a PublishedTopic if it is published otherwise None | [
"This",
"stream",
"as",
"a",
"PublishedTopic",
"if",
"it",
"is",
"published",
"otherwise",
"None"
] | python | train | 32.323529 |
markuskiller/textblob-de | textblob_de/ext/_pattern/text/__init__.py | https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/__init__.py#L540-L548 | def insert(self, i, tag1, tag2, cmd="prevtag", x=None, y=None):
""" Inserts a new rule that updates words with tag1 to tag2,
given constraints x and y, e.g., Context.append("TO < NN", "VB")
"""
if " < " in tag1 and not x and not y:
tag1, x = tag1.split(" < "); cmd="prevta... | [
"def",
"insert",
"(",
"self",
",",
"i",
",",
"tag1",
",",
"tag2",
",",
"cmd",
"=",
"\"prevtag\"",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"if",
"\" < \"",
"in",
"tag1",
"and",
"not",
"x",
"and",
"not",
"y",
":",
"tag1",
",",
"... | Inserts a new rule that updates words with tag1 to tag2,
given constraints x and y, e.g., Context.append("TO < NN", "VB") | [
"Inserts",
"a",
"new",
"rule",
"that",
"updates",
"words",
"with",
"tag1",
"to",
"tag2",
"given",
"constraints",
"x",
"and",
"y",
"e",
".",
"g",
".",
"Context",
".",
"append",
"(",
"TO",
"<",
"NN",
"VB",
")"
] | python | train | 53.888889 |
mgraffg/EvoDAG | EvoDAG/base.py | https://github.com/mgraffg/EvoDAG/blob/e11fa1fd1ca9e69cca92696c86661a3dc7b3a1d5/EvoDAG/base.py#L454-L476 | def random_offspring(self):
"Returns an offspring with the associated weight(s)"
function_set = self.function_set
function_selection = self._function_selection_ins
function_selection.density = self.population.density
function_selection.unfeasible_functions.clear()
for i i... | [
"def",
"random_offspring",
"(",
"self",
")",
":",
"function_set",
"=",
"self",
".",
"function_set",
"function_selection",
"=",
"self",
".",
"_function_selection_ins",
"function_selection",
".",
"density",
"=",
"self",
".",
"population",
".",
"density",
"function_sel... | Returns an offspring with the associated weight(s) | [
"Returns",
"an",
"offspring",
"with",
"the",
"associated",
"weight",
"(",
"s",
")"
] | python | train | 46.043478 |
pyviz/holoviews | holoviews/core/element.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/element.py#L481-L489 | def static_dimensions(self):
"""
Return all constant dimensions.
"""
dimensions = []
for dim in self.kdims:
if len(set(self.dimension_values(dim.name))) == 1:
dimensions.append(dim)
return dimensions | [
"def",
"static_dimensions",
"(",
"self",
")",
":",
"dimensions",
"=",
"[",
"]",
"for",
"dim",
"in",
"self",
".",
"kdims",
":",
"if",
"len",
"(",
"set",
"(",
"self",
".",
"dimension_values",
"(",
"dim",
".",
"name",
")",
")",
")",
"==",
"1",
":",
... | Return all constant dimensions. | [
"Return",
"all",
"constant",
"dimensions",
"."
] | python | train | 29.666667 |
Esri/ArcREST | src/arcrest/agol/services.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/agol/services.py#L1459-L1472 | def securityHandler(self, value):
""" sets the security handler """
if isinstance(value, abstract.BaseSecurityHandler):
if isinstance(value, security.AGOLTokenSecurityHandler):
self._securityHandler = value
self._token = value.token
self._usern... | [
"def",
"securityHandler",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"abstract",
".",
"BaseSecurityHandler",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"security",
".",
"AGOLTokenSecurityHandler",
")",
":",
"self",
".",... | sets the security handler | [
"sets",
"the",
"security",
"handler"
] | python | train | 44.285714 |
Erotemic/utool | utool/util_str.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L75-L128 | def replace_between_tags(text, repl_, start_tag, end_tag=None):
r"""
Replaces text between sentinal lines in a block of text.
Args:
text (str):
repl_ (str):
start_tag (str):
end_tag (str): (default=None)
Returns:
str: new_text
CommandLine:
python -m... | [
"def",
"replace_between_tags",
"(",
"text",
",",
"repl_",
",",
"start_tag",
",",
"end_tag",
"=",
"None",
")",
":",
"new_lines",
"=",
"[",
"]",
"editing",
"=",
"False",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",... | r"""
Replaces text between sentinal lines in a block of text.
Args:
text (str):
repl_ (str):
start_tag (str):
end_tag (str): (default=None)
Returns:
str: new_text
CommandLine:
python -m utool.util_str --exec-replace_between_tags
Example:
>>... | [
"r",
"Replaces",
"text",
"between",
"sentinal",
"lines",
"in",
"a",
"block",
"of",
"text",
"."
] | python | train | 25.796296 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/breakpoint.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/breakpoint.py#L332-L355 | def eval_condition(self, event):
"""
Evaluates the breakpoint condition, if any was set.
@type event: L{Event}
@param event: Debug event triggered by the breakpoint.
@rtype: bool
@return: C{True} to dispatch the event, C{False} otherwise.
"""
condition... | [
"def",
"eval_condition",
"(",
"self",
",",
"event",
")",
":",
"condition",
"=",
"self",
".",
"get_condition",
"(",
")",
"if",
"condition",
"is",
"True",
":",
"# shortcut for unconditional breakpoints",
"return",
"True",
"if",
"callable",
"(",
"condition",
")",
... | Evaluates the breakpoint condition, if any was set.
@type event: L{Event}
@param event: Debug event triggered by the breakpoint.
@rtype: bool
@return: C{True} to dispatch the event, C{False} otherwise. | [
"Evaluates",
"the",
"breakpoint",
"condition",
"if",
"any",
"was",
"set",
"."
] | python | train | 36.666667 |
softlayer/softlayer-python | SoftLayer/transports.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L158-L163 | def client(self):
"""Returns client session object"""
if self._client is None:
self._client = get_session(self.user_agent)
return self._client | [
"def",
"client",
"(",
"self",
")",
":",
"if",
"self",
".",
"_client",
"is",
"None",
":",
"self",
".",
"_client",
"=",
"get_session",
"(",
"self",
".",
"user_agent",
")",
"return",
"self",
".",
"_client"
] | Returns client session object | [
"Returns",
"client",
"session",
"object"
] | python | train | 29 |
Pr0Ger/PyAPNs2 | apns2/client.py | https://github.com/Pr0Ger/PyAPNs2/blob/6f3b2a7456ef22c6aafc1467618f665130b0aeea/apns2/client.py#L111-L125 | def get_notification_result(self, stream_id):
"""
Get result for specified stream
The function returns: 'Success' or 'failure reason' or ('Unregistered', timestamp)
"""
with self._connection.get_response(stream_id) as response:
if response.status == 200:
... | [
"def",
"get_notification_result",
"(",
"self",
",",
"stream_id",
")",
":",
"with",
"self",
".",
"_connection",
".",
"get_response",
"(",
"stream_id",
")",
"as",
"response",
":",
"if",
"response",
".",
"status",
"==",
"200",
":",
"return",
"'Success'",
"else"... | Get result for specified stream
The function returns: 'Success' or 'failure reason' or ('Unregistered', timestamp) | [
"Get",
"result",
"for",
"specified",
"stream",
"The",
"function",
"returns",
":",
"Success",
"or",
"failure",
"reason",
"or",
"(",
"Unregistered",
"timestamp",
")"
] | python | train | 40.933333 |
phaethon/kamene | kamene/crypto/cert.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/crypto/cert.py#L1916-L1934 | def verifychain_from_cafile(self, cafile, untrusted_file=None):
"""
Does the same job as .verifychain() but using the list of anchors
from the cafile. This is useful (because more efficient) if
you have a lot of certificates to verify do it that way: it
avoids the creation of a c... | [
"def",
"verifychain_from_cafile",
"(",
"self",
",",
"cafile",
",",
"untrusted_file",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"\"openssl\"",
",",
"\"verify\"",
",",
"\"-CAfile\"",
",",
"cafile",
"]",
"if",
"untrusted_file",
":",
"cmd",
"+=",
"[",
"\"-untruste... | Does the same job as .verifychain() but using the list of anchors
from the cafile. This is useful (because more efficient) if
you have a lot of certificates to verify do it that way: it
avoids the creation of a cafile from anchors at each call.
As for .verifychain(), a list of untrusted... | [
"Does",
"the",
"same",
"job",
"as",
".",
"verifychain",
"()",
"but",
"using",
"the",
"list",
"of",
"anchors",
"from",
"the",
"cafile",
".",
"This",
"is",
"useful",
"(",
"because",
"more",
"efficient",
")",
"if",
"you",
"have",
"a",
"lot",
"of",
"certif... | python | train | 42.736842 |
ronhanson/python-tbx | tbx/code.py | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/code.py#L104-L123 | def safe_dict(obj_or_func, **kwargs):
"""
Create a dict from any object with all attributes, but not the ones starting with an underscore _
Useful for objects or function that return an object that have no __dict__ attribute, like psutil functions.
"""
if callable(obj_or_func):
res = obj_or_... | [
"def",
"safe_dict",
"(",
"obj_or_func",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"obj_or_func",
")",
":",
"res",
"=",
"obj_or_func",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"res",
"=",
"obj_or_func",
"if",
"hasattr",
"(",
"res",
"... | Create a dict from any object with all attributes, but not the ones starting with an underscore _
Useful for objects or function that return an object that have no __dict__ attribute, like psutil functions. | [
"Create",
"a",
"dict",
"from",
"any",
"object",
"with",
"all",
"attributes",
"but",
"not",
"the",
"ones",
"starting",
"with",
"an",
"underscore",
"_",
"Useful",
"for",
"objects",
"or",
"function",
"that",
"return",
"an",
"object",
"that",
"have",
"no",
"__... | python | train | 31.2 |
mfitzp/padua | padua/process.py | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/process.py#L309-L327 | def transform_expression_columns(df, fn=np.log2, prefix='Intensity '):
"""
Apply transformation to expression columns.
Default is log2 transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return:
"""
df = df.copy(... | [
"def",
"transform_expression_columns",
"(",
"df",
",",
"fn",
"=",
"np",
".",
"log2",
",",
"prefix",
"=",
"'Intensity '",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"mask",
"=",
"np",
".",
"array",
"(",
"[",
"l",
".",
"startswith",
"(",
"pref... | Apply transformation to expression columns.
Default is log2 transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return: | [
"Apply",
"transformation",
"to",
"expression",
"columns",
"."
] | python | train | 26.052632 |
awslabs/sockeye | sockeye/utils.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/utils.py#L791-L800 | def read_metrics_file(path: str) -> List[Dict[str, Any]]:
"""
Reads lines metrics file and returns list of mappings of key and values.
:param path: File to read metric values from.
:return: Dictionary of metric names (e.g. perplexity-train) mapping to a list of values.
"""
with open(path) as fi... | [
"def",
"read_metrics_file",
"(",
"path",
":",
"str",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"with",
"open",
"(",
"path",
")",
"as",
"fin",
":",
"metrics",
"=",
"[",
"parse_metrics_line",
"(",
"i",
",",
"line",
".",
... | Reads lines metrics file and returns list of mappings of key and values.
:param path: File to read metric values from.
:return: Dictionary of metric names (e.g. perplexity-train) mapping to a list of values. | [
"Reads",
"lines",
"metrics",
"file",
"and",
"returns",
"list",
"of",
"mappings",
"of",
"key",
"and",
"values",
"."
] | python | train | 42.1 |
hazelcast/hazelcast-python-client | hazelcast/proxy/queue.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L67-L93 | def add_listener(self, include_value=False, item_added_func=None, item_removed_func=None):
"""
Adds an item listener for this queue. Listener will be notified for all queue add/remove events.
:param include_value: (bool), whether received events include the updated item or not (optional).
... | [
"def",
"add_listener",
"(",
"self",
",",
"include_value",
"=",
"False",
",",
"item_added_func",
"=",
"None",
",",
"item_removed_func",
"=",
"None",
")",
":",
"request",
"=",
"queue_add_listener_codec",
".",
"encode_request",
"(",
"self",
".",
"name",
",",
"inc... | Adds an item listener for this queue. Listener will be notified for all queue add/remove events.
:param include_value: (bool), whether received events include the updated item or not (optional).
:param item_added_func: Function to be called when an item is added to this set (optional).
:param i... | [
"Adds",
"an",
"item",
"listener",
"for",
"this",
"queue",
".",
"Listener",
"will",
"be",
"notified",
"for",
"all",
"queue",
"add",
"/",
"remove",
"events",
"."
] | python | train | 55.555556 |
B2W-BIT/aiologger | aiologger/handlers/files.py | https://github.com/B2W-BIT/aiologger/blob/0b366597a8305d5577a267305e81d5e4784cd398/aiologger/handlers/files.py#L106-L120 | async def emit(self, record: LogRecord): # type: ignore
"""
Emit a record.
Output the record to the file, catering for rollover as described
in `do_rollover`.
"""
try:
if self.should_rollover(record):
async with self._rollover_lock:
... | [
"async",
"def",
"emit",
"(",
"self",
",",
"record",
":",
"LogRecord",
")",
":",
"# type: ignore",
"try",
":",
"if",
"self",
".",
"should_rollover",
"(",
"record",
")",
":",
"async",
"with",
"self",
".",
"_rollover_lock",
":",
"if",
"self",
".",
"should_r... | Emit a record.
Output the record to the file, catering for rollover as described
in `do_rollover`. | [
"Emit",
"a",
"record",
"."
] | python | train | 34.066667 |
OLC-Bioinformatics/sipprverse | MLSTsippr/mlst.py | https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/MLSTsippr/mlst.py#L84-L150 | def profiler(self):
"""Creates a dictionary from the profile scheme(s)"""
logging.info('Loading profiles')
# Initialise variables
profiledata = defaultdict(make_dict)
reverse_profiledata = dict()
profileset = set()
# Find all the unique profiles to use with a set
... | [
"def",
"profiler",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Loading profiles'",
")",
"# Initialise variables",
"profiledata",
"=",
"defaultdict",
"(",
"make_dict",
")",
"reverse_profiledata",
"=",
"dict",
"(",
")",
"profileset",
"=",
"set",
"(",
"... | Creates a dictionary from the profile scheme(s) | [
"Creates",
"a",
"dictionary",
"from",
"the",
"profile",
"scheme",
"(",
"s",
")"
] | python | train | 60.925373 |
sentinel-hub/sentinelhub-py | sentinelhub/aws_safe.py | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws_safe.py#L329-L348 | def get_qi_name(self, qi_type, band='B00', data_format=MimeType.GML):
"""
:param qi_type: type of quality indicator
:type qi_type: str
:param band: band name
:type band: str
:param data_format: format of the file
:type data_format: MimeType
:return: name o... | [
"def",
"get_qi_name",
"(",
"self",
",",
"qi_type",
",",
"band",
"=",
"'B00'",
",",
"data_format",
"=",
"MimeType",
".",
"GML",
")",
":",
"band",
"=",
"band",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"if",
"self",
".",
"safe_type",
"==",
... | :param qi_type: type of quality indicator
:type qi_type: str
:param band: band name
:type band: str
:param data_format: format of the file
:type data_format: MimeType
:return: name of gml file
:rtype: str | [
":",
"param",
"qi_type",
":",
"type",
"of",
"quality",
"indicator",
":",
"type",
"qi_type",
":",
"str",
":",
"param",
"band",
":",
"band",
"name",
":",
"type",
"band",
":",
"str",
":",
"param",
"data_format",
":",
"format",
"of",
"the",
"file",
":",
... | python | train | 41.75 |
iotile/coretools | iotilegateway/iotilegateway/supervisor/states.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/states.py#L202-L220 | def set_headline(self, level, message, timestamp=None, now_reference=None):
"""Set the persistent headline message for this service.
Args:
level (int): The level of the message (info, warning, error)
message (string): The message contents
timestamp (float): An option... | [
"def",
"set_headline",
"(",
"self",
",",
"level",
",",
"message",
",",
"timestamp",
"=",
"None",
",",
"now_reference",
"=",
"None",
")",
":",
"if",
"self",
".",
"headline",
"is",
"not",
"None",
"and",
"self",
".",
"headline",
".",
"message",
"==",
"mes... | Set the persistent headline message for this service.
Args:
level (int): The level of the message (info, warning, error)
message (string): The message contents
timestamp (float): An optional monotonic value in seconds for when the message was created
now_referenc... | [
"Set",
"the",
"persistent",
"headline",
"message",
"for",
"this",
"service",
"."
] | python | train | 48.315789 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L640-L687 | def out_interactions_iter(self, nbunch=None, t=None):
"""Return an iterator over the out interactions present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes... | [
"def",
"out_interactions_iter",
"(",
"self",
",",
"nbunch",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"if",
"nbunch",
"is",
"None",
":",
"nodes_nbrs_succ",
"=",
"self",
".",
"_succ",
".",
"items",
"(",
")",
"else",
":",
"nodes_nbrs_succ",
"=",
"[",... | Return an iterator over the out interactions present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterat... | [
"Return",
"an",
"iterator",
"over",
"the",
"out",
"interactions",
"present",
"in",
"a",
"given",
"snapshot",
"."
] | python | train | 34.270833 |
log2timeline/dfvfs | dfvfs/volume/volume_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/volume/volume_system.py#L154-L170 | def _AddVolume(self, volume):
"""Adds a volume.
Args:
volume (Volume): a volume.
Raises:
KeyError: if volume is already set for the corresponding volume
identifier.
"""
if volume.identifier in self._volumes:
raise KeyError(
'Volume object already set for volum... | [
"def",
"_AddVolume",
"(",
"self",
",",
"volume",
")",
":",
"if",
"volume",
".",
"identifier",
"in",
"self",
".",
"_volumes",
":",
"raise",
"KeyError",
"(",
"'Volume object already set for volume identifier: {0:s}'",
".",
"format",
"(",
"volume",
".",
"identifier",... | Adds a volume.
Args:
volume (Volume): a volume.
Raises:
KeyError: if volume is already set for the corresponding volume
identifier. | [
"Adds",
"a",
"volume",
"."
] | python | train | 27.529412 |
iterative/dvc | dvc/progress.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/progress.py#L68-L80 | def finish_target(self, name):
"""Finishes progress bar for a specified target."""
# We have to write a msg about finished target
with self._lock:
pbar = self._bar(name, 100, 100)
if sys.stdout.isatty():
self.clearln()
self._print(pbar)
... | [
"def",
"finish_target",
"(",
"self",
",",
"name",
")",
":",
"# We have to write a msg about finished target",
"with",
"self",
".",
"_lock",
":",
"pbar",
"=",
"self",
".",
"_bar",
"(",
"name",
",",
"100",
",",
"100",
")",
"if",
"sys",
".",
"stdout",
".",
... | Finishes progress bar for a specified target. | [
"Finishes",
"progress",
"bar",
"for",
"a",
"specified",
"target",
"."
] | python | train | 28.230769 |
rigetti/quantumflow | quantumflow/ops.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L254-L259 | def su(self) -> 'Gate':
"""Convert gate tensor to the special unitary group."""
rank = 2**self.qubit_nb
U = asarray(self.asoperator())
U /= np.linalg.det(U) ** (1/rank)
return Gate(tensor=U, qubits=self.qubits) | [
"def",
"su",
"(",
"self",
")",
"->",
"'Gate'",
":",
"rank",
"=",
"2",
"**",
"self",
".",
"qubit_nb",
"U",
"=",
"asarray",
"(",
"self",
".",
"asoperator",
"(",
")",
")",
"U",
"/=",
"np",
".",
"linalg",
".",
"det",
"(",
"U",
")",
"**",
"(",
"1"... | Convert gate tensor to the special unitary group. | [
"Convert",
"gate",
"tensor",
"to",
"the",
"special",
"unitary",
"group",
"."
] | python | train | 40.833333 |
clusterpoint/python-client-api | pycps/converters.py | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/converters.py#L141-L175 | def to_etree(source, root_tag=None):
""" Convert various representations of an XML structure to a etree Element
Args:
source -- The source object to be converted - ET.Element\ElementTree, dict or string.
Keyword args:
root_tag -- A optional parent tag in which to wrap the x... | [
"def",
"to_etree",
"(",
"source",
",",
"root_tag",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"source",
",",
"'get_root'",
")",
":",
"#XXX:",
"return",
"source",
".",
"get_root",
"(",
")",
"elif",
"isinstance",
"(",
"source",
",",
"type",
"(",
"ET",
... | Convert various representations of an XML structure to a etree Element
Args:
source -- The source object to be converted - ET.Element\ElementTree, dict or string.
Keyword args:
root_tag -- A optional parent tag in which to wrap the xml tree if no root in dict representation.
... | [
"Convert",
"various",
"representations",
"of",
"an",
"XML",
"structure",
"to",
"a",
"etree",
"Element"
] | python | train | 35.314286 |
tomMoral/loky | loky/process_executor.py | https://github.com/tomMoral/loky/blob/dc2d941d8285a96f3a5b666a4bd04875b0b25984/loky/process_executor.py#L468-L505 | def _add_call_item_to_queue(pending_work_items,
running_work_items,
work_ids,
call_queue):
"""Fills call_queue with _WorkItems from pending_work_items.
This function never blocks.
Args:
pending_work_items: A dict m... | [
"def",
"_add_call_item_to_queue",
"(",
"pending_work_items",
",",
"running_work_items",
",",
"work_ids",
",",
"call_queue",
")",
":",
"while",
"True",
":",
"if",
"call_queue",
".",
"full",
"(",
")",
":",
"return",
"try",
":",
"work_id",
"=",
"work_ids",
".",
... | Fills call_queue with _WorkItems from pending_work_items.
This function never blocks.
Args:
pending_work_items: A dict mapping work ids to _WorkItems e.g.
{5: <_WorkItem...>, 6: <_WorkItem...>, ...}
work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids
a... | [
"Fills",
"call_queue",
"with",
"_WorkItems",
"from",
"pending_work_items",
"."
] | python | test | 37.710526 |
eandersson/amqpstorm | examples/robust_consumer.py | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/robust_consumer.py#L39-L59 | def start(self):
"""Start the Consumers.
:return:
"""
if not self.connection:
self.create_connection()
while True:
try:
channel = self.connection.channel()
channel.queue.declare('simple_queue')
channel.basic... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connection",
":",
"self",
".",
"create_connection",
"(",
")",
"while",
"True",
":",
"try",
":",
"channel",
"=",
"self",
".",
"connection",
".",
"channel",
"(",
")",
"channel",
".",
"qu... | Start the Consumers.
:return: | [
"Start",
"the",
"Consumers",
"."
] | python | train | 33.047619 |
SYNHAK/spiff | spiff/api/models.py | https://github.com/SYNHAK/spiff/blob/5e5c731f67954ddc11d2fb75371cfcfd0fef49b7/spiff/api/models.py#L10-L42 | def add_resource_permissions(*args, **kwargs):
"""
This syncdb hooks takes care of adding a view permission too all our
content types.
"""
# for each of our content types
for resource in find_api_classes('v1_api', ModelResource):
auth = resource._meta.authorization
content_type = ContentType.object... | [
"def",
"add_resource_permissions",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# for each of our content types",
"for",
"resource",
"in",
"find_api_classes",
"(",
"'v1_api'",
",",
"ModelResource",
")",
":",
"auth",
"=",
"resource",
".",
"_meta",
".",
... | This syncdb hooks takes care of adding a view permission too all our
content types. | [
"This",
"syncdb",
"hooks",
"takes",
"care",
"of",
"adding",
"a",
"view",
"permission",
"too",
"all",
"our",
"content",
"types",
"."
] | python | train | 42.818182 |
atmos-python/atmos | atmos/plot.py | https://github.com/atmos-python/atmos/blob/f4af8eaca23cce881bde979599d15d322fc1935e/atmos/plot.py#L323-L389 | def plot_dry_adiabats(self, p=None, theta=None, **kwargs):
r'''Plot dry adiabats.
Adds dry adiabats (lines of constant potential temperature) to the
plot. The default style of these lines is dashed red lines with an
alpha value of 0.5. These can be overridden using keyword arguments.
... | [
"def",
"plot_dry_adiabats",
"(",
"self",
",",
"p",
"=",
"None",
",",
"theta",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"artist",
"in",
"self",
".",
"_dry_adiabats",
":",
"artist",
".",
"remove",
"(",
")",
"self",
".",
"_dry_adiabats",
"... | r'''Plot dry adiabats.
Adds dry adiabats (lines of constant potential temperature) to the
plot. The default style of these lines is dashed red lines with an
alpha value of 0.5. These can be overridden using keyword arguments.
Parameters
----------
p : array_like, option... | [
"r",
"Plot",
"dry",
"adiabats",
"."
] | python | train | 39.58209 |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb/phlb_main.py | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/phlb_main.py#L456-L511 | def _backup_dir_item(self, dir_path, process_bar):
"""
Backup one dir item
:param dir_path: filesystem_walk.DirEntryPath() instance
"""
self.path_helper.set_src_filepath(dir_path)
if self.path_helper.abs_src_filepath is None:
self.total_errored_items += 1
... | [
"def",
"_backup_dir_item",
"(",
"self",
",",
"dir_path",
",",
"process_bar",
")",
":",
"self",
".",
"path_helper",
".",
"set_src_filepath",
"(",
"dir_path",
")",
"if",
"self",
".",
"path_helper",
".",
"abs_src_filepath",
"is",
"None",
":",
"self",
".",
"tota... | Backup one dir item
:param dir_path: filesystem_walk.DirEntryPath() instance | [
"Backup",
"one",
"dir",
"item"
] | python | train | 36.357143 |
Julius2342/pyvlx | pyvlx/scene.py | https://github.com/Julius2342/pyvlx/blob/ee78e1324bcb1be5b8d1a9d05ab5496b72eae848/pyvlx/scene.py#L23-L37 | async def run(self, wait_for_completion=True):
"""Run scene.
Parameters:
* wait_for_completion: If set, function will return
after device has reached target position.
"""
activate_scene = ActivateScene(
pyvlx=self.pyvlx,
wait_for_comp... | [
"async",
"def",
"run",
"(",
"self",
",",
"wait_for_completion",
"=",
"True",
")",
":",
"activate_scene",
"=",
"ActivateScene",
"(",
"pyvlx",
"=",
"self",
".",
"pyvlx",
",",
"wait_for_completion",
"=",
"wait_for_completion",
",",
"scene_id",
"=",
"self",
".",
... | Run scene.
Parameters:
* wait_for_completion: If set, function will return
after device has reached target position. | [
"Run",
"scene",
"."
] | python | train | 34.133333 |
NASA-AMMOS/AIT-Core | ait/core/util.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/util.py#L414-L435 | def listAllFiles (directory, suffix=None, abspath=False):
"""Returns the list of all files within the input directory and
all subdirectories.
"""
files = []
directory = expandPath(directory)
for dirpath, dirnames, filenames in os.walk(directory, followlinks=True):
if suffix:
... | [
"def",
"listAllFiles",
"(",
"directory",
",",
"suffix",
"=",
"None",
",",
"abspath",
"=",
"False",
")",
":",
"files",
"=",
"[",
"]",
"directory",
"=",
"expandPath",
"(",
"directory",
")",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
... | Returns the list of all files within the input directory and
all subdirectories. | [
"Returns",
"the",
"list",
"of",
"all",
"files",
"within",
"the",
"input",
"directory",
"and",
"all",
"subdirectories",
"."
] | python | train | 29.454545 |
Crypto-toolbox/btfxwss | btfxwss/client.py | https://github.com/Crypto-toolbox/btfxwss/blob/16827fa6aacb2c0e289aa852bf61a18df6905835/btfxwss/client.py#L131-L140 | def candles(self, pair, timeframe=None):
"""Return a queue containing all received candles data.
:param pair: str, Symbol pair to request data for
:param timeframe: str
:return: Queue()
"""
timeframe = '1m' if not timeframe else timeframe
key = ('candles', pair, ... | [
"def",
"candles",
"(",
"self",
",",
"pair",
",",
"timeframe",
"=",
"None",
")",
":",
"timeframe",
"=",
"'1m'",
"if",
"not",
"timeframe",
"else",
"timeframe",
"key",
"=",
"(",
"'candles'",
",",
"pair",
",",
"timeframe",
")",
"return",
"self",
".",
"queu... | Return a queue containing all received candles data.
:param pair: str, Symbol pair to request data for
:param timeframe: str
:return: Queue() | [
"Return",
"a",
"queue",
"containing",
"all",
"received",
"candles",
"data",
"."
] | python | test | 37 |
mottosso/be | be/lib.py | https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L457-L484 | def item_from_topics(key, topics):
"""Get binding from `topics` via `key`
Example:
{0} == hello --> be in hello world
{1} == world --> be in hello world
Returns:
Single topic matching the key
Raises:
IndexError (int): With number of required
arguments for t... | [
"def",
"item_from_topics",
"(",
"key",
",",
"topics",
")",
":",
"if",
"re",
".",
"match",
"(",
"\"{\\d+}\"",
",",
"key",
")",
":",
"pos",
"=",
"int",
"(",
"key",
".",
"strip",
"(",
"\"{}\"",
")",
")",
"try",
":",
"binding",
"=",
"topics",
"[",
"p... | Get binding from `topics` via `key`
Example:
{0} == hello --> be in hello world
{1} == world --> be in hello world
Returns:
Single topic matching the key
Raises:
IndexError (int): With number of required
arguments for the key | [
"Get",
"binding",
"from",
"topics",
"via",
"key"
] | python | train | 21.5 |
pywbem/pywbem | pywbem/cim_http.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_http.py#L1011-L1044 | def get_cimobject_header(obj):
"""
Return the value for the CIM-XML extension header field 'CIMObject', using
the given object.
This function implements the rules defined in DSP0200 section 6.3.7
"CIMObject". The format of the CIMObject value is similar but not identical
to a local WBEM URI (on... | [
"def",
"get_cimobject_header",
"(",
"obj",
")",
":",
"# Local namespace path",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"return",
"obj",
"# Local class path",
"if",
"isinstance",
"(",
"obj",
",",
"CIMClassName",
")",
":",
"ret... | Return the value for the CIM-XML extension header field 'CIMObject', using
the given object.
This function implements the rules defined in DSP0200 section 6.3.7
"CIMObject". The format of the CIMObject value is similar but not identical
to a local WBEM URI (one without namespace type and authority), as... | [
"Return",
"the",
"value",
"for",
"the",
"CIM",
"-",
"XML",
"extension",
"header",
"field",
"CIMObject",
"using",
"the",
"given",
"object",
"."
] | python | train | 35.823529 |
aleju/imgaug | imgaug/augmentables/heatmaps.py | https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L78-L104 | def get_arr(self):
"""
Get the heatmap's array within the value range originally provided in ``__init__()``.
The HeatmapsOnImage object saves heatmaps internally in the value range ``(min=0.0, max=1.0)``.
This function converts the internal representation to ``(min=min_value, max=max_va... | [
"def",
"get_arr",
"(",
"self",
")",
":",
"if",
"self",
".",
"arr_was_2d",
"and",
"self",
".",
"arr_0to1",
".",
"shape",
"[",
"2",
"]",
"==",
"1",
":",
"arr",
"=",
"self",
".",
"arr_0to1",
"[",
":",
",",
":",
",",
"0",
"]",
"else",
":",
"arr",
... | Get the heatmap's array within the value range originally provided in ``__init__()``.
The HeatmapsOnImage object saves heatmaps internally in the value range ``(min=0.0, max=1.0)``.
This function converts the internal representation to ``(min=min_value, max=max_value)``,
where ``min_value`` and... | [
"Get",
"the",
"heatmap",
"s",
"array",
"within",
"the",
"value",
"range",
"originally",
"provided",
"in",
"__init__",
"()",
"."
] | python | valid | 38 |
DomainTools/python_api | domaintools/api.py | https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L249-L305 | def iris_investigate(self, domains=None, data_updated_after=None, expiration_date=None,
create_date=None, active=None, **kwargs):
"""Returns back a list of domains based on the provided filters.
The following filters are available beyond what is parameterized as kwargs:
... | [
"def",
"iris_investigate",
"(",
"self",
",",
"domains",
"=",
"None",
",",
"data_updated_after",
"=",
"None",
",",
"expiration_date",
"=",
"None",
",",
"create_date",
"=",
"None",
",",
"active",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",... | Returns back a list of domains based on the provided filters.
The following filters are available beyond what is parameterized as kwargs:
- ip: Search for domains having this IP.
- email: Search for domains with this email in their data.
- email_domain: Search for domains wh... | [
"Returns",
"back",
"a",
"list",
"of",
"domains",
"based",
"on",
"the",
"provided",
"filters",
".",
"The",
"following",
"filters",
"are",
"available",
"beyond",
"what",
"is",
"parameterized",
"as",
"kwargs",
":"
] | python | train | 65.824561 |
facebook/watchman | python/pywatchman/__init__.py | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1019-L1056 | def receive(self):
""" receive the next PDU from the watchman service
If the client has activated subscriptions or logs then
this PDU may be a unilateral PDU sent by the service to
inform the client of a log event or subscription change.
It may also simply be the response porti... | [
"def",
"receive",
"(",
"self",
")",
":",
"self",
".",
"_connect",
"(",
")",
"result",
"=",
"self",
".",
"recvConn",
".",
"receive",
"(",
")",
"if",
"self",
".",
"_hasprop",
"(",
"result",
",",
"\"error\"",
")",
":",
"raise",
"CommandError",
"(",
"res... | receive the next PDU from the watchman service
If the client has activated subscriptions or logs then
this PDU may be a unilateral PDU sent by the service to
inform the client of a log event or subscription change.
It may also simply be the response portion of a request
initiat... | [
"receive",
"the",
"next",
"PDU",
"from",
"the",
"watchman",
"service"
] | python | train | 36.026316 |
senaite/senaite.lims | src/senaite/lims/browser/bootstrap/views.py | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/bootstrap/views.py#L60-L81 | def get_icon_for(self, brain_or_object):
"""Get the navigation portlet icon for the brain or object
The cache key ensures that the lookup is done only once per domain name
"""
portal_types = api.get_tool("portal_types")
fti = portal_types.getTypeInfo(api.get_portal_type(brain_or... | [
"def",
"get_icon_for",
"(",
"self",
",",
"brain_or_object",
")",
":",
"portal_types",
"=",
"api",
".",
"get_tool",
"(",
"\"portal_types\"",
")",
"fti",
"=",
"portal_types",
".",
"getTypeInfo",
"(",
"api",
".",
"get_portal_type",
"(",
"brain_or_object",
")",
")... | Get the navigation portlet icon for the brain or object
The cache key ensures that the lookup is done only once per domain name | [
"Get",
"the",
"navigation",
"portlet",
"icon",
"for",
"the",
"brain",
"or",
"object"
] | python | train | 46.454545 |
lsst-sqre/lsst-projectmeta-kit | lsstprojectmeta/ltd.py | https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/ltd.py#L28-L58 | async def get_ltd_product(session, slug=None, url=None):
"""Get the product resource (JSON document) from the LSST the Docs API.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/client.html.
... | [
"async",
"def",
"get_ltd_product",
"(",
"session",
",",
"slug",
"=",
"None",
",",
"url",
"=",
"None",
")",
":",
"if",
"url",
"is",
"None",
":",
"url",
"=",
"'https://keeper.lsst.codes/products/{}'",
".",
"format",
"(",
"slug",
")",
"async",
"with",
"sessio... | Get the product resource (JSON document) from the LSST the Docs API.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/client.html.
slug : `str`, optional
Slug identfying the product. Th... | [
"Get",
"the",
"product",
"resource",
"(",
"JSON",
"document",
")",
"from",
"the",
"LSST",
"the",
"Docs",
"API",
"."
] | python | valid | 34.967742 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L132-L134 | def count(self, weighted=True):
"""Return numberic count of rows considered for cube response."""
return self._measures.weighted_n if weighted else self._measures.unweighted_n | [
"def",
"count",
"(",
"self",
",",
"weighted",
"=",
"True",
")",
":",
"return",
"self",
".",
"_measures",
".",
"weighted_n",
"if",
"weighted",
"else",
"self",
".",
"_measures",
".",
"unweighted_n"
] | Return numberic count of rows considered for cube response. | [
"Return",
"numberic",
"count",
"of",
"rows",
"considered",
"for",
"cube",
"response",
"."
] | python | train | 63 |
anomaly/prestans | prestans/devel/__init__.py | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/devel/__init__.py#L72-L124 | def _add_generate_sub_commands(self):
"""
Sub commands for generating models for usage by clients.
Currently supports Google Closure.
"""
gen_parser = self._subparsers_handle.add_parser(
name="gen",
help="generate client side model stubs, filters"
... | [
"def",
"_add_generate_sub_commands",
"(",
"self",
")",
":",
"gen_parser",
"=",
"self",
".",
"_subparsers_handle",
".",
"add_parser",
"(",
"name",
"=",
"\"gen\"",
",",
"help",
"=",
"\"generate client side model stubs, filters\"",
")",
"gen_parser",
".",
"add_argument",... | Sub commands for generating models for usage by clients.
Currently supports Google Closure. | [
"Sub",
"commands",
"for",
"generating",
"models",
"for",
"usage",
"by",
"clients",
".",
"Currently",
"supports",
"Google",
"Closure",
"."
] | python | train | 28.075472 |
wglass/lighthouse | lighthouse/zookeeper.py | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/zookeeper.py#L200-L228 | def report_up(self, service, port):
"""
Report the given service's present node as up by creating/updating
its respective znode in Zookeeper and setting the znode's data to
the serialized representation of the node.
Waits for zookeeper to be connected before taking any action.
... | [
"def",
"report_up",
"(",
"self",
",",
"service",
",",
"port",
")",
":",
"wait_on_any",
"(",
"self",
".",
"connected",
",",
"self",
".",
"shutdown",
")",
"node",
"=",
"Node",
".",
"current",
"(",
"service",
",",
"port",
")",
"path",
"=",
"self",
".",
... | Report the given service's present node as up by creating/updating
its respective znode in Zookeeper and setting the znode's data to
the serialized representation of the node.
Waits for zookeeper to be connected before taking any action. | [
"Report",
"the",
"given",
"service",
"s",
"present",
"node",
"as",
"up",
"by",
"creating",
"/",
"updating",
"its",
"respective",
"znode",
"in",
"Zookeeper",
"and",
"setting",
"the",
"znode",
"s",
"data",
"to",
"the",
"serialized",
"representation",
"of",
"th... | python | train | 38.448276 |
ejeschke/ginga | ginga/util/wcs.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcs.py#L577-L585 | def get_starsep_RaDecDeg(ra1_deg, dec1_deg, ra2_deg, dec2_deg):
"""Calculate separation."""
sep = deltaStarsRaDecDeg(ra1_deg, dec1_deg, ra2_deg, dec2_deg)
sgn, deg, mn, sec = degToDms(sep)
if deg != 0:
txt = '%02d:%02d:%06.3f' % (deg, mn, sec)
else:
txt = '%02d:%06.3f' % (mn, sec)
... | [
"def",
"get_starsep_RaDecDeg",
"(",
"ra1_deg",
",",
"dec1_deg",
",",
"ra2_deg",
",",
"dec2_deg",
")",
":",
"sep",
"=",
"deltaStarsRaDecDeg",
"(",
"ra1_deg",
",",
"dec1_deg",
",",
"ra2_deg",
",",
"dec2_deg",
")",
"sgn",
",",
"deg",
",",
"mn",
",",
"sec",
... | Calculate separation. | [
"Calculate",
"separation",
"."
] | python | train | 36 |
nosegae/NoseGAE | examples/modules_example/printenv.py | https://github.com/nosegae/NoseGAE/blob/fca9fab22b480bb9721ecaa0967a636107648d92/examples/modules_example/printenv.py#L33-L43 | def html_for_env_var(key):
"""Returns an HTML snippet for an environment variable.
Args:
key: A string representing an environment variable name.
Returns:
String HTML representing the value and variable.
"""
value = os.getenv(key)
return KEY_VALUE_TEMPLATE.format(key, value) | [
"def",
"html_for_env_var",
"(",
"key",
")",
":",
"value",
"=",
"os",
".",
"getenv",
"(",
"key",
")",
"return",
"KEY_VALUE_TEMPLATE",
".",
"format",
"(",
"key",
",",
"value",
")"
] | Returns an HTML snippet for an environment variable.
Args:
key: A string representing an environment variable name.
Returns:
String HTML representing the value and variable. | [
"Returns",
"an",
"HTML",
"snippet",
"for",
"an",
"environment",
"variable",
"."
] | python | train | 27.909091 |
agusmakmun/djipsum | djipsum/fields.py | https://github.com/agusmakmun/djipsum/blob/e7950556422b4039092db2083db7a83728230977/djipsum/fields.py#L85-L120 | def randomDecimalField(self, model_class, field_name):
"""
Validate if the field has a `max_digits` and `decimal_places`
And generating the unique decimal number.
"""
decimal_field = model_class._meta.get_field(field_name)
max_digits = None
decimal_places = None
... | [
"def",
"randomDecimalField",
"(",
"self",
",",
"model_class",
",",
"field_name",
")",
":",
"decimal_field",
"=",
"model_class",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
"max_digits",
"=",
"None",
"decimal_places",
"=",
"None",
"if",
"decimal_field... | Validate if the field has a `max_digits` and `decimal_places`
And generating the unique decimal number. | [
"Validate",
"if",
"the",
"field",
"has",
"a",
"max_digits",
"and",
"decimal_places",
"And",
"generating",
"the",
"unique",
"decimal",
"number",
"."
] | python | train | 33.666667 |
rabitt/pysox | sox/transform.py | https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L506-L545 | def bandpass(self, frequency, width_q=2.0, constant_skirt=False):
'''Apply a two-pole Butterworth band-pass filter with the given central
frequency, and (3dB-point) band-width. The filter rolls off at 6dB per
octave (20dB per decade) and is described in detail in
http://musicdsp.org/file... | [
"def",
"bandpass",
"(",
"self",
",",
"frequency",
",",
"width_q",
"=",
"2.0",
",",
"constant_skirt",
"=",
"False",
")",
":",
"if",
"not",
"is_number",
"(",
"frequency",
")",
"or",
"frequency",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"frequency must b... | Apply a two-pole Butterworth band-pass filter with the given central
frequency, and (3dB-point) band-width. The filter rolls off at 6dB per
octave (20dB per decade) and is described in detail in
http://musicdsp.org/files/Audio-EQ-Cookbook.txt
Parameters
----------
freque... | [
"Apply",
"a",
"two",
"-",
"pole",
"Butterworth",
"band",
"-",
"pass",
"filter",
"with",
"the",
"given",
"central",
"frequency",
"and",
"(",
"3dB",
"-",
"point",
")",
"band",
"-",
"width",
".",
"The",
"filter",
"rolls",
"off",
"at",
"6dB",
"per",
"octav... | python | valid | 34.8 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L263-L271 | def cursor_position_col(self):
"""
Current column. (0-based.)
"""
# (Don't use self.text_before_cursor to calculate this. Creating
# substrings and doing rsplit is too expensive for getting the cursor
# position.)
_, line_start_index = self._find_line_start_index(... | [
"def",
"cursor_position_col",
"(",
"self",
")",
":",
"# (Don't use self.text_before_cursor to calculate this. Creating",
"# substrings and doing rsplit is too expensive for getting the cursor",
"# position.)",
"_",
",",
"line_start_index",
"=",
"self",
".",
"_find_line_start_index",
... | Current column. (0-based.) | [
"Current",
"column",
".",
"(",
"0",
"-",
"based",
".",
")"
] | python | train | 43.111111 |
genialis/resolwe | resolwe/flow/utils/stats.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/stats.py#L164-L169 | def to_dict(self):
"""Pack the load averages into a nicely-keyed dictionary."""
result = {}
for meta in self.intervals.values():
result[meta.display] = meta.value
return result | [
"def",
"to_dict",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"meta",
"in",
"self",
".",
"intervals",
".",
"values",
"(",
")",
":",
"result",
"[",
"meta",
".",
"display",
"]",
"=",
"meta",
".",
"value",
"return",
"result"
] | Pack the load averages into a nicely-keyed dictionary. | [
"Pack",
"the",
"load",
"averages",
"into",
"a",
"nicely",
"-",
"keyed",
"dictionary",
"."
] | python | train | 35.833333 |
scanny/python-pptx | pptx/chart/chart.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/chart.py#L170-L178 | def replace_data(self, chart_data):
"""
Use the categories and series values in the |ChartData| object
*chart_data* to replace those in the XML and Excel worksheet for this
chart.
"""
rewriter = SeriesXmlRewriterFactory(self.chart_type, chart_data)
rewriter.replac... | [
"def",
"replace_data",
"(",
"self",
",",
"chart_data",
")",
":",
"rewriter",
"=",
"SeriesXmlRewriterFactory",
"(",
"self",
".",
"chart_type",
",",
"chart_data",
")",
"rewriter",
".",
"replace_series_data",
"(",
"self",
".",
"_chartSpace",
")",
"self",
".",
"_w... | Use the categories and series values in the |ChartData| object
*chart_data* to replace those in the XML and Excel worksheet for this
chart. | [
"Use",
"the",
"categories",
"and",
"series",
"values",
"in",
"the",
"|ChartData|",
"object",
"*",
"chart_data",
"*",
"to",
"replace",
"those",
"in",
"the",
"XML",
"and",
"Excel",
"worksheet",
"for",
"this",
"chart",
"."
] | python | train | 45.555556 |
santoshphilip/eppy | eppy/idfreader.py | https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/idfreader.py#L132-L137 | def convertafield(field_comm, field_val, field_iddname):
"""convert field based on field info in IDD"""
convinidd = ConvInIDD()
field_typ = field_comm.get('type', [None])[0]
conv = convinidd.conv_dict().get(field_typ, convinidd.no_type)
return conv(field_val, field_iddname) | [
"def",
"convertafield",
"(",
"field_comm",
",",
"field_val",
",",
"field_iddname",
")",
":",
"convinidd",
"=",
"ConvInIDD",
"(",
")",
"field_typ",
"=",
"field_comm",
".",
"get",
"(",
"'type'",
",",
"[",
"None",
"]",
")",
"[",
"0",
"]",
"conv",
"=",
"co... | convert field based on field info in IDD | [
"convert",
"field",
"based",
"on",
"field",
"info",
"in",
"IDD"
] | python | train | 48.833333 |
CodyKochmann/generators | generators/split.py | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/split.py#L12-L46 | def split(pipe, splitter, skip_empty=False):
''' this function works a lot like groupby but splits on given patterns,
the same behavior as str.split provides. if skip_empty is True,
split only yields pieces that have contents
Example:
splitting 1011101010101
by ... | [
"def",
"split",
"(",
"pipe",
",",
"splitter",
",",
"skip_empty",
"=",
"False",
")",
":",
"splitter",
"=",
"tuple",
"(",
"splitter",
")",
"len_splitter",
"=",
"len",
"(",
"splitter",
")",
"pipe",
"=",
"iter",
"(",
"pipe",
")",
"current",
"=",
"deque",
... | this function works a lot like groupby but splits on given patterns,
the same behavior as str.split provides. if skip_empty is True,
split only yields pieces that have contents
Example:
splitting 1011101010101
by 10
returns ,11,,,,1
Or if s... | [
"this",
"function",
"works",
"a",
"lot",
"like",
"groupby",
"but",
"splits",
"on",
"given",
"patterns",
"the",
"same",
"behavior",
"as",
"str",
".",
"split",
"provides",
".",
"if",
"skip_empty",
"is",
"True",
"split",
"only",
"yields",
"pieces",
"that",
"h... | python | train | 26.542857 |
biocore/burrito-fillings | bfillings/usearch.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/usearch.py#L1039-L1100 | def get_retained_chimeras(output_fp_de_novo_nonchimeras,
output_fp_ref_nonchimeras,
output_combined_fp,
chimeras_retention='union'):
""" Gets union or intersection of two supplied fasta files
output_fp_de_novo_nonchimeras: filepath o... | [
"def",
"get_retained_chimeras",
"(",
"output_fp_de_novo_nonchimeras",
",",
"output_fp_ref_nonchimeras",
",",
"output_combined_fp",
",",
"chimeras_retention",
"=",
"'union'",
")",
":",
"de_novo_non_chimeras",
"=",
"[",
"]",
"reference_non_chimeras",
"=",
"[",
"]",
"de_novo... | Gets union or intersection of two supplied fasta files
output_fp_de_novo_nonchimeras: filepath of nonchimeras from de novo
usearch detection.
output_fp_ref_nonchimeras: filepath of nonchimeras from reference based
usearch detection.
output_combined_fp: filepath to write retained sequences to.
... | [
"Gets",
"union",
"or",
"intersection",
"of",
"two",
"supplied",
"fasta",
"files"
] | python | train | 40.516129 |
MonashBI/arcana | arcana/pipeline/base.py | https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/pipeline/base.py#L507-L526 | def iterators(self, frequency=None):
"""
Returns the iterators (i.e. subject_id, visit_id) that the pipeline
iterates over
Parameters
----------
frequency : str | None
A selected data frequency to use to determine which iterators are
required. If ... | [
"def",
"iterators",
"(",
"self",
",",
"frequency",
"=",
"None",
")",
":",
"iterators",
"=",
"set",
"(",
")",
"if",
"frequency",
"is",
"None",
":",
"input_freqs",
"=",
"list",
"(",
"self",
".",
"input_frequencies",
")",
"else",
":",
"input_freqs",
"=",
... | Returns the iterators (i.e. subject_id, visit_id) that the pipeline
iterates over
Parameters
----------
frequency : str | None
A selected data frequency to use to determine which iterators are
required. If None, all input frequencies of the pipeline are
... | [
"Returns",
"the",
"iterators",
"(",
"i",
".",
"e",
".",
"subject_id",
"visit_id",
")",
"that",
"the",
"pipeline",
"iterates",
"over"
] | python | train | 33 |
petl-developers/petlx | petlx/bio/vcf.py | https://github.com/petl-developers/petlx/blob/54039e30388c7da12407d6b5c3cb865b00436004/petlx/bio/vcf.py#L126-L158 | def vcfmeltsamples(table, *samples):
"""
Melt the samples columns. E.g.::
>>> import petl as etl
>>> # activate bio extensions
... import petlx.bio
>>> table1 = (
... etl
... .fromvcf('fixture/sample.vcf')
... .vcfmeltsamples()
...... | [
"def",
"vcfmeltsamples",
"(",
"table",
",",
"*",
"samples",
")",
":",
"result",
"=",
"etl",
".",
"melt",
"(",
"table",
",",
"key",
"=",
"VCF_HEADER",
",",
"variables",
"=",
"samples",
",",
"variablefield",
"=",
"'SAMPLE'",
",",
"valuefield",
"=",
"'CALL'... | Melt the samples columns. E.g.::
>>> import petl as etl
>>> # activate bio extensions
... import petlx.bio
>>> table1 = (
... etl
... .fromvcf('fixture/sample.vcf')
... .vcfmeltsamples()
... )
>>> table1
+-------+-----+----... | [
"Melt",
"the",
"samples",
"columns",
".",
"E",
".",
"g",
".",
"::",
">>>",
"import",
"petl",
"as",
"etl",
">>>",
"#",
"activate",
"bio",
"extensions",
"...",
"import",
"petlx",
".",
"bio",
">>>",
"table1",
"=",
"(",
"...",
"etl",
"...",
".",
"fromvcf... | python | train | 66.484848 |
jonfaustman/django-frontend | djfrontend/templatetags/djfrontend.py | https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L204-L218 | def djfrontend_jquery_scrollto(version=None):
"""
Returns the jQuery ScrollTo plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERY_SCROLLTO', DJFRONTEND_JQUERY_SCROLL... | [
"def",
"djfrontend_jquery_scrollto",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_SCROLLTO'",
",",
"DJFRONTEND_JQUERY_SCROLLTO_DEFAULT",
")",
"if",
"getattr",
"(",
"... | Returns the jQuery ScrollTo plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file. | [
"Returns",
"the",
"jQuery",
"ScrollTo",
"plugin",
"file",
"according",
"to",
"version",
"number",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
"."
] | python | test | 57.933333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.