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 |
|---|---|---|---|---|---|---|---|---|---|
Damgaard/PyImgur | pyimgur/__init__.py | https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1294-L1304 | def get_albums(self, limit=None):
"""
Return a list of the user's albums.
Secret and hidden albums are only returned if this is the logged-in
user.
"""
url = (self._imgur._base_url + "/3/account/{0}/albums/{1}".format(self.name,
... | [
"def",
"get_albums",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"url",
"=",
"(",
"self",
".",
"_imgur",
".",
"_base_url",
"+",
"\"/3/account/{0}/albums/{1}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"'{}'",
")",
")",
"resp",
"=",
"self",
... | Return a list of the user's albums.
Secret and hidden albums are only returned if this is the logged-in
user. | [
"Return",
"a",
"list",
"of",
"the",
"user",
"s",
"albums",
"."
] | python | train | 42.636364 |
has2k1/plotnine | plotnine/utils.py | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L721-L744 | def make_line_segments(x, y, ispath=True):
"""
Return an (n x 2 x 2) array of n line segments
Parameters
----------
x : array-like
x points
y : array-like
y points
ispath : bool
If True, the points represent a path from one point
to the next until the last. I... | [
"def",
"make_line_segments",
"(",
"x",
",",
"y",
",",
"ispath",
"=",
"True",
")",
":",
"if",
"ispath",
":",
"x",
"=",
"interleave",
"(",
"x",
"[",
":",
"-",
"1",
"]",
",",
"x",
"[",
"1",
":",
"]",
")",
"y",
"=",
"interleave",
"(",
"y",
"[",
... | Return an (n x 2 x 2) array of n line segments
Parameters
----------
x : array-like
x points
y : array-like
y points
ispath : bool
If True, the points represent a path from one point
to the next until the last. If False, then each pair
of successive(even-odd ... | [
"Return",
"an",
"(",
"n",
"x",
"2",
"x",
"2",
")",
"array",
"of",
"n",
"line",
"segments"
] | python | train | 27.416667 |
openego/ding0 | ding0/tools/geo.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/tools/geo.py#L31-L74 | def calc_geo_branches_in_polygon(mv_grid, polygon, mode, proj):
""" Calculate geographical branches in polygon.
For a given `mv_grid` all branches (edges in the graph of the grid) are
tested if they are in the given `polygon`. You can choose different modes
and projections for this operation.
Para... | [
"def",
"calc_geo_branches_in_polygon",
"(",
"mv_grid",
",",
"polygon",
",",
"mode",
",",
"proj",
")",
":",
"branches",
"=",
"[",
"]",
"polygon_shp",
"=",
"transform",
"(",
"proj",
",",
"polygon",
")",
"for",
"branch",
"in",
"mv_grid",
".",
"graph_edges",
"... | Calculate geographical branches in polygon.
For a given `mv_grid` all branches (edges in the graph of the grid) are
tested if they are in the given `polygon`. You can choose different modes
and projections for this operation.
Parameters
----------
mv_grid : MVGridDing0
MV Grid object. ... | [
"Calculate",
"geographical",
"branches",
"in",
"polygon",
"."
] | python | train | 33.045455 |
rstoneback/pysat | pysat/instruments/nasa_cdaweb_methods.py | https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/instruments/nasa_cdaweb_methods.py#L159-L261 | def download(supported_tags, date_array, tag, sat_id,
ftp_site='cdaweb.gsfc.nasa.gov',
data_path=None, user=None, password=None,
fake_daily_files_from_monthly=False):
"""Routine to download NASA CDAWeb CDF data.
This routine is intended to be used by pysat instrumen... | [
"def",
"download",
"(",
"supported_tags",
",",
"date_array",
",",
"tag",
",",
"sat_id",
",",
"ftp_site",
"=",
"'cdaweb.gsfc.nasa.gov'",
",",
"data_path",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"fake_daily_files_from_monthly",
... | Routine to download NASA CDAWeb CDF data.
This routine is intended to be used by pysat instrument modules supporting
a particular NASA CDAWeb dataset.
Parameters
-----------
supported_tags : dict
dict of dicts. Keys are supported tag names for download. Value is
a dict with 'd... | [
"Routine",
"to",
"download",
"NASA",
"CDAWeb",
"CDF",
"data",
".",
"This",
"routine",
"is",
"intended",
"to",
"be",
"used",
"by",
"pysat",
"instrument",
"modules",
"supporting",
"a",
"particular",
"NASA",
"CDAWeb",
"dataset",
"."
] | python | train | 37.330097 |
rkargon/pixelsorter | pixelsorter/util.py | https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/util.py#L72-L84 | def weighted_random_choice(items):
"""
Returns a weighted random choice from a list of items.
:param items: A list of tuples (object, weight)
:return: A random object, whose likelihood is proportional to its weight.
"""
l = list(items)
r = random.random() * sum([i[1] for i in l])
for x, ... | [
"def",
"weighted_random_choice",
"(",
"items",
")",
":",
"l",
"=",
"list",
"(",
"items",
")",
"r",
"=",
"random",
".",
"random",
"(",
")",
"*",
"sum",
"(",
"[",
"i",
"[",
"1",
"]",
"for",
"i",
"in",
"l",
"]",
")",
"for",
"x",
",",
"p",
"in",
... | Returns a weighted random choice from a list of items.
:param items: A list of tuples (object, weight)
:return: A random object, whose likelihood is proportional to its weight. | [
"Returns",
"a",
"weighted",
"random",
"choice",
"from",
"a",
"list",
"of",
"items",
".",
":",
"param",
"items",
":",
"A",
"list",
"of",
"tuples",
"(",
"object",
"weight",
")",
":",
"return",
":",
"A",
"random",
"object",
"whose",
"likelihood",
"is",
"p... | python | train | 29.615385 |
projectshift/shift-boiler | boiler/cli/db.py | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L121-L129 | def merge(revision, branch_label, message, list_revisions=''):
""" Merge two revision together, create new revision file """
alembic_command.merge(
config=get_config(),
revisions=list_revisions,
message=message,
branch_label=branch_label,
rev_id=revision
) | [
"def",
"merge",
"(",
"revision",
",",
"branch_label",
",",
"message",
",",
"list_revisions",
"=",
"''",
")",
":",
"alembic_command",
".",
"merge",
"(",
"config",
"=",
"get_config",
"(",
")",
",",
"revisions",
"=",
"list_revisions",
",",
"message",
"=",
"me... | Merge two revision together, create new revision file | [
"Merge",
"two",
"revision",
"together",
"create",
"new",
"revision",
"file"
] | python | train | 33.333333 |
brbsix/pip-utils | pip_utils/outdated.py | https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/outdated.py#L176-L183 | def get_dependants(cls, dist):
"""Yield dependant user packages for a given package name."""
for package in cls.installed_distributions:
for requirement_package in package.requires():
requirement_name = requirement_package.project_name
# perform case-insensiti... | [
"def",
"get_dependants",
"(",
"cls",
",",
"dist",
")",
":",
"for",
"package",
"in",
"cls",
".",
"installed_distributions",
":",
"for",
"requirement_package",
"in",
"package",
".",
"requires",
"(",
")",
":",
"requirement_name",
"=",
"requirement_package",
".",
... | Yield dependant user packages for a given package name. | [
"Yield",
"dependant",
"user",
"packages",
"for",
"a",
"given",
"package",
"name",
"."
] | python | train | 52.375 |
ARMmbed/icetea | icetea_lib/IceteaManager.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L292-L305 | def _cleanup_resourceprovider(self):
"""
Calls cleanup for ResourceProvider of this run.
:return: Nothing
"""
# Disable too broad exception warning
# pylint: disable=W0703
self.resourceprovider = ResourceProvider(self.args)
try:
self.resourcep... | [
"def",
"_cleanup_resourceprovider",
"(",
"self",
")",
":",
"# Disable too broad exception warning",
"# pylint: disable=W0703",
"self",
".",
"resourceprovider",
"=",
"ResourceProvider",
"(",
"self",
".",
"args",
")",
"try",
":",
"self",
".",
"resourceprovider",
".",
"c... | Calls cleanup for ResourceProvider of this run.
:return: Nothing | [
"Calls",
"cleanup",
"for",
"ResourceProvider",
"of",
"this",
"run",
"."
] | python | train | 33.142857 |
prompt-toolkit/pyvim | pyvim/commands/commands.py | https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/commands/commands.py#L302-L306 | def quit_all(editor, force=False):
"""
Quit all.
"""
quit(editor, all_=True, force=force) | [
"def",
"quit_all",
"(",
"editor",
",",
"force",
"=",
"False",
")",
":",
"quit",
"(",
"editor",
",",
"all_",
"=",
"True",
",",
"force",
"=",
"force",
")"
] | Quit all. | [
"Quit",
"all",
"."
] | python | train | 20.2 |
ValvePython/steam | steam/client/user.py | https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/client/user.py#L28-L39 | def get_ps(self, field_name, wait_pstate=True):
"""Get property from PersonaState
`See full list of available fields_names <https://github.com/ValvePython/steam/blob/fa8a5127e9bb23185483930da0b6ae85e93055a7/protobufs/steammessages_clientserver_friends.proto#L125-L153>`_
"""
if not wait_... | [
"def",
"get_ps",
"(",
"self",
",",
"field_name",
",",
"wait_pstate",
"=",
"True",
")",
":",
"if",
"not",
"wait_pstate",
"or",
"self",
".",
"_pstate_ready",
".",
"wait",
"(",
"timeout",
"=",
"5",
")",
":",
"if",
"self",
".",
"_pstate",
"is",
"None",
"... | Get property from PersonaState
`See full list of available fields_names <https://github.com/ValvePython/steam/blob/fa8a5127e9bb23185483930da0b6ae85e93055a7/protobufs/steammessages_clientserver_friends.proto#L125-L153>`_ | [
"Get",
"property",
"from",
"PersonaState"
] | python | train | 49.916667 |
matiasb/demiurge | demiurge/demiurge.py | https://github.com/matiasb/demiurge/blob/4cfbb24f0519ab99b9bf36fa4c20283ae6e7b9fe/demiurge/demiurge.py#L250-L254 | def all(cls, path=''):
"""Return all ocurrences of the item."""
url = urljoin(cls._meta.base_url, path)
pq_items = cls._get_items(url=url, **cls._meta._pyquery_kwargs)
return [cls(item=i) for i in pq_items.items()] | [
"def",
"all",
"(",
"cls",
",",
"path",
"=",
"''",
")",
":",
"url",
"=",
"urljoin",
"(",
"cls",
".",
"_meta",
".",
"base_url",
",",
"path",
")",
"pq_items",
"=",
"cls",
".",
"_get_items",
"(",
"url",
"=",
"url",
",",
"*",
"*",
"cls",
".",
"_meta... | Return all ocurrences of the item. | [
"Return",
"all",
"ocurrences",
"of",
"the",
"item",
"."
] | python | train | 48.4 |
wonambi-python/wonambi | wonambi/trans/reject.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/reject.py#L13-L83 | def remove_artf_evts(times, annot, chan=None, min_dur=0.1):
"""Correct times to remove events marked 'Artefact'.
Parameters
----------
times : list of tuple of float
the start and end times of each segment
annot : instance of Annotations
the annotation file containing events and epo... | [
"def",
"remove_artf_evts",
"(",
"times",
",",
"annot",
",",
"chan",
"=",
"None",
",",
"min_dur",
"=",
"0.1",
")",
":",
"new_times",
"=",
"times",
"beg",
"=",
"times",
"[",
"0",
"]",
"[",
"0",
"]",
"end",
"=",
"times",
"[",
"-",
"1",
"]",
"[",
"... | Correct times to remove events marked 'Artefact'.
Parameters
----------
times : list of tuple of float
the start and end times of each segment
annot : instance of Annotations
the annotation file containing events and epochs
chan : str, optional
full name of channel on which ... | [
"Correct",
"times",
"to",
"remove",
"events",
"marked",
"Artefact",
"."
] | python | train | 33.549296 |
napalm-automation/napalm-logs | napalm_logs/transport/__init__.py | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/transport/__init__.py#L50-L60 | def get_transport(name):
'''
Return the transport class.
'''
try:
log.debug('Using %s as transport', name)
return TRANSPORT_LOOKUP[name]
except KeyError:
msg = 'Transport {} is not available. Are the dependencies installed?'.format(name)
log.error(msg, exc_info=True)
... | [
"def",
"get_transport",
"(",
"name",
")",
":",
"try",
":",
"log",
".",
"debug",
"(",
"'Using %s as transport'",
",",
"name",
")",
"return",
"TRANSPORT_LOOKUP",
"[",
"name",
"]",
"except",
"KeyError",
":",
"msg",
"=",
"'Transport {} is not available. Are the depend... | Return the transport class. | [
"Return",
"the",
"transport",
"class",
"."
] | python | train | 32.181818 |
f3at/feat | src/feat/extern/log/log.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/extern/log/log.py#L826-L831 | def log(self, *args):
"""Log a log message. Used for debugging recurring events."""
if _canShortcutLogging(self.logCategory, LOG):
return
logObject(self.logObjectName(), self.logCategory,
*self.logFunction(*args)) | [
"def",
"log",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"_canShortcutLogging",
"(",
"self",
".",
"logCategory",
",",
"LOG",
")",
":",
"return",
"logObject",
"(",
"self",
".",
"logObjectName",
"(",
")",
",",
"self",
".",
"logCategory",
",",
"*",
... | Log a log message. Used for debugging recurring events. | [
"Log",
"a",
"log",
"message",
".",
"Used",
"for",
"debugging",
"recurring",
"events",
"."
] | python | train | 42.833333 |
spotify/docker_interface | docker_interface/util.py | https://github.com/spotify/docker_interface/blob/4df80e1fe072d958020080d32c16551ff7703d51/docker_interface/util.py#L57-L74 | def split_path(path, ref=None):
"""
Split a path into its components.
Parameters
----------
path : str
absolute or relative path with respect to `ref`
ref : str or None
reference path if `path` is relative
Returns
-------
list : str
components of the path
... | [
"def",
"split_path",
"(",
"path",
",",
"ref",
"=",
"None",
")",
":",
"path",
"=",
"abspath",
"(",
"path",
",",
"ref",
")",
"return",
"path",
".",
"strip",
"(",
"os",
".",
"path",
".",
"sep",
")",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep"... | Split a path into its components.
Parameters
----------
path : str
absolute or relative path with respect to `ref`
ref : str or None
reference path if `path` is relative
Returns
-------
list : str
components of the path | [
"Split",
"a",
"path",
"into",
"its",
"components",
"."
] | python | train | 21.777778 |
apache/spark | python/pyspark/ml/param/__init__.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L273-L288 | def explainParam(self, param):
"""
Explains a single param and returns its name, doc, and optional
default value and user-supplied value in a string.
"""
param = self._resolveParam(param)
values = []
if self.isDefined(param):
if param in self._defaultP... | [
"def",
"explainParam",
"(",
"self",
",",
"param",
")",
":",
"param",
"=",
"self",
".",
"_resolveParam",
"(",
"param",
")",
"values",
"=",
"[",
"]",
"if",
"self",
".",
"isDefined",
"(",
"param",
")",
":",
"if",
"param",
"in",
"self",
".",
"_defaultPar... | Explains a single param and returns its name, doc, and optional
default value and user-supplied value in a string. | [
"Explains",
"a",
"single",
"param",
"and",
"returns",
"its",
"name",
"doc",
"and",
"optional",
"default",
"value",
"and",
"user",
"-",
"supplied",
"value",
"in",
"a",
"string",
"."
] | python | train | 41.4375 |
mdiener/grace | grace/py27/pyjsdoc.py | https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/pyjsdoc.py#L1395-L1416 | def topological_sort(dependencies, start_nodes):
"""
Perform a topological sort on the dependency graph `dependencies`, starting
from list `start_nodes`.
"""
retval = []
def edges(node): return dependencies[node][1]
def in_degree(node): return dependencies[node][0]
def remove_incoming(no... | [
"def",
"topological_sort",
"(",
"dependencies",
",",
"start_nodes",
")",
":",
"retval",
"=",
"[",
"]",
"def",
"edges",
"(",
"node",
")",
":",
"return",
"dependencies",
"[",
"node",
"]",
"[",
"1",
"]",
"def",
"in_degree",
"(",
"node",
")",
":",
"return"... | Perform a topological sort on the dependency graph `dependencies`, starting
from list `start_nodes`. | [
"Perform",
"a",
"topological",
"sort",
"on",
"the",
"dependency",
"graph",
"dependencies",
"starting",
"from",
"list",
"start_nodes",
"."
] | python | train | 36 |
ianmiell/shutit | emailer.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/emailer.py#L180-L198 | def __compose(self):
""" Compose the message, pulling together body, attachments etc
"""
msg = MIMEMultipart()
msg['Subject'] = self.config['shutit.core.alerting.emailer.subject']
msg['To'] = self.config['shutit.core.alerting.emailer.mailto']
msg['From'] = self.config['shutit.core.alerting.emailer.... | [
"def",
"__compose",
"(",
"self",
")",
":",
"msg",
"=",
"MIMEMultipart",
"(",
")",
"msg",
"[",
"'Subject'",
"]",
"=",
"self",
".",
"config",
"[",
"'shutit.core.alerting.emailer.subject'",
"]",
"msg",
"[",
"'To'",
"]",
"=",
"self",
".",
"config",
"[",
"'sh... | Compose the message, pulling together body, attachments etc | [
"Compose",
"the",
"message",
"pulling",
"together",
"body",
"attachments",
"etc"
] | python | train | 45.421053 |
pyviz/holoviews | holoviews/util/__init__.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/util/__init__.py#L320-L359 | def _expand_options(cls, options, backend=None):
"""
Validates and expands a dictionaries of options indexed by
type[.group][.label] keys into separate style, plot, norm and
output options.
opts._expand_options({'Image': dict(cmap='viridis', show_title=False)})
retu... | [
"def",
"_expand_options",
"(",
"cls",
",",
"options",
",",
"backend",
"=",
"None",
")",
":",
"current_backend",
"=",
"Store",
".",
"current_backend",
"try",
":",
"backend_options",
"=",
"Store",
".",
"options",
"(",
"backend",
"=",
"backend",
"or",
"current_... | Validates and expands a dictionaries of options indexed by
type[.group][.label] keys into separate style, plot, norm and
output options.
opts._expand_options({'Image': dict(cmap='viridis', show_title=False)})
returns
{'Image': {'plot': dict(show_title=False), 'style': ... | [
"Validates",
"and",
"expands",
"a",
"dictionaries",
"of",
"options",
"indexed",
"by",
"type",
"[",
".",
"group",
"]",
"[",
".",
"label",
"]",
"keys",
"into",
"separate",
"style",
"plot",
"norm",
"and",
"output",
"options",
"."
] | python | train | 43.275 |
niemasd/TreeSwift | treeswift/Tree.py | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L525-L548 | def indent(self, space=4):
'''Return an indented Newick string, just like ``nw_indent`` in Newick Utilities
Args:
``space`` (``int``): The number of spaces a tab should equal
Returns:
``str``: An indented Newick string
'''
if not isinstance(space,int):
... | [
"def",
"indent",
"(",
"self",
",",
"space",
"=",
"4",
")",
":",
"if",
"not",
"isinstance",
"(",
"space",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"space must be an int\"",
")",
"if",
"space",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"spac... | Return an indented Newick string, just like ``nw_indent`` in Newick Utilities
Args:
``space`` (``int``): The number of spaces a tab should equal
Returns:
``str``: An indented Newick string | [
"Return",
"an",
"indented",
"Newick",
"string",
"just",
"like",
"nw_indent",
"in",
"Newick",
"Utilities"
] | python | train | 35.208333 |
kensho-technologies/graphql-compiler | graphql_compiler/compiler/filters.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/filters.py#L284-L346 | def _process_name_or_alias_filter_directive(filter_operation_info, location, context, parameters):
"""Return a Filter basic block that checks for a match against an Entity's name or alias.
Args:
filter_operation_info: FilterOperationInfo object, containing the directive and field info
... | [
"def",
"_process_name_or_alias_filter_directive",
"(",
"filter_operation_info",
",",
"location",
",",
"context",
",",
"parameters",
")",
":",
"filtered_field_type",
"=",
"filter_operation_info",
".",
"field_type",
"if",
"isinstance",
"(",
"filtered_field_type",
",",
"Grap... | Return a Filter basic block that checks for a match against an Entity's name or alias.
Args:
filter_operation_info: FilterOperationInfo object, containing the directive and field info
of the field where the filter is to be applied.
location: Location where this filter... | [
"Return",
"a",
"Filter",
"basic",
"block",
"that",
"checks",
"for",
"a",
"match",
"against",
"an",
"Entity",
"s",
"name",
"or",
"alias",
"."
] | python | train | 57.936508 |
bitlabstudio/django-dynamic-content | dynamic_content/templatetags/dynamic_content_tags.py | https://github.com/bitlabstudio/django-dynamic-content/blob/65fc557872c1a3d789fa6cc345532ad6f1e4bba7/dynamic_content/templatetags/dynamic_content_tags.py#L11-L30 | def get_content(identifier, default=None):
'''
Returns the DynamicContent instance for the given identifier.
If no object is found, a new one will be created.
:param identifier: String representing the unique identifier of a
``DynamicContent`` object.
:param default: String that should be us... | [
"def",
"get_content",
"(",
"identifier",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"''",
"try",
":",
"return",
"models",
".",
"DynamicContent",
".",
"objects",
".",
"get",
"(",
"identifier",
"=",
"identifi... | Returns the DynamicContent instance for the given identifier.
If no object is found, a new one will be created.
:param identifier: String representing the unique identifier of a
``DynamicContent`` object.
:param default: String that should be used in case that no matching
``DynamicContent`` ob... | [
"Returns",
"the",
"DynamicContent",
"instance",
"for",
"the",
"given",
"identifier",
"."
] | python | train | 32.8 |
cloudify-cosmo/wagon | wagon.py | https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L866-L914 | def validate(source):
"""Validate a Wagon archive. Return True if succeeds, False otherwise.
It also prints a list of all validation errors.
This will test that some of the metadata is solid, that
the required wheels are present within the archives and that
the package is installable.
Note tha... | [
"def",
"validate",
"(",
"source",
")",
":",
"_assert_virtualenv_is_installed",
"(",
")",
"logger",
".",
"info",
"(",
"'Validating %s'",
",",
"source",
")",
"processed_source",
"=",
"get_source",
"(",
"source",
")",
"metadata",
"=",
"_get_metadata",
"(",
"process... | Validate a Wagon archive. Return True if succeeds, False otherwise.
It also prints a list of all validation errors.
This will test that some of the metadata is solid, that
the required wheels are present within the archives and that
the package is installable.
Note that if the metadata file is cor... | [
"Validate",
"a",
"Wagon",
"archive",
".",
"Return",
"True",
"if",
"succeeds",
"False",
"otherwise",
".",
"It",
"also",
"prints",
"a",
"list",
"of",
"all",
"validation",
"errors",
"."
] | python | train | 37 |
sorgerlab/indra | indra/sources/bel/rdf_processor.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L873-L880 | def print_statements(self):
"""Print all extracted INDRA Statements."""
logger.info('--- Direct INDRA statements ----------')
for i, stmt in enumerate(self.statements):
logger.info("%s: %s" % (i, stmt))
logger.info('--- Indirect INDRA statements ----------')
for i, st... | [
"def",
"print_statements",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'--- Direct INDRA statements ----------'",
")",
"for",
"i",
",",
"stmt",
"in",
"enumerate",
"(",
"self",
".",
"statements",
")",
":",
"logger",
".",
"info",
"(",
"\"%s: %s\"",
"%"... | Print all extracted INDRA Statements. | [
"Print",
"all",
"extracted",
"INDRA",
"Statements",
"."
] | python | train | 49.5 |
inasafe/inasafe | safe/gui/tools/help/field_mapping_help.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/field_mapping_help.py#L50-L82 | def content():
"""Helper method that returns just the content.
This method was added so that the text could be reused in the
dock_help module.
.. versionadded:: 4.1.0
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message
"""
message = m.Message()
... | [
"def",
"content",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"paragraph",
"=",
"m",
".",
"Paragraph",
"(",
"m",
".",
"Image",
"(",
"'file:///%s/img/screenshots/'",
"'field-mapping-tool-screenshot.png'",
"%",
"resources_path",
"(",
")",
")",
... | Helper method that returns just the content.
This method was added so that the text could be reused in the
dock_help module.
.. versionadded:: 4.1.0
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message | [
"Helper",
"method",
"that",
"returns",
"just",
"the",
"content",
"."
] | python | train | 29.454545 |
openvax/isovar | isovar/assembly.py | https://github.com/openvax/isovar/blob/b39b684920e3f6b344851d6598a1a1c67bce913b/isovar/assembly.py#L118-L146 | def iterative_overlap_assembly(
variant_sequences,
min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE):
"""
Assembles longer sequences from reads centered on a variant by
between merging all pairs of overlapping sequences and collapsing
shorter sequences onto every longer sequen... | [
"def",
"iterative_overlap_assembly",
"(",
"variant_sequences",
",",
"min_overlap_size",
"=",
"MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE",
")",
":",
"if",
"len",
"(",
"variant_sequences",
")",
"<=",
"1",
":",
"# if we don't have at least two sequences to start with then",
"# sk... | Assembles longer sequences from reads centered on a variant by
between merging all pairs of overlapping sequences and collapsing
shorter sequences onto every longer sequence which contains them.
Returns a list of variant sequences, sorted by decreasing read support. | [
"Assembles",
"longer",
"sequences",
"from",
"reads",
"centered",
"on",
"a",
"variant",
"by",
"between",
"merging",
"all",
"pairs",
"of",
"overlapping",
"sequences",
"and",
"collapsing",
"shorter",
"sequences",
"onto",
"every",
"longer",
"sequence",
"which",
"conta... | python | train | 40.310345 |
BerkeleyAutomation/visualization | visualization/visualizer2d.py | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L34-L45 | def show(filename=None, *args, **kwargs):
""" Show the current figure.
Parameters
----------
filename : :obj:`str`
filename to save the image to, for auto-saving
"""
if filename is None:
plt.show(*args, **kwargs)
else:
plt.save... | [
"def",
"show",
"(",
"filename",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"filename",
"is",
"None",
":",
"plt",
".",
"show",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"plt",
".",
"savefig",
"(",
... | Show the current figure.
Parameters
----------
filename : :obj:`str`
filename to save the image to, for auto-saving | [
"Show",
"the",
"current",
"figure",
"."
] | python | train | 28.25 |
martinpitt/python-dbusmock | dbusmock/mockobject.py | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L133-L145 | def Get(self, interface_name, property_name):
'''Standard D-Bus API for getting a property value'''
self.log('Get %s.%s' % (interface_name, property_name))
if not interface_name:
interface_name = self.interface
try:
return self.GetAll(interface_name)[property_na... | [
"def",
"Get",
"(",
"self",
",",
"interface_name",
",",
"property_name",
")",
":",
"self",
".",
"log",
"(",
"'Get %s.%s'",
"%",
"(",
"interface_name",
",",
"property_name",
")",
")",
"if",
"not",
"interface_name",
":",
"interface_name",
"=",
"self",
".",
"i... | Standard D-Bus API for getting a property value | [
"Standard",
"D",
"-",
"Bus",
"API",
"for",
"getting",
"a",
"property",
"value"
] | python | train | 38.153846 |
getsentry/rb | rb/router.py | https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/router.py#L87-L89 | def get_host_for_command(self, command, args):
"""Returns the host this command should be executed against."""
return self.get_host_for_key(self.get_key(command, args)) | [
"def",
"get_host_for_command",
"(",
"self",
",",
"command",
",",
"args",
")",
":",
"return",
"self",
".",
"get_host_for_key",
"(",
"self",
".",
"get_key",
"(",
"command",
",",
"args",
")",
")"
] | Returns the host this command should be executed against. | [
"Returns",
"the",
"host",
"this",
"command",
"should",
"be",
"executed",
"against",
"."
] | python | train | 60.666667 |
KE-works/pykechain | pykechain/models/customization.py | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L96-L126 | def _save_customization(self, widgets):
"""
Save the complete customization to the activity.
:param widgets: The complete set of widgets to be customized
"""
if len(widgets) > 0:
# Get the current customization and only replace the 'ext' part of it
custom... | [
"def",
"_save_customization",
"(",
"self",
",",
"widgets",
")",
":",
"if",
"len",
"(",
"widgets",
")",
">",
"0",
":",
"# Get the current customization and only replace the 'ext' part of it",
"customization",
"=",
"self",
".",
"activity",
".",
"_json_data",
".",
"get... | Save the complete customization to the activity.
:param widgets: The complete set of widgets to be customized | [
"Save",
"the",
"complete",
"customization",
"to",
"the",
"activity",
"."
] | python | train | 43.516129 |
spotify/gordon-gcp | src/gordon_gcp/plugins/service/__init__.py | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/service/__init__.py#L34-L60 | def get_event_consumer(config, success_channel, error_channel, metrics,
**kwargs):
"""Get a GPSEventConsumer client.
A factory function that validates configuration, creates schema
validator and parser clients, creates an auth and a pubsub client,
and returns an event consumer (:... | [
"def",
"get_event_consumer",
"(",
"config",
",",
"success_channel",
",",
"error_channel",
",",
"metrics",
",",
"*",
"*",
"kwargs",
")",
":",
"builder",
"=",
"event_consumer",
".",
"GPSEventConsumerBuilder",
"(",
"config",
",",
"success_channel",
",",
"error_channe... | Get a GPSEventConsumer client.
A factory function that validates configuration, creates schema
validator and parser clients, creates an auth and a pubsub client,
and returns an event consumer (:interface:`gordon.interfaces.
IRunnable` and :interface:`gordon.interfaces.IMessageHandler`)
provider.
... | [
"Get",
"a",
"GPSEventConsumer",
"client",
"."
] | python | train | 44.222222 |
QuantEcon/QuantEcon.py | quantecon/matrix_eqn.py | https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/matrix_eqn.py#L22-L96 | def solve_discrete_lyapunov(A, B, max_it=50, method="doubling"):
r"""
Computes the solution to the discrete lyapunov equation
.. math::
AXA' - X + B = 0
:math:`X` is computed by using a doubling algorithm. In particular, we
iterate to convergence on :math:`X_j` with the following recursio... | [
"def",
"solve_discrete_lyapunov",
"(",
"A",
",",
"B",
",",
"max_it",
"=",
"50",
",",
"method",
"=",
"\"doubling\"",
")",
":",
"if",
"method",
"==",
"\"doubling\"",
":",
"A",
",",
"B",
"=",
"list",
"(",
"map",
"(",
"np",
".",
"atleast_2d",
",",
"[",
... | r"""
Computes the solution to the discrete lyapunov equation
.. math::
AXA' - X + B = 0
:math:`X` is computed by using a doubling algorithm. In particular, we
iterate to convergence on :math:`X_j` with the following recursions for
:math:`j = 1, 2, \dots` starting from :math:`X_0 = B`, :ma... | [
"r",
"Computes",
"the",
"solution",
"to",
"the",
"discrete",
"lyapunov",
"equation"
] | python | train | 28.52 |
abe-winter/pg13-py | pg13/syncschema.py | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/syncschema.py#L68-L86 | def update_changes(changes,newtext,change):
"decide whether to compact the newest change into the old last; return new change list. assumes changes is safe to mutate.\
note: newtext MUST be the result of applying change to changes, and is only passed to save doing the computation again."
# the criteria for a n... | [
"def",
"update_changes",
"(",
"changes",
",",
"newtext",
",",
"change",
")",
":",
"# the criteria for a new version are:\r",
"# 1. mode change (modes are adding to end, deleting from end, internal edits)\r",
"# 2. length changed by more than 256 chars (why power of 2? why not)\r",
"# 3. ti... | decide whether to compact the newest change into the old last; return new change list. assumes changes is safe to mutate.\
note: newtext MUST be the result of applying change to changes, and is only passed to save doing the computation again. | [
"decide",
"whether",
"to",
"compact",
"the",
"newest",
"change",
"into",
"the",
"old",
"last",
";",
"return",
"new",
"change",
"list",
".",
"assumes",
"changes",
"is",
"safe",
"to",
"mutate",
".",
"\\",
"note",
":",
"newtext",
"MUST",
"be",
"the",
"resul... | python | train | 56.052632 |
CalebBell/fluids | fluids/geometry.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L567-L606 | def V_vertical_conical(D, a, h):
r'''Calculates volume of a vertical tank with a convex conical bottom,
according to [1]_. No provision for the top of the tank is made here.
.. math::
V_f = \frac{\pi}{4}\left(\frac{Dh}{a}\right)^2\left(\frac{h}{3}\right),\; h < a
.. math::
V_f = \frac{... | [
"def",
"V_vertical_conical",
"(",
"D",
",",
"a",
",",
"h",
")",
":",
"if",
"h",
"<",
"a",
":",
"Vf",
"=",
"pi",
"/",
"4",
"*",
"(",
"D",
"*",
"h",
"/",
"a",
")",
"**",
"2",
"*",
"(",
"h",
"/",
"3.",
")",
"else",
":",
"Vf",
"=",
"pi",
... | r'''Calculates volume of a vertical tank with a convex conical bottom,
according to [1]_. No provision for the top of the tank is made here.
.. math::
V_f = \frac{\pi}{4}\left(\frac{Dh}{a}\right)^2\left(\frac{h}{3}\right),\; h < a
.. math::
V_f = \frac{\pi D^2}{4}\left(h - \frac{2a}{3}\rig... | [
"r",
"Calculates",
"volume",
"of",
"a",
"vertical",
"tank",
"with",
"a",
"convex",
"conical",
"bottom",
"according",
"to",
"[",
"1",
"]",
"_",
".",
"No",
"provision",
"for",
"the",
"top",
"of",
"the",
"tank",
"is",
"made",
"here",
"."
] | python | train | 27.525 |
senaite/senaite.core | bika/lims/content/duplicateanalysis.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/duplicateanalysis.py#L81-L120 | def getSiblings(self, retracted=False):
"""
Return the list of duplicate analyses that share the same Request and
are included in the same Worksheet as the current analysis. The current
duplicate is excluded from the list.
:param retracted: If false, retracted/rejected siblings a... | [
"def",
"getSiblings",
"(",
"self",
",",
"retracted",
"=",
"False",
")",
":",
"worksheet",
"=",
"self",
".",
"getWorksheet",
"(",
")",
"requestuid",
"=",
"self",
".",
"getRequestUID",
"(",
")",
"if",
"not",
"requestuid",
"or",
"not",
"worksheet",
":",
"re... | Return the list of duplicate analyses that share the same Request and
are included in the same Worksheet as the current analysis. The current
duplicate is excluded from the list.
:param retracted: If false, retracted/rejected siblings are dismissed
:type retracted: bool
:return: ... | [
"Return",
"the",
"list",
"of",
"duplicate",
"analyses",
"that",
"share",
"the",
"same",
"Request",
"and",
"are",
"included",
"in",
"the",
"same",
"Worksheet",
"as",
"the",
"current",
"analysis",
".",
"The",
"current",
"duplicate",
"is",
"excluded",
"from",
"... | python | train | 36.025 |
Duke-GCB/DukeDSClient | ddsc/core/localstore.py | https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/localstore.py#L106-L140 | def _build_folder_tree(top_abspath, followsymlinks, file_filter):
"""
Build a tree of LocalFolder with children based on a path.
:param top_abspath: str path to a directory to walk
:param followsymlinks: bool should we follow symlinks when walking
:param file_filter: FileFilter: include method retur... | [
"def",
"_build_folder_tree",
"(",
"top_abspath",
",",
"followsymlinks",
",",
"file_filter",
")",
":",
"path_to_content",
"=",
"{",
"}",
"child_to_parent",
"=",
"{",
"}",
"ignore_file_patterns",
"=",
"IgnoreFilePatterns",
"(",
"file_filter",
")",
"ignore_file_patterns"... | Build a tree of LocalFolder with children based on a path.
:param top_abspath: str path to a directory to walk
:param followsymlinks: bool should we follow symlinks when walking
:param file_filter: FileFilter: include method returns True if we should include a file/folder
:return: the top node of the tr... | [
"Build",
"a",
"tree",
"of",
"LocalFolder",
"with",
"children",
"based",
"on",
"a",
"path",
".",
":",
"param",
"top_abspath",
":",
"str",
"path",
"to",
"a",
"directory",
"to",
"walk",
":",
"param",
"followsymlinks",
":",
"bool",
"should",
"we",
"follow",
... | python | train | 51.771429 |
timothydmorton/VESPA | vespa/populations.py | https://github.com/timothydmorton/VESPA/blob/0446b54d48009f3655cfd1a3957ceea21d3adcaa/vespa/populations.py#L1105-L1233 | def generate(self,rprs=None, mass=None, radius=None,
n=2e4, fp_specific=0.01, u1=None, u2=None,
starmodel=None,
Teff=None, logg=None, rbin_width=0.3,
MAfn=None, lhoodcachefile=None):
"""Generates Population
All arguments defined in ``__in... | [
"def",
"generate",
"(",
"self",
",",
"rprs",
"=",
"None",
",",
"mass",
"=",
"None",
",",
"radius",
"=",
"None",
",",
"n",
"=",
"2e4",
",",
"fp_specific",
"=",
"0.01",
",",
"u1",
"=",
"None",
",",
"u2",
"=",
"None",
",",
"starmodel",
"=",
"None",
... | Generates Population
All arguments defined in ``__init__``. | [
"Generates",
"Population"
] | python | train | 38.992248 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L164-L178 | def add_file_group(self, fileGrp):
"""
Add a new ``mets:fileGrp``.
Arguments:
fileGrp (string): ``USE`` attribute of the new filegroup.
"""
el_fileSec = self._tree.getroot().find('mets:fileSec', NS)
if el_fileSec is None:
el_fileSec = ET.SubElemen... | [
"def",
"add_file_group",
"(",
"self",
",",
"fileGrp",
")",
":",
"el_fileSec",
"=",
"self",
".",
"_tree",
".",
"getroot",
"(",
")",
".",
"find",
"(",
"'mets:fileSec'",
",",
"NS",
")",
"if",
"el_fileSec",
"is",
"None",
":",
"el_fileSec",
"=",
"ET",
".",
... | Add a new ``mets:fileGrp``.
Arguments:
fileGrp (string): ``USE`` attribute of the new filegroup. | [
"Add",
"a",
"new",
"mets",
":",
"fileGrp",
"."
] | python | train | 39.6 |
stevearc/dynamo3 | dynamo3/result.py | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L499-L506 | def set_request_args(self, args):
""" Set the Limit parameter into the request args """
if self.scan_limit is not None:
args['Limit'] = self.scan_limit
elif self.item_limit is not None:
args['Limit'] = max(self.item_limit, self.min_scan_limit)
else:
ar... | [
"def",
"set_request_args",
"(",
"self",
",",
"args",
")",
":",
"if",
"self",
".",
"scan_limit",
"is",
"not",
"None",
":",
"args",
"[",
"'Limit'",
"]",
"=",
"self",
".",
"scan_limit",
"elif",
"self",
".",
"item_limit",
"is",
"not",
"None",
":",
"args",
... | Set the Limit parameter into the request args | [
"Set",
"the",
"Limit",
"parameter",
"into",
"the",
"request",
"args"
] | python | train | 41.75 |
symengine/symengine.py | symengine/utilities.py | https://github.com/symengine/symengine.py/blob/1366cf98ceaade339c5dd24ae3381a0e63ea9dad/symengine/utilities.py#L12-L181 | def symbols(names, **args):
"""
Transform strings into instances of :class:`Symbol` class.
:func:`symbols` function returns a sequence of symbols with names taken
from ``names`` argument, which can be a comma or whitespace delimited
string, or a sequence of strings::
>>> from symengine impor... | [
"def",
"symbols",
"(",
"names",
",",
"*",
"*",
"args",
")",
":",
"result",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"names",
",",
"string_types",
")",
":",
"marker",
"=",
"0",
"literals",
"=",
"[",
"'\\,'",
",",
"'\\:'",
",",
"'\\ '",
"]",
"for",
... | Transform strings into instances of :class:`Symbol` class.
:func:`symbols` function returns a sequence of symbols with names taken
from ``names`` argument, which can be a comma or whitespace delimited
string, or a sequence of strings::
>>> from symengine import symbols
>>> x, y, z = symbols(... | [
"Transform",
"strings",
"into",
"instances",
"of",
":",
"class",
":",
"Symbol",
"class",
".",
":",
"func",
":",
"symbols",
"function",
"returns",
"a",
"sequence",
"of",
"symbols",
"with",
"names",
"taken",
"from",
"names",
"argument",
"which",
"can",
"be",
... | python | train | 36.729412 |
vanheeringen-lab/gimmemotifs | gimmemotifs/motif.py | https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/motif.py#L1149-L1178 | def parse_motifs(motifs):
"""Parse motifs in a variety of formats to return a list of motifs.
Parameters
----------
motifs : list or str
Filename of motif, list of motifs or single Motif instance.
Returns
-------
motifs : list
List of Motif instances.
"""
if isin... | [
"def",
"parse_motifs",
"(",
"motifs",
")",
":",
"if",
"isinstance",
"(",
"motifs",
",",
"six",
".",
"string_types",
")",
":",
"with",
"open",
"(",
"motifs",
")",
"as",
"f",
":",
"if",
"motifs",
".",
"endswith",
"(",
"\"pwm\"",
")",
"or",
"motifs",
".... | Parse motifs in a variety of formats to return a list of motifs.
Parameters
----------
motifs : list or str
Filename of motif, list of motifs or single Motif instance.
Returns
-------
motifs : list
List of Motif instances. | [
"Parse",
"motifs",
"in",
"a",
"variety",
"of",
"formats",
"to",
"return",
"a",
"list",
"of",
"motifs",
"."
] | python | train | 27.933333 |
StackStorm/pybind | pybind/slxos/v17s_1_02/routing_system/router/hide_pim_holder/pim/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/routing_system/router/hide_pim_holder/pim/__init__.py#L509-L530 | def _set_anycast_rp_ip(self, v, load=False):
"""
Setter method for anycast_rp_ip, mapped from YANG variable /routing_system/router/hide_pim_holder/pim/anycast_rp_ip (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_anycast_rp_ip is considered as a private
method... | [
"def",
"_set_anycast_rp_ip",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | Setter method for anycast_rp_ip, mapped from YANG variable /routing_system/router/hide_pim_holder/pim/anycast_rp_ip (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_anycast_rp_ip is considered as a private
method. Backends looking to populate this variable should
d... | [
"Setter",
"method",
"for",
"anycast_rp_ip",
"mapped",
"from",
"YANG",
"variable",
"/",
"routing_system",
"/",
"router",
"/",
"hide_pim_holder",
"/",
"pim",
"/",
"anycast_rp_ip",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"con... | python | train | 122.636364 |
pandas-dev/pandas | pandas/core/indexes/multi.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/multi.py#L1384-L1418 | def get_level_values(self, level):
"""
Return vector of label values for requested level,
equal to the length of the index.
Parameters
----------
level : int or str
``level`` is either the integer position of the level in the
MultiIndex, or the na... | [
"def",
"get_level_values",
"(",
"self",
",",
"level",
")",
":",
"level",
"=",
"self",
".",
"_get_level_number",
"(",
"level",
")",
"values",
"=",
"self",
".",
"_get_level_values",
"(",
"level",
")",
"return",
"values"
] | Return vector of label values for requested level,
equal to the length of the index.
Parameters
----------
level : int or str
``level`` is either the integer position of the level in the
MultiIndex, or the name of the level.
Returns
-------
... | [
"Return",
"vector",
"of",
"label",
"values",
"for",
"requested",
"level",
"equal",
"to",
"the",
"length",
"of",
"the",
"index",
"."
] | python | train | 30.485714 |
shoebot/shoebot | shoebot/grammar/grammar.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L101-L200 | def _run_frame(self, executor, limit=False, iteration=0):
""" Run single frame of the bot
:param source_or_code: path to code to run, or actual code.
:param limit: Time a frame should take to run (float - seconds)
"""
#
# Gets a bit complex here...
#
# No... | [
"def",
"_run_frame",
"(",
"self",
",",
"executor",
",",
"limit",
"=",
"False",
",",
"iteration",
"=",
"0",
")",
":",
"#",
"# Gets a bit complex here...",
"#",
"# Nodebox (which we are trying to be compatible with) supports two",
"# kinds of bot 'dynamic' which has a 'draw' fu... | Run single frame of the bot
:param source_or_code: path to code to run, or actual code.
:param limit: Time a frame should take to run (float - seconds) | [
"Run",
"single",
"frame",
"of",
"the",
"bot"
] | python | valid | 37.4 |
nephila/djangocms-page-meta | djangocms_page_meta/utils.py | https://github.com/nephila/djangocms-page-meta/blob/a38efe3fe3a717d9ad91bfc6aacab90989cd04a4/djangocms_page_meta/utils.py#L22-L143 | def get_page_meta(page, language):
"""
Retrieves all the meta information for the page in the given language
:param page: a Page instance
:param lang: a language code
:return: Meta instance
:type: object
"""
from django.core.cache import cache
from meta.views import Meta
from .... | [
"def",
"get_page_meta",
"(",
"page",
",",
"language",
")",
":",
"from",
"django",
".",
"core",
".",
"cache",
"import",
"cache",
"from",
"meta",
".",
"views",
"import",
"Meta",
"from",
".",
"models",
"import",
"PageMeta",
",",
"TitleMeta",
"try",
":",
"me... | Retrieves all the meta information for the page in the given language
:param page: a Page instance
:param lang: a language code
:return: Meta instance
:type: object | [
"Retrieves",
"all",
"the",
"meta",
"information",
"for",
"the",
"page",
"in",
"the",
"given",
"language"
] | python | train | 43.934426 |
hollenstein/maspy | maspy/peptidemethods.py | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/peptidemethods.py#L42-L128 | def digestInSilico(proteinSequence, cleavageRule='[KR]', missedCleavage=0,
removeNtermM=True, minLength=5, maxLength=55):
"""Returns a list of peptide sequences and cleavage information derived
from an in silico digestion of a polypeptide.
:param proteinSequence: amino acid sequence of t... | [
"def",
"digestInSilico",
"(",
"proteinSequence",
",",
"cleavageRule",
"=",
"'[KR]'",
",",
"missedCleavage",
"=",
"0",
",",
"removeNtermM",
"=",
"True",
",",
"minLength",
"=",
"5",
",",
"maxLength",
"=",
"55",
")",
":",
"passFilter",
"=",
"lambda",
"startPos"... | Returns a list of peptide sequences and cleavage information derived
from an in silico digestion of a polypeptide.
:param proteinSequence: amino acid sequence of the poly peptide to be
digested
:param cleavageRule: cleavage rule expressed in a regular expression, see
:attr:`maspy.constants.... | [
"Returns",
"a",
"list",
"of",
"peptide",
"sequences",
"and",
"cleavage",
"information",
"derived",
"from",
"an",
"in",
"silico",
"digestion",
"of",
"a",
"polypeptide",
"."
] | python | train | 43.977011 |
viewflow/django-fsm | django_fsm/__init__.py | https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L271-L289 | def set_proxy(self, instance, state):
"""
Change class
"""
if state in self.state_proxy:
state_proxy = self.state_proxy[state]
try:
app_label, model_name = state_proxy.split(".")
except ValueError:
# If we can't split, ... | [
"def",
"set_proxy",
"(",
"self",
",",
"instance",
",",
"state",
")",
":",
"if",
"state",
"in",
"self",
".",
"state_proxy",
":",
"state_proxy",
"=",
"self",
".",
"state_proxy",
"[",
"state",
"]",
"try",
":",
"app_label",
",",
"model_name",
"=",
"state_pro... | Change class | [
"Change",
"class"
] | python | train | 32.842105 |
nteract/papermill | papermill/parameterize.py | https://github.com/nteract/papermill/blob/7423a303f3fa22ec6d03edf5fd9700d659b5a6fa/papermill/parameterize.py#L14-L33 | def add_builtin_parameters(parameters):
"""Add built-in parameters to a dictionary of parameters
Parameters
----------
parameters : dict
Dictionary of parameters provided by the user
"""
with_builtin_parameters = {
"pm": {
"run_uuid": str(uuid4()),
"curren... | [
"def",
"add_builtin_parameters",
"(",
"parameters",
")",
":",
"with_builtin_parameters",
"=",
"{",
"\"pm\"",
":",
"{",
"\"run_uuid\"",
":",
"str",
"(",
"uuid4",
"(",
")",
")",
",",
"\"current_datetime_local\"",
":",
"datetime",
".",
"now",
"(",
")",
",",
"\"... | Add built-in parameters to a dictionary of parameters
Parameters
----------
parameters : dict
Dictionary of parameters provided by the user | [
"Add",
"built",
"-",
"in",
"parameters",
"to",
"a",
"dictionary",
"of",
"parameters"
] | python | train | 26.25 |
arne-cl/discoursegraphs | src/discoursegraphs/util.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/util.py#L195-L222 | def create_dir(path):
"""
Creates a directory. Warns, if the directory can't be accessed. Passes,
if the directory already exists.
modified from http://stackoverflow.com/a/600612
Parameters
----------
path : str
path to the directory to be created
"""
import sys
import ... | [
"def",
"create_dir",
"(",
"path",
")",
":",
"import",
"sys",
"import",
"errno",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"exc",
":",
"# Python >2.5",
"if",
"exc",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
":",
... | Creates a directory. Warns, if the directory can't be accessed. Passes,
if the directory already exists.
modified from http://stackoverflow.com/a/600612
Parameters
----------
path : str
path to the directory to be created | [
"Creates",
"a",
"directory",
".",
"Warns",
"if",
"the",
"directory",
"can",
"t",
"be",
"accessed",
".",
"Passes",
"if",
"the",
"directory",
"already",
"exists",
"."
] | python | train | 26.392857 |
NLeSC/noodles | examples/static_sum.py | https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/examples/static_sum.py#L7-L16 | def static_sum(values, limit_n=1000):
"""Example of static sum routine."""
if len(values) < limit_n:
return sum(values)
else:
half = len(values) // 2
return add(
static_sum(values[:half], limit_n),
static_sum(values[half:], limit_n)) | [
"def",
"static_sum",
"(",
"values",
",",
"limit_n",
"=",
"1000",
")",
":",
"if",
"len",
"(",
"values",
")",
"<",
"limit_n",
":",
"return",
"sum",
"(",
"values",
")",
"else",
":",
"half",
"=",
"len",
"(",
"values",
")",
"//",
"2",
"return",
"add",
... | Example of static sum routine. | [
"Example",
"of",
"static",
"sum",
"routine",
"."
] | python | train | 29.3 |
liminspace/dju-image | dju_image/tools.py | https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L75-L92 | def generate_img_id(profile, ext=None, label=None, tmp=False):
"""
Generates img_id.
"""
if ext and not ext.startswith('.'):
ext = '.' + ext
if label:
label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I)
label = re.sub(r'_+', '_', label)
label = label[:60]
retur... | [
"def",
"generate_img_id",
"(",
"profile",
",",
"ext",
"=",
"None",
",",
"label",
"=",
"None",
",",
"tmp",
"=",
"False",
")",
":",
"if",
"ext",
"and",
"not",
"ext",
".",
"startswith",
"(",
"'.'",
")",
":",
"ext",
"=",
"'.'",
"+",
"ext",
"if",
"lab... | Generates img_id. | [
"Generates",
"img_id",
"."
] | python | train | 35.5 |
luckydonald/pytgbot | pytgbot/api_types/sendable/passport.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/passport.py#L351-L363 | def to_array(self):
"""
Serializes this PassportElementErrorReverseSide to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PassportElementErrorReverseSide, self).to_array()
array['source'] = u(self.source) # py2: t... | [
"def",
"to_array",
"(",
"self",
")",
":",
"array",
"=",
"super",
"(",
"PassportElementErrorReverseSide",
",",
"self",
")",
".",
"to_array",
"(",
")",
"array",
"[",
"'source'",
"]",
"=",
"u",
"(",
"self",
".",
"source",
")",
"# py2: type unicode, py3: type st... | Serializes this PassportElementErrorReverseSide to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | [
"Serializes",
"this",
"PassportElementErrorReverseSide",
"to",
"a",
"dictionary",
"."
] | python | train | 45.384615 |
CodyKochmann/strict_functions | strict_functions/cached2.py | https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/cached2.py#L3-L10 | def cached(fn, size=32):
''' this decorator creates a type safe lru_cache
around the decorated function. Unlike
functools.lru_cache, this will not crash when
unhashable arguments are passed to the function'''
assert callable(fn)
assert isinstance(size, int)
return overload(fn)(lru_cache(size... | [
"def",
"cached",
"(",
"fn",
",",
"size",
"=",
"32",
")",
":",
"assert",
"callable",
"(",
"fn",
")",
"assert",
"isinstance",
"(",
"size",
",",
"int",
")",
"return",
"overload",
"(",
"fn",
")",
"(",
"lru_cache",
"(",
"size",
",",
"typed",
"=",
"True"... | this decorator creates a type safe lru_cache
around the decorated function. Unlike
functools.lru_cache, this will not crash when
unhashable arguments are passed to the function | [
"this",
"decorator",
"creates",
"a",
"type",
"safe",
"lru_cache",
"around",
"the",
"decorated",
"function",
".",
"Unlike",
"functools",
".",
"lru_cache",
"this",
"will",
"not",
"crash",
"when",
"unhashable",
"arguments",
"are",
"passed",
"to",
"the",
"function"
... | python | train | 41.375 |
axialmarket/fsq | fsq/path.py | https://github.com/axialmarket/fsq/blob/43b84c292cb8a187599d86753b947cf73248f989/fsq/path.py#L46-L50 | def queue(p_queue, host=None):
'''Construct a path to the queue dir for a queue'''
if host is not None:
return _path(_c.FSQ_QUEUE, root=_path(host, root=hosts(p_queue)))
return _path(p_queue, _c.FSQ_QUEUE) | [
"def",
"queue",
"(",
"p_queue",
",",
"host",
"=",
"None",
")",
":",
"if",
"host",
"is",
"not",
"None",
":",
"return",
"_path",
"(",
"_c",
".",
"FSQ_QUEUE",
",",
"root",
"=",
"_path",
"(",
"host",
",",
"root",
"=",
"hosts",
"(",
"p_queue",
")",
")... | Construct a path to the queue dir for a queue | [
"Construct",
"a",
"path",
"to",
"the",
"queue",
"dir",
"for",
"a",
"queue"
] | python | train | 44.2 |
OpenTreeOfLife/peyotl | peyotl/manip.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/manip.py#L19-L42 | def iter_otus(nexson, nexson_version=None):
"""generator over all otus in all otus group elements.
yields a tuple of 3 items:
otus group ID,
otu ID,
the otu obj
"""
if nexson_version is None:
nexson_version = detect_nexson_version(nexson)
if not _is_by_id_hbf(nexson_v... | [
"def",
"iter_otus",
"(",
"nexson",
",",
"nexson_version",
"=",
"None",
")",
":",
"if",
"nexson_version",
"is",
"None",
":",
"nexson_version",
"=",
"detect_nexson_version",
"(",
"nexson",
")",
"if",
"not",
"_is_by_id_hbf",
"(",
"nexson_version",
")",
":",
"conv... | generator over all otus in all otus group elements.
yields a tuple of 3 items:
otus group ID,
otu ID,
the otu obj | [
"generator",
"over",
"all",
"otus",
"in",
"all",
"otus",
"group",
"elements",
".",
"yields",
"a",
"tuple",
"of",
"3",
"items",
":",
"otus",
"group",
"ID",
"otu",
"ID",
"the",
"otu",
"obj"
] | python | train | 38.958333 |
juiceinc/recipe | recipe/core.py | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L519-L524 | def subquery(self, name=None):
""" The recipe's query as a subquery suitable for use in joins or other
queries.
"""
query = self.query()
return query.subquery(name=name) | [
"def",
"subquery",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"query",
"=",
"self",
".",
"query",
"(",
")",
"return",
"query",
".",
"subquery",
"(",
"name",
"=",
"name",
")"
] | The recipe's query as a subquery suitable for use in joins or other
queries. | [
"The",
"recipe",
"s",
"query",
"as",
"a",
"subquery",
"suitable",
"for",
"use",
"in",
"joins",
"or",
"other",
"queries",
"."
] | python | train | 34 |
blubberdiblub/eztemplate | eztemplate/engines/string_template_engine.py | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/string_template_engine.py#L25-L34 | def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
mapping = {name: self.str(value, tolerant=self.tolerant)
for name, value in mapping.items()
if value is not None or self.tolerant}
if self.tolerant:
return self.t... | [
"def",
"apply",
"(",
"self",
",",
"mapping",
")",
":",
"mapping",
"=",
"{",
"name",
":",
"self",
".",
"str",
"(",
"value",
",",
"tolerant",
"=",
"self",
".",
"tolerant",
")",
"for",
"name",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
"... | Apply a mapping of name-value-pairs to a template. | [
"Apply",
"a",
"mapping",
"of",
"name",
"-",
"value",
"-",
"pairs",
"to",
"a",
"template",
"."
] | python | train | 39.3 |
Esri/ArcREST | src/arcrest/ags/_gpobjects.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_gpobjects.py#L560-L572 | def fromJSON(value):
"""loads the GP object from a JSON string """
j = json.loads(value)
v = GPLong()
if "defaultValue" in j:
v.value = j['defaultValue']
else:
v.value = j['value']
if 'paramName' in j:
v.paramName = j['paramName']
... | [
"def",
"fromJSON",
"(",
"value",
")",
":",
"j",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"v",
"=",
"GPLong",
"(",
")",
"if",
"\"defaultValue\"",
"in",
"j",
":",
"v",
".",
"value",
"=",
"j",
"[",
"'defaultValue'",
"]",
"else",
":",
"v",
".",
... | loads the GP object from a JSON string | [
"loads",
"the",
"GP",
"object",
"from",
"a",
"JSON",
"string"
] | python | train | 29.307692 |
apache/spark | python/pyspark/rdd.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2455-L2468 | def mapPartitions(self, f, preservesPartitioning=False):
"""
.. note:: Experimental
Returns a new RDD by applying a function to each partition of the wrapped RDD,
where tasks are launched together in a barrier stage.
The interface is the same as :func:`RDD.mapPartitions`.
... | [
"def",
"mapPartitions",
"(",
"self",
",",
"f",
",",
"preservesPartitioning",
"=",
"False",
")",
":",
"def",
"func",
"(",
"s",
",",
"iterator",
")",
":",
"return",
"f",
"(",
"iterator",
")",
"return",
"PipelinedRDD",
"(",
"self",
".",
"rdd",
",",
"func"... | .. note:: Experimental
Returns a new RDD by applying a function to each partition of the wrapped RDD,
where tasks are launched together in a barrier stage.
The interface is the same as :func:`RDD.mapPartitions`.
Please see the API doc there.
.. versionadded:: 2.4.0 | [
"..",
"note",
"::",
"Experimental"
] | python | train | 38 |
raphaelvallat/pingouin | pingouin/plotting.py | https://github.com/raphaelvallat/pingouin/blob/58b19fa4fffbfe09d58b456e3926a148249e4d9b/pingouin/plotting.py#L21-L172 | def plot_blandaltman(x, y, agreement=1.96, confidence=.95, figsize=(5, 4),
dpi=100, ax=None):
"""
Generate a Bland-Altman plot to compare two sets of measurements.
Parameters
----------
x, y : np.array or list
First and second measurements.
agreement : float
... | [
"def",
"plot_blandaltman",
"(",
"x",
",",
"y",
",",
"agreement",
"=",
"1.96",
",",
"confidence",
"=",
".95",
",",
"figsize",
"=",
"(",
"5",
",",
"4",
")",
",",
"dpi",
"=",
"100",
",",
"ax",
"=",
"None",
")",
":",
"# Safety check",
"x",
"=",
"np",... | Generate a Bland-Altman plot to compare two sets of measurements.
Parameters
----------
x, y : np.array or list
First and second measurements.
agreement : float
Multiple of the standard deviation to plot limit of agreement bounds.
The defaults is 1.96.
confidence : float
... | [
"Generate",
"a",
"Bland",
"-",
"Altman",
"plot",
"to",
"compare",
"two",
"sets",
"of",
"measurements",
"."
] | python | train | 37.730263 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L145-L161 | def extend(self, protocol: Union[Iterable[Dict], 'Pipeline']) -> 'Pipeline':
"""Add another pipeline to the end of the current pipeline.
:param protocol: An iterable of dictionaries (or another Pipeline)
:return: This pipeline for fluid query building
Example:
>>> p1 = Pipelin... | [
"def",
"extend",
"(",
"self",
",",
"protocol",
":",
"Union",
"[",
"Iterable",
"[",
"Dict",
"]",
",",
"'Pipeline'",
"]",
")",
"->",
"'Pipeline'",
":",
"for",
"data",
"in",
"protocol",
":",
"name",
",",
"args",
",",
"kwargs",
"=",
"_get_protocol_tuple",
... | Add another pipeline to the end of the current pipeline.
:param protocol: An iterable of dictionaries (or another Pipeline)
:return: This pipeline for fluid query building
Example:
>>> p1 = Pipeline.from_functions(['enrich_protein_and_rna_origins'])
>>> p2 = Pipeline.from_func... | [
"Add",
"another",
"pipeline",
"to",
"the",
"end",
"of",
"the",
"current",
"pipeline",
"."
] | python | train | 36.235294 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L282-L295 | def _select_row_by_column_value(tree_view, list_store, column, value):
"""Helper method to select a tree view row
:param Gtk.TreeView tree_view: Tree view who's row is to be selected
:param Gtk.ListStore list_store: List store of the tree view
:param int column: Column in which the valu... | [
"def",
"_select_row_by_column_value",
"(",
"tree_view",
",",
"list_store",
",",
"column",
",",
"value",
")",
":",
"for",
"row_num",
",",
"iter_elem",
"in",
"enumerate",
"(",
"list_store",
")",
":",
"if",
"iter_elem",
"[",
"column",
"]",
"==",
"value",
":",
... | Helper method to select a tree view row
:param Gtk.TreeView tree_view: Tree view who's row is to be selected
:param Gtk.ListStore list_store: List store of the tree view
:param int column: Column in which the value is searched
:param value: Value to search for
:returns: Row of l... | [
"Helper",
"method",
"to",
"select",
"a",
"tree",
"view",
"row"
] | python | train | 44.642857 |
hyperledger-archives/indy-client | sovrin_client/cli/cli.py | https://github.com/hyperledger-archives/indy-client/blob/b5633dd7767b4aaf08f622181f3937a104b290fb/sovrin_client/cli/cli.py#L468-L485 | def _getRole(self, matchedVars):
"""
:param matchedVars:
:return: NULL or the role's integer value
"""
role = matchedVars.get(ROLE)
if role is not None and role.strip() == '':
role = NULL
else:
valid = Authoriser.isValidRoleName(role)
... | [
"def",
"_getRole",
"(",
"self",
",",
"matchedVars",
")",
":",
"role",
"=",
"matchedVars",
".",
"get",
"(",
"ROLE",
")",
"if",
"role",
"is",
"not",
"None",
"and",
"role",
".",
"strip",
"(",
")",
"==",
"''",
":",
"role",
"=",
"NULL",
"else",
":",
"... | :param matchedVars:
:return: NULL or the role's integer value | [
":",
"param",
"matchedVars",
":",
":",
"return",
":",
"NULL",
"or",
"the",
"role",
"s",
"integer",
"value"
] | python | train | 34.555556 |
grangier/python-goose | goose/extractors/content.py | https://github.com/grangier/python-goose/blob/09023ec9f5ef26a628a2365616c0a7c864f0ecea/goose/extractors/content.py#L37-L47 | def get_language(self):
"""\
Returns the language is by the article or
the configuration language
"""
# we don't want to force the target language
# so we use the article.meta_lang
if self.config.use_meta_language:
if self.article.meta_lang:
... | [
"def",
"get_language",
"(",
"self",
")",
":",
"# we don't want to force the target language",
"# so we use the article.meta_lang",
"if",
"self",
".",
"config",
".",
"use_meta_language",
":",
"if",
"self",
".",
"article",
".",
"meta_lang",
":",
"return",
"self",
".",
... | \
Returns the language is by the article or
the configuration language | [
"\\",
"Returns",
"the",
"language",
"is",
"by",
"the",
"article",
"or",
"the",
"configuration",
"language"
] | python | train | 35.636364 |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L439-L530 | def buildRootname(filename, ext=None):
"""
Build a new rootname for an existing file and given extension.
Any user supplied extensions to use for searching for file need to be
provided as a list of extensions.
Examples
--------
::
>>> rootname = buildRootname(filename, ext=['_dth... | [
"def",
"buildRootname",
"(",
"filename",
",",
"ext",
"=",
"None",
")",
":",
"if",
"filename",
"in",
"[",
"''",
",",
"' '",
",",
"None",
"]",
":",
"return",
"None",
"fpath",
",",
"fname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
... | Build a new rootname for an existing file and given extension.
Any user supplied extensions to use for searching for file need to be
provided as a list of extensions.
Examples
--------
::
>>> rootname = buildRootname(filename, ext=['_dth.fits']) # doctest: +SKIP | [
"Build",
"a",
"new",
"rootname",
"for",
"an",
"existing",
"file",
"and",
"given",
"extension",
"."
] | python | train | 30.021739 |
jtauber/sebastian | sebastian/core/elements.py | https://github.com/jtauber/sebastian/blob/4e460c3aeab332b45c74fe78e65e76ec87d5cfa8/sebastian/core/elements.py#L84-L125 | def display(self, format="png"):
"""
Return an object that can be used to display this sequence.
This is used for IPython Notebook.
:param format: "png" or "svg"
"""
from sebastian.core.transforms import lilypond
seq = HSeq(self) | lilypond()
lily_output... | [
"def",
"display",
"(",
"self",
",",
"format",
"=",
"\"png\"",
")",
":",
"from",
"sebastian",
".",
"core",
".",
"transforms",
"import",
"lilypond",
"seq",
"=",
"HSeq",
"(",
"self",
")",
"|",
"lilypond",
"(",
")",
"lily_output",
"=",
"write_lilypond",
".",... | Return an object that can be used to display this sequence.
This is used for IPython Notebook.
:param format: "png" or "svg" | [
"Return",
"an",
"object",
"that",
"can",
"be",
"used",
"to",
"display",
"this",
"sequence",
".",
"This",
"is",
"used",
"for",
"IPython",
"Notebook",
"."
] | python | train | 38.02381 |
jldbc/pybaseball | pybaseball/playerid_lookup.py | https://github.com/jldbc/pybaseball/blob/085ea26bfd1b5f5926d79d4fac985c88278115f2/pybaseball/playerid_lookup.py#L46-L70 | def playerid_reverse_lookup(player_ids, key_type=None):
"""Retrieve a table of player information given a list of player ids
:param player_ids: list of player ids
:type player_ids: list
:param key_type: name of the key type being looked up (one of "mlbam", "retro", "bbref", or "fangraphs")
:type ke... | [
"def",
"playerid_reverse_lookup",
"(",
"player_ids",
",",
"key_type",
"=",
"None",
")",
":",
"key_types",
"=",
"(",
"'mlbam'",
",",
"'retro'",
",",
"'bbref'",
",",
"'fangraphs'",
",",
")",
"if",
"not",
"key_type",
":",
"key_type",
"=",
"key_types",
"[",
"0... | Retrieve a table of player information given a list of player ids
:param player_ids: list of player ids
:type player_ids: list
:param key_type: name of the key type being looked up (one of "mlbam", "retro", "bbref", or "fangraphs")
:type key_type: str
:rtype: :class:`pandas.core.frame.DataFrame` | [
"Retrieve",
"a",
"table",
"of",
"player",
"information",
"given",
"a",
"list",
"of",
"player",
"ids"
] | python | train | 35.92 |
basho/riak-python-client | riak/transports/pool.py | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/transports/pool.py#L125-L160 | def acquire(self, _filter=None, default=None):
"""
acquire(_filter=None, default=None)
Claims a resource from the pool for manual use. Resources are
created as needed when all members of the pool are claimed or
the pool is empty. Most of the time you will want to use
:me... | [
"def",
"acquire",
"(",
"self",
",",
"_filter",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"_filter",
":",
"def",
"_filter",
"(",
"obj",
")",
":",
"return",
"True",
"elif",
"not",
"callable",
"(",
"_filter",
")",
":",
"raise",
... | acquire(_filter=None, default=None)
Claims a resource from the pool for manual use. Resources are
created as needed when all members of the pool are claimed or
the pool is empty. Most of the time you will want to use
:meth:`transaction`.
:param _filter: a filter that can be use... | [
"acquire",
"(",
"_filter",
"=",
"None",
"default",
"=",
"None",
")"
] | python | train | 36.444444 |
NoviceLive/intellicoder | intellicoder/utils.py | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/utils.py#L181-L186 | def read_files(filenames, with_name=False):
"""Read many files."""
text = [read_file(filename) for filename in filenames]
if with_name:
return dict(zip(filenames, text))
return text | [
"def",
"read_files",
"(",
"filenames",
",",
"with_name",
"=",
"False",
")",
":",
"text",
"=",
"[",
"read_file",
"(",
"filename",
")",
"for",
"filename",
"in",
"filenames",
"]",
"if",
"with_name",
":",
"return",
"dict",
"(",
"zip",
"(",
"filenames",
",",
... | Read many files. | [
"Read",
"many",
"files",
"."
] | python | train | 33.333333 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/mp_tile.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/mp_tile.py#L437-L444 | def coord_from_area(self, x, y, lat, lon, width, ground_width):
'''return (lat,lon) for a pixel in an area image'''
pixel_width = ground_width / float(width)
dx = x * pixel_width
dy = y * pixel_width
return mp_util.gps_offset(lat, lon, dx, -dy) | [
"def",
"coord_from_area",
"(",
"self",
",",
"x",
",",
"y",
",",
"lat",
",",
"lon",
",",
"width",
",",
"ground_width",
")",
":",
"pixel_width",
"=",
"ground_width",
"/",
"float",
"(",
"width",
")",
"dx",
"=",
"x",
"*",
"pixel_width",
"dy",
"=",
"y",
... | return (lat,lon) for a pixel in an area image | [
"return",
"(",
"lat",
"lon",
")",
"for",
"a",
"pixel",
"in",
"an",
"area",
"image"
] | python | train | 31.125 |
Kronuz/pyScss | scss/cssdefs.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L208-L224 | def convert_units_to_base_units(units):
"""Convert a set of units into a set of "base" units.
Returns a 2-tuple of `factor, new_units`.
"""
total_factor = 1
new_units = []
for unit in units:
if unit not in BASE_UNIT_CONVERSIONS:
continue
factor, new_unit = BASE_UNIT... | [
"def",
"convert_units_to_base_units",
"(",
"units",
")",
":",
"total_factor",
"=",
"1",
"new_units",
"=",
"[",
"]",
"for",
"unit",
"in",
"units",
":",
"if",
"unit",
"not",
"in",
"BASE_UNIT_CONVERSIONS",
":",
"continue",
"factor",
",",
"new_unit",
"=",
"BASE_... | Convert a set of units into a set of "base" units.
Returns a 2-tuple of `factor, new_units`. | [
"Convert",
"a",
"set",
"of",
"units",
"into",
"a",
"set",
"of",
"base",
"units",
"."
] | python | train | 26.588235 |
jmgilman/Neolib | neolib/pyamf/util/pure.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L370-L394 | def write_24bit_uint(self, n):
"""
Writes a 24 bit unsigned integer to the stream.
@since: 0.4
@param n: 24 bit unsigned integer
@type n: C{int}
@raise TypeError: Unexpected type for int C{n}.
@raise OverflowError: Not in range.
"""
if type(n) not... | [
"def",
"write_24bit_uint",
"(",
"self",
",",
"n",
")",
":",
"if",
"type",
"(",
"n",
")",
"not",
"in",
"python",
".",
"int_types",
":",
"raise",
"TypeError",
"(",
"'expected an int (got:%r)'",
"%",
"(",
"type",
"(",
"n",
")",
",",
")",
")",
"if",
"not... | Writes a 24 bit unsigned integer to the stream.
@since: 0.4
@param n: 24 bit unsigned integer
@type n: C{int}
@raise TypeError: Unexpected type for int C{n}.
@raise OverflowError: Not in range. | [
"Writes",
"a",
"24",
"bit",
"unsigned",
"integer",
"to",
"the",
"stream",
"."
] | python | train | 27.32 |
googleapis/google-cloud-python | datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L2157-L2249 | def create_instruction(
self,
parent,
instruction,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates an instruction for how data should be labeled.
Example:
... | [
"def",
"create_instruction",
"(",
"self",
",",
"parent",
",",
"instruction",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
... | Creates an instruction for how data should be labeled.
Example:
>>> from google.cloud import datalabeling_v1beta1
>>>
>>> client = datalabeling_v1beta1.DataLabelingServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
... | [
"Creates",
"an",
"instruction",
"for",
"how",
"data",
"should",
"be",
"labeled",
"."
] | python | train | 41.27957 |
HttpRunner/HttpRunner | httprunner/validator.py | https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/validator.py#L141-L171 | def get_uniform_comparator(comparator):
""" convert comparator alias to uniform name
"""
if comparator in ["eq", "equals", "==", "is"]:
return "equals"
elif comparator in ["lt", "less_than"]:
return "less_than"
elif comparator in ["le", "less_than_or_equals"]:
return "less_th... | [
"def",
"get_uniform_comparator",
"(",
"comparator",
")",
":",
"if",
"comparator",
"in",
"[",
"\"eq\"",
",",
"\"equals\"",
",",
"\"==\"",
",",
"\"is\"",
"]",
":",
"return",
"\"equals\"",
"elif",
"comparator",
"in",
"[",
"\"lt\"",
",",
"\"less_than\"",
"]",
":... | convert comparator alias to uniform name | [
"convert",
"comparator",
"alias",
"to",
"uniform",
"name"
] | python | train | 43.290323 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/debug.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/debug.py#L810-L824 | def detach_from_all(self, bIgnoreExceptions = False):
"""
Detaches from all processes currently being debugged.
@note: To better handle last debugging event, call L{stop} instead.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may... | [
"def",
"detach_from_all",
"(",
"self",
",",
"bIgnoreExceptions",
"=",
"False",
")",
":",
"for",
"pid",
"in",
"self",
".",
"get_debugee_pids",
"(",
")",
":",
"self",
".",
"detach",
"(",
"pid",
",",
"bIgnoreExceptions",
"=",
"bIgnoreExceptions",
")"
] | Detaches from all processes currently being debugged.
@note: To better handle last debugging event, call L{stop} instead.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when detaching.
@raise WindowsError: Raise... | [
"Detaches",
"from",
"all",
"processes",
"currently",
"being",
"debugged",
"."
] | python | train | 38.666667 |
CamDavidsonPilon/lifelines | lifelines/fitters/__init__.py | https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/fitters/__init__.py#L1032-L1036 | def confidence_interval_hazard_(self):
"""
The confidence interval of the hazard.
"""
return self._compute_confidence_bounds_of_transform(self._hazard, self.alpha, self._ci_labels) | [
"def",
"confidence_interval_hazard_",
"(",
"self",
")",
":",
"return",
"self",
".",
"_compute_confidence_bounds_of_transform",
"(",
"self",
".",
"_hazard",
",",
"self",
".",
"alpha",
",",
"self",
".",
"_ci_labels",
")"
] | The confidence interval of the hazard. | [
"The",
"confidence",
"interval",
"of",
"the",
"hazard",
"."
] | python | train | 41.6 |
django-danceschool/django-danceschool | danceschool/core/models.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L83-L89 | def save(self, *args, **kwargs):
''' Just add "s" if no plural name given. '''
if not self.pluralName:
self.pluralName = self.name + 's'
super(self.__class__, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"pluralName",
":",
"self",
".",
"pluralName",
"=",
"self",
".",
"name",
"+",
"'s'",
"super",
"(",
"self",
".",
"__class__",
",",
"self",
")... | Just add "s" if no plural name given. | [
"Just",
"add",
"s",
"if",
"no",
"plural",
"name",
"given",
"."
] | python | train | 31.142857 |
opennode/waldur-core | waldur_core/cost_tracking/admin.py | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/admin.py#L106-L133 | def reinit_configurations(self, request):
""" Re-initialize configuration for resource if it has been changed.
This method should be called if resource consumption strategy was changed.
"""
now = timezone.now()
# Step 1. Collect all resources with changed configuration.
... | [
"def",
"reinit_configurations",
"(",
"self",
",",
"request",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"# Step 1. Collect all resources with changed configuration.",
"changed_resources",
"=",
"[",
"]",
"for",
"resource_model",
"in",
"CostTrackingRegister",... | Re-initialize configuration for resource if it has been changed.
This method should be called if resource consumption strategy was changed. | [
"Re",
"-",
"initialize",
"configuration",
"for",
"resource",
"if",
"it",
"has",
"been",
"changed",
"."
] | python | train | 51.5 |
chaoss/grimoirelab-elk | grimoire_elk/enriched/enrich.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L515-L529 | def add_project_levels(cls, project):
""" Add project sub levels extra items """
eitem_path = ''
eitem_project_levels = {}
if project is not None:
subprojects = project.split('.')
for i in range(0, len(subprojects)):
if i > 0:
... | [
"def",
"add_project_levels",
"(",
"cls",
",",
"project",
")",
":",
"eitem_path",
"=",
"''",
"eitem_project_levels",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"subprojects",
"=",
"project",
".",
"split",
"(",
"'.'",
")",
"for",
"i",
"in",
... | Add project sub levels extra items | [
"Add",
"project",
"sub",
"levels",
"extra",
"items"
] | python | train | 32.066667 |
tmontaigu/pylas | pylas/lasreader.py | https://github.com/tmontaigu/pylas/blob/8335a1a7d7677f0e4bc391bb6fa3c75b42ed5b06/pylas/lasreader.py#L97-L117 | def _read_points(self, vlrs):
""" private function to handle reading of the points record parts
of the las file.
the header is needed for the point format and number of points
the vlrs are need to get the potential laszip vlr as well as the extra bytes vlr
"""
try:
... | [
"def",
"_read_points",
"(",
"self",
",",
"vlrs",
")",
":",
"try",
":",
"extra_dims",
"=",
"vlrs",
".",
"get",
"(",
"\"ExtraBytesVlr\"",
")",
"[",
"0",
"]",
".",
"type_of_extra_dims",
"(",
")",
"except",
"IndexError",
":",
"extra_dims",
"=",
"None",
"poin... | private function to handle reading of the points record parts
of the las file.
the header is needed for the point format and number of points
the vlrs are need to get the potential laszip vlr as well as the extra bytes vlr | [
"private",
"function",
"to",
"handle",
"reading",
"of",
"the",
"points",
"record",
"parts",
"of",
"the",
"las",
"file",
"."
] | python | test | 41.714286 |
biocore-ntnu/epic | epic/utils/find_readlength.py | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/utils/find_readlength.py#L16-L55 | def find_readlength(args):
# type: (Namespace) -> int
"""Estimate length of reads based on 10000 first."""
try:
bed_file = args.treatment[0]
except AttributeError:
bed_file = args.infiles[0]
filereader = "cat "
if bed_file.endswith(".gz") and search("linux", platform, IGNORECAS... | [
"def",
"find_readlength",
"(",
"args",
")",
":",
"# type: (Namespace) -> int",
"try",
":",
"bed_file",
"=",
"args",
".",
"treatment",
"[",
"0",
"]",
"except",
"AttributeError",
":",
"bed_file",
"=",
"args",
".",
"infiles",
"[",
"0",
"]",
"filereader",
"=",
... | Estimate length of reads based on 10000 first. | [
"Estimate",
"length",
"of",
"reads",
"based",
"on",
"10000",
"first",
"."
] | python | train | 31.45 |
DistrictDataLabs/yellowbrick | yellowbrick/cluster/icdm.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L320-L330 | def _score_clusters(self, X, y=None):
"""
Determines the "scores" of the cluster, the metric that determines the
size of the cluster visualized on the visualization.
"""
stype = self.scoring.lower() # scoring method name
if stype == "membership":
return np.bi... | [
"def",
"_score_clusters",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"stype",
"=",
"self",
".",
"scoring",
".",
"lower",
"(",
")",
"# scoring method name",
"if",
"stype",
"==",
"\"membership\"",
":",
"return",
"np",
".",
"bincount",
"(",
"... | Determines the "scores" of the cluster, the metric that determines the
size of the cluster visualized on the visualization. | [
"Determines",
"the",
"scores",
"of",
"the",
"cluster",
"the",
"metric",
"that",
"determines",
"the",
"size",
"of",
"the",
"cluster",
"visualized",
"on",
"the",
"visualization",
"."
] | python | train | 38.363636 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/addons/guerilla/guerillamgmt.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L150-L165 | def create_seq(self, ):
"""Create a sequence and store it in the self.sequence
:returns: None
:rtype: None
:raises: None
"""
name = self.name_le.text()
desc = self.desc_pte.toPlainText()
try:
seq = djadapter.models.Sequence(name=name, project=... | [
"def",
"create_seq",
"(",
"self",
",",
")",
":",
"name",
"=",
"self",
".",
"name_le",
".",
"text",
"(",
")",
"desc",
"=",
"self",
".",
"desc_pte",
".",
"toPlainText",
"(",
")",
"try",
":",
"seq",
"=",
"djadapter",
".",
"models",
".",
"Sequence",
"(... | Create a sequence and store it in the self.sequence
:returns: None
:rtype: None
:raises: None | [
"Create",
"a",
"sequence",
"and",
"store",
"it",
"in",
"the",
"self",
".",
"sequence"
] | python | train | 30.8125 |
data-8/datascience | datascience/tables.py | https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/tables.py#L288-L300 | def values(self):
"""Return data in `self` as a numpy array.
If all columns are the same dtype, the resulting array
will have this dtype. If there are >1 dtypes in columns,
then the resulting array will have dtype `object`.
"""
dtypes = [col.dtype for col in self.columns... | [
"def",
"values",
"(",
"self",
")",
":",
"dtypes",
"=",
"[",
"col",
".",
"dtype",
"for",
"col",
"in",
"self",
".",
"columns",
"]",
"if",
"len",
"(",
"set",
"(",
"dtypes",
")",
")",
">",
"1",
":",
"dtype",
"=",
"object",
"else",
":",
"dtype",
"="... | Return data in `self` as a numpy array.
If all columns are the same dtype, the resulting array
will have this dtype. If there are >1 dtypes in columns,
then the resulting array will have dtype `object`. | [
"Return",
"data",
"in",
"self",
"as",
"a",
"numpy",
"array",
"."
] | python | train | 35.461538 |
TC01/python-xkcd | xkcd.py | https://github.com/TC01/python-xkcd/blob/6998d4073507eea228185e02ad1d9071c77fa955/xkcd.py#L277-L317 | def download(self, output="", outputFile="", silent=True):
""" Downloads the image of the comic onto your computer.
Arguments:
output: the output directory where comics will be downloaded to. The
default argument for 'output is the empty string; if the empty
string is passed, it defaults to a "Downloa... | [
"def",
"download",
"(",
"self",
",",
"output",
"=",
"\"\"",
",",
"outputFile",
"=",
"\"\"",
",",
"silent",
"=",
"True",
")",
":",
"image",
"=",
"urllib",
".",
"urlopen",
"(",
"self",
".",
"imageLink",
")",
".",
"read",
"(",
")",
"#Process optional inpu... | Downloads the image of the comic onto your computer.
Arguments:
output: the output directory where comics will be downloaded to. The
default argument for 'output is the empty string; if the empty
string is passed, it defaults to a "Downloads" directory in your home folder
(this directory will be cre... | [
"Downloads",
"the",
"image",
"of",
"the",
"comic",
"onto",
"your",
"computer",
"."
] | python | train | 39.463415 |
explosion/spaCy | bin/ud/run_eval.py | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L62-L68 | def get_freq_tuples(my_list, print_total_threshold):
""" Turn a list of errors into frequency-sorted tuples thresholded by a certain total number """
d = {}
for token in my_list:
d.setdefault(token, 0)
d[token] += 1
return sorted(d.items(), key=operator.itemgetter(1), reverse=True)[:prin... | [
"def",
"get_freq_tuples",
"(",
"my_list",
",",
"print_total_threshold",
")",
":",
"d",
"=",
"{",
"}",
"for",
"token",
"in",
"my_list",
":",
"d",
".",
"setdefault",
"(",
"token",
",",
"0",
")",
"d",
"[",
"token",
"]",
"+=",
"1",
"return",
"sorted",
"(... | Turn a list of errors into frequency-sorted tuples thresholded by a certain total number | [
"Turn",
"a",
"list",
"of",
"errors",
"into",
"frequency",
"-",
"sorted",
"tuples",
"thresholded",
"by",
"a",
"certain",
"total",
"number"
] | python | train | 47.428571 |
pmacosta/peng | docs/support/ptypes.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/ptypes.py#L171-L202 | def touchstone_data(obj):
r"""
Validate if an object is an :ref:`TouchstoneData` pseudo-type object.
:param obj: Object
:type obj: any
:raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The
token \*[argument_name]\* is replaced by the name of the argument the
contract ... | [
"def",
"touchstone_data",
"(",
"obj",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
")",
"or",
"(",
"isinstance",
"(",
"obj",
",",
"dict",
")",
"and",
"(",
"sorted",
"(",
"obj",
".",
"keys",
"(",
")",
")",
"!=",
"sorted"... | r"""
Validate if an object is an :ref:`TouchstoneData` pseudo-type object.
:param obj: Object
:type obj: any
:raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The
token \*[argument_name]\* is replaced by the name of the argument the
contract is attached to
:rtype: No... | [
"r",
"Validate",
"if",
"an",
"object",
"is",
"an",
":",
"ref",
":",
"TouchstoneData",
"pseudo",
"-",
"type",
"object",
"."
] | python | test | 41.625 |
dmlc/gluon-nlp | scripts/sentiment_analysis/text_cnn.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/text_cnn.py#L48-L60 | def init(textCNN, vocab, model_mode, context, lr):
"""Initialize parameters."""
textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True)
if model_mode != 'rand':
textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec)
if model_mode == 'multichannel':
textCNN.embedding_... | [
"def",
"init",
"(",
"textCNN",
",",
"vocab",
",",
"model_mode",
",",
"context",
",",
"lr",
")",
":",
"textCNN",
".",
"initialize",
"(",
"mx",
".",
"init",
".",
"Xavier",
"(",
")",
",",
"ctx",
"=",
"context",
",",
"force_reinit",
"=",
"True",
")",
"... | Initialize parameters. | [
"Initialize",
"parameters",
"."
] | python | train | 52.307692 |
bd808/python-iptools | iptools/ipv4.py | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv4.py#L313-L352 | def validate_subnet(s):
"""Validate a dotted-quad ip address including a netmask.
The string is considered a valid dotted-quad address with netmask if it
consists of one to four octets (0-255) seperated by periods (.) followed
by a forward slash (/) and a subnet bitmask which is expressed in
dotted... | [
"def",
"validate_subnet",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"if",
"'/'",
"in",
"s",
":",
"start",
",",
"mask",
"=",
"s",
".",
"split",
"(",
"'/'",
",",
"2",
")",
"return",
"validate_ip",
"(",
"start",
... | Validate a dotted-quad ip address including a netmask.
The string is considered a valid dotted-quad address with netmask if it
consists of one to four octets (0-255) seperated by periods (.) followed
by a forward slash (/) and a subnet bitmask which is expressed in
dotted-quad format.
>>> validat... | [
"Validate",
"a",
"dotted",
"-",
"quad",
"ip",
"address",
"including",
"a",
"netmask",
"."
] | python | train | 30.75 |
subdownloader/subdownloader | subdownloader/video2.py | https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/video2.py#L131-L138 | def get_osdb_hash(self):
"""
Get the hash of this local videofile
:return: hash as string
"""
if self._osdb_hash is None:
self._osdb_hash = self._calculate_osdb_hash()
return self._osdb_hash | [
"def",
"get_osdb_hash",
"(",
"self",
")",
":",
"if",
"self",
".",
"_osdb_hash",
"is",
"None",
":",
"self",
".",
"_osdb_hash",
"=",
"self",
".",
"_calculate_osdb_hash",
"(",
")",
"return",
"self",
".",
"_osdb_hash"
] | Get the hash of this local videofile
:return: hash as string | [
"Get",
"the",
"hash",
"of",
"this",
"local",
"videofile",
":",
"return",
":",
"hash",
"as",
"string"
] | python | train | 30.375 |
autokey/autokey | lib/autokey/scripting.py | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L841-L857 | def get_selection(self):
"""
Read text from the X selection
Usage: C{clipboard.get_selection()}
@return: text contents of the mouse selection
@rtype: C{str}
@raise Exception: if no text was found in the selection
"""
Gdk.threads_enter()
t... | [
"def",
"get_selection",
"(",
"self",
")",
":",
"Gdk",
".",
"threads_enter",
"(",
")",
"text",
"=",
"self",
".",
"selection",
".",
"wait_for_text",
"(",
")",
"Gdk",
".",
"threads_leave",
"(",
")",
"if",
"text",
"is",
"not",
"None",
":",
"return",
"text"... | Read text from the X selection
Usage: C{clipboard.get_selection()}
@return: text contents of the mouse selection
@rtype: C{str}
@raise Exception: if no text was found in the selection | [
"Read",
"text",
"from",
"the",
"X",
"selection",
"Usage",
":",
"C",
"{",
"clipboard",
".",
"get_selection",
"()",
"}"
] | python | train | 29.117647 |
dsoprea/PySchedules | pyschedules/examples/read.py | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/examples/read.py#L86-L96 | def new_program(self, _id, series, title, subtitle, description, mpaaRating,
starRating, runTime, year, showType, colorCode,
originalAirDate, syndicatedEpisodeNumber, advisories):
"""Callback run for each new program entry"""
if self.__v_program:
# [Pro... | [
"def",
"new_program",
"(",
"self",
",",
"_id",
",",
"series",
",",
"title",
",",
"subtitle",
",",
"description",
",",
"mpaaRating",
",",
"starRating",
",",
"runTime",
",",
"year",
",",
"showType",
",",
"colorCode",
",",
"originalAirDate",
",",
"syndicatedEpi... | Callback run for each new program entry | [
"Callback",
"run",
"for",
"each",
"new",
"program",
"entry"
] | python | train | 72.090909 |
python-diamond/Diamond | src/collectors/diskusage/diskusage.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/diskusage/diskusage.py#L54-L70 | def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(DiskUsageCollector, self).get_default_config()
config.update({
'path': 'iostat',
'devices': ('PhysicalDrive[0-9]+$' +
'|md[0-9]+$' +
... | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"DiskUsageCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'path'",
":",
"'iostat'",
",",
"'devices'",
":",
"(",
"'Physic... | Returns the default collector settings | [
"Returns",
"the",
"default",
"collector",
"settings"
] | python | train | 33.941176 |
etcher-be/emiz | emiz/avwx/translate.py | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/translate.py#L336-L359 | def taf(wxdata: TafData, units: Units) -> TafTrans:
"""
Translate the results of taf.parse
Keys: Forecast, Min-Temp, Max-Temp
Forecast keys: Wind, Visibility, Clouds, Altimeter, Wind-Shear, Turbulance, Icing, Other
"""
translations = {'forecast': []} # type: ignore
for line in wxdata.fore... | [
"def",
"taf",
"(",
"wxdata",
":",
"TafData",
",",
"units",
":",
"Units",
")",
"->",
"TafTrans",
":",
"translations",
"=",
"{",
"'forecast'",
":",
"[",
"]",
"}",
"# type: ignore",
"for",
"line",
"in",
"wxdata",
".",
"forecast",
":",
"trans",
"=",
"share... | Translate the results of taf.parse
Keys: Forecast, Min-Temp, Max-Temp
Forecast keys: Wind, Visibility, Clouds, Altimeter, Wind-Shear, Turbulance, Icing, Other | [
"Translate",
"the",
"results",
"of",
"taf",
".",
"parse"
] | python | train | 52.666667 |
turicas/rows | rows/plugins/txt.py | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/txt.py#L130-L179 | def import_from_txt(
filename_or_fobj, encoding="utf-8", frame_style=FRAME_SENTINEL, *args, **kwargs
):
"""Return a rows.Table created from imported TXT file."""
# TODO: (maybe)
# enable parsing of non-fixed-width-columns
# with old algorithm - that would just split columns
# at the vertical se... | [
"def",
"import_from_txt",
"(",
"filename_or_fobj",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"frame_style",
"=",
"FRAME_SENTINEL",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: (maybe)",
"# enable parsing of non-fixed-width-columns",
"# with old algorithm ... | Return a rows.Table created from imported TXT file. | [
"Return",
"a",
"rows",
".",
"Table",
"created",
"from",
"imported",
"TXT",
"file",
"."
] | python | train | 32.86 |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L14597-L14616 | def vdotg(v1, v2, ndim):
"""
Compute the dot product of two double precision vectors of
arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdotg_c.html
:param v1: First vector in the dot product.
:type v1: list[ndim]
:param v2: Second vector in the dot product.
... | [
"def",
"vdotg",
"(",
"v1",
",",
"v2",
",",
"ndim",
")",
":",
"v1",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"v1",
")",
"v2",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"v2",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"ndim",
")",
"return",
... | Compute the dot product of two double precision vectors of
arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdotg_c.html
:param v1: First vector in the dot product.
:type v1: list[ndim]
:param v2: Second vector in the dot product.
:type v2: list[ndim]
:param n... | [
"Compute",
"the",
"dot",
"product",
"of",
"two",
"double",
"precision",
"vectors",
"of",
"arbitrary",
"dimension",
"."
] | python | train | 29.7 |
databio/pypiper | pypiper/ngstk.py | https://github.com/databio/pypiper/blob/00e6c2b94033c4187d47ff14c5580bbfc2ff097f/pypiper/ngstk.py#L1039-L1082 | def skewer(
self, input_fastq1, output_prefix, output_fastq1,
log, cpus, adapters, input_fastq2=None, output_fastq2=None):
"""
Create commands with which to run skewer.
:param str input_fastq1: Path to input (read 1) FASTQ file
:param str output_prefix: Prefix fo... | [
"def",
"skewer",
"(",
"self",
",",
"input_fastq1",
",",
"output_prefix",
",",
"output_fastq1",
",",
"log",
",",
"cpus",
",",
"adapters",
",",
"input_fastq2",
"=",
"None",
",",
"output_fastq2",
"=",
"None",
")",
":",
"pe",
"=",
"input_fastq2",
"is",
"not",
... | Create commands with which to run skewer.
:param str input_fastq1: Path to input (read 1) FASTQ file
:param str output_prefix: Prefix for output FASTQ file names
:param str output_fastq1: Path to (read 1) output FASTQ file
:param str log: Path to file to which to write logging informati... | [
"Create",
"commands",
"with",
"which",
"to",
"run",
"skewer",
"."
] | python | train | 43.590909 |
mozilla/FoxPuppet | foxpuppet/windows/browser/notifications/base.py | https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/base.py#L95-L99 | def close(self):
"""Close the notification."""
with self.selenium.context(self.selenium.CONTEXT_CHROME):
self.find_close_button().click()
self.window.wait_for_notification(None) | [
"def",
"close",
"(",
"self",
")",
":",
"with",
"self",
".",
"selenium",
".",
"context",
"(",
"self",
".",
"selenium",
".",
"CONTEXT_CHROME",
")",
":",
"self",
".",
"find_close_button",
"(",
")",
".",
"click",
"(",
")",
"self",
".",
"window",
".",
"wa... | Close the notification. | [
"Close",
"the",
"notification",
"."
] | python | train | 41.8 |
fjwCode/cerium | cerium/androiddriver.py | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L163-L166 | def get_resolution(self) -> list:
'''Show device resolution.'''
output, _ = self._execute('-s', self.device_sn, 'shell', 'wm', 'size')
return output.split()[2].split('x') | [
"def",
"get_resolution",
"(",
"self",
")",
"->",
"list",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'wm'",
",",
"'size'",
")",
"return",
"output",
".",
"split",
"(",
")",
... | Show device resolution. | [
"Show",
"device",
"resolution",
"."
] | python | train | 47.75 |
globocom/GloboNetworkAPI-client-python | networkapiclient/DireitoGrupoEquipamento.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/DireitoGrupoEquipamento.py#L135-L168 | def buscar_por_id(self, id_direito):
"""Obtém os direitos de um grupo de usuário e um grupo de equipamento.
:param id_direito: Identificador do direito grupo equipamento.
:return: Dicionário com a seguinte estrutura:
::
{'direito_grupo_equipamento':
{'id_grupo... | [
"def",
"buscar_por_id",
"(",
"self",
",",
"id_direito",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_direito",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'O identificador do direito grupo equipamento é inválido ou não foi informado.')",
"",
"url",
"=",
"'... | Obtém os direitos de um grupo de usuário e um grupo de equipamento.
:param id_direito: Identificador do direito grupo equipamento.
:return: Dicionário com a seguinte estrutura:
::
{'direito_grupo_equipamento':
{'id_grupo_equipamento': < id_grupo_equipamento >,
... | [
"Obtém",
"os",
"direitos",
"de",
"um",
"grupo",
"de",
"usuário",
"e",
"um",
"grupo",
"de",
"equipamento",
"."
] | python | train | 41.205882 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.