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 |
|---|---|---|---|---|---|---|---|---|---|
TracyWebTech/django-revproxy | revproxy/transformer.py | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/transformer.py#L112-L161 | def transform(self, rules, theme_template, is_html5, context_data=None):
"""Method used to make a transformation on the content of
the http response based on the rules and theme_templates
passed as paremters
:param rules: A file with a set of diazo rules to make a
... | [
"def",
"transform",
"(",
"self",
",",
"rules",
",",
"theme_template",
",",
"is_html5",
",",
"context_data",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"should_transform",
"(",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Don't need to be transf... | Method used to make a transformation on the content of
the http response based on the rules and theme_templates
passed as paremters
:param rules: A file with a set of diazo rules to make a
transformation over the original response content
:param theme_template: ... | [
"Method",
"used",
"to",
"make",
"a",
"transformation",
"on",
"the",
"content",
"of",
"the",
"http",
"response",
"based",
"on",
"the",
"rules",
"and",
"theme_templates",
"passed",
"as",
"paremters"
] | python | train | 39.66 |
p3trus/slave | slave/protocol.py | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/protocol.py#L263-L287 | def query_bytes(self, transport, num_bytes, header, *data):
"""Queries for binary data
:param transport: A transport object.
:param num_bytes: The exact number of data bytes expected.
:param header: The message header.
:param data: Optional data.
:returns: The raw unpar... | [
"def",
"query_bytes",
"(",
"self",
",",
"transport",
",",
"num_bytes",
",",
"header",
",",
"*",
"data",
")",
":",
"message",
"=",
"self",
".",
"create_message",
"(",
"header",
",",
"*",
"data",
")",
"logger",
".",
"debug",
"(",
"'SignalRecovery query bytes... | Queries for binary data
:param transport: A transport object.
:param num_bytes: The exact number of data bytes expected.
:param header: The message header.
:param data: Optional data.
:returns: The raw unparsed data bytearray. | [
"Queries",
"for",
"binary",
"data"
] | python | train | 41.32 |
opencobra/memote | memote/support/helpers.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/helpers.py#L184-L217 | def is_transport_reaction_formulae(rxn):
"""
Return boolean if a reaction is a transport reaction (from formulae).
Parameters
----------
rxn: cobra.Reaction
The metabolic reaction under investigation.
"""
# Collecting criteria to classify transporters by.
rxn_reactants = set([m... | [
"def",
"is_transport_reaction_formulae",
"(",
"rxn",
")",
":",
"# Collecting criteria to classify transporters by.",
"rxn_reactants",
"=",
"set",
"(",
"[",
"met",
".",
"formula",
"for",
"met",
"in",
"rxn",
".",
"reactants",
"]",
")",
"rxn_products",
"=",
"set",
"(... | Return boolean if a reaction is a transport reaction (from formulae).
Parameters
----------
rxn: cobra.Reaction
The metabolic reaction under investigation. | [
"Return",
"boolean",
"if",
"a",
"reaction",
"is",
"a",
"transport",
"reaction",
"(",
"from",
"formulae",
")",
"."
] | python | train | 42.205882 |
aio-libs/aiohttp | aiohttp/multipart.py | https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/multipart.py#L277-L291 | async def read(self, *, decode: bool=False) -> Any:
"""Reads body part data.
decode: Decodes data following by encoding
method from Content-Encoding header. If it missed
data remains untouched
"""
if self._at_eof:
return b''
data = byt... | [
"async",
"def",
"read",
"(",
"self",
",",
"*",
",",
"decode",
":",
"bool",
"=",
"False",
")",
"->",
"Any",
":",
"if",
"self",
".",
"_at_eof",
":",
"return",
"b''",
"data",
"=",
"bytearray",
"(",
")",
"while",
"not",
"self",
".",
"_at_eof",
":",
"... | Reads body part data.
decode: Decodes data following by encoding
method from Content-Encoding header. If it missed
data remains untouched | [
"Reads",
"body",
"part",
"data",
"."
] | python | train | 32.533333 |
materialsproject/pymatgen | pymatgen/io/abinit/flows.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/flows.py#L1049-L1101 | def show_inputs(self, varnames=None, nids=None, wslice=None, stream=sys.stdout):
"""
Print the input of the tasks to the given stream.
Args:
varnames:
List of Abinit variables. If not None, only the variable in varnames
are selected and printed.
... | [
"def",
"show_inputs",
"(",
"self",
",",
"varnames",
"=",
"None",
",",
"nids",
"=",
"None",
",",
"wslice",
"=",
"None",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"varnames",
"is",
"not",
"None",
":",
"# Build dictionary varname --> [(task1, ... | Print the input of the tasks to the given stream.
Args:
varnames:
List of Abinit variables. If not None, only the variable in varnames
are selected and printed.
nids:
List of node identifiers. By defaults all nodes are shown
ws... | [
"Print",
"the",
"input",
"of",
"the",
"tasks",
"to",
"the",
"given",
"stream",
"."
] | python | train | 41.339623 |
kylejusticemagnuson/pyti | pyti/weighted_moving_average.py | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/weighted_moving_average.py#L7-L25 | def weighted_moving_average(data, period):
"""
Weighted Moving Average.
Formula:
(P1 + 2 P2 + 3 P3 + ... + n Pn) / K
where K = (1+2+...+n) = n(n+1)/2 and Pn is the most recent price
"""
catch_errors.check_for_period_error(data, period)
k = (period * (period + 1)) / 2.0
wmas = []
... | [
"def",
"weighted_moving_average",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"k",
"=",
"(",
"period",
"*",
"(",
"period",
"+",
"1",
")",
")",
"/",
"2.0",
"wmas",
"=",
"[",
"]",
... | Weighted Moving Average.
Formula:
(P1 + 2 P2 + 3 P3 + ... + n Pn) / K
where K = (1+2+...+n) = n(n+1)/2 and Pn is the most recent price | [
"Weighted",
"Moving",
"Average",
"."
] | python | train | 29.736842 |
aouyar/PyMunin | pysysinfo/util.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pysysinfo/util.py#L266-L273 | def unregisterFilter(self, column):
"""Unregister filter on a column of the table.
@param column: The column header.
"""
if self._filters.has_key(column):
del self._filters[column] | [
"def",
"unregisterFilter",
"(",
"self",
",",
"column",
")",
":",
"if",
"self",
".",
"_filters",
".",
"has_key",
"(",
"column",
")",
":",
"del",
"self",
".",
"_filters",
"[",
"column",
"]"
] | Unregister filter on a column of the table.
@param column: The column header. | [
"Unregister",
"filter",
"on",
"a",
"column",
"of",
"the",
"table",
"."
] | python | train | 29.375 |
bapakode/OmMongo | ommongo/query_expression.py | https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L429-L445 | def or_(self, expression):
''' Adds the given expression to this instance's MongoDB ``$or``
expression, starting a new one if one does not exst
**Example**: ``(User.name == 'Jeff').or_(User.name == 'Jack')``
.. note:: The prefered usageis via an operator: ``User.name == 'Je... | [
"def",
"or_",
"(",
"self",
",",
"expression",
")",
":",
"if",
"'$or'",
"in",
"self",
".",
"obj",
":",
"self",
".",
"obj",
"[",
"'$or'",
"]",
".",
"append",
"(",
"expression",
".",
"obj",
")",
"return",
"self",
"self",
".",
"obj",
"=",
"{",
"'$or'... | Adds the given expression to this instance's MongoDB ``$or``
expression, starting a new one if one does not exst
**Example**: ``(User.name == 'Jeff').or_(User.name == 'Jack')``
.. note:: The prefered usageis via an operator: ``User.name == 'Jeff' | User.name == 'Jack'`` | [
"Adds",
"the",
"given",
"expression",
"to",
"this",
"instance",
"s",
"MongoDB",
"$or",
"expression",
"starting",
"a",
"new",
"one",
"if",
"one",
"does",
"not",
"exst"
] | python | train | 32.470588 |
nerdvegas/rez | src/rez/utils/formatting.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L247-L279 | def dict_to_attributes_code(dict_):
"""Given a nested dict, generate a python code equivalent.
Example:
>>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}}
>>> print dict_to_attributes_code(d)
foo = 'bah'
colors.red = 1
colors.blue = 2
Returns:
str.
... | [
"def",
"dict_to_attributes_code",
"(",
"dict_",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"dict_",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"txt",
"=",
"dict_to_attributes_code",
... | Given a nested dict, generate a python code equivalent.
Example:
>>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}}
>>> print dict_to_attributes_code(d)
foo = 'bah'
colors.red = 1
colors.blue = 2
Returns:
str. | [
"Given",
"a",
"nested",
"dict",
"generate",
"a",
"python",
"code",
"equivalent",
"."
] | python | train | 30.151515 |
ttinies/sc2common | sc2common/containers.py | https://github.com/ttinies/sc2common/blob/469623c319c7ab7af799551055839ea3b3f87d54/sc2common/containers.py#L246-L251 | def midPoint(self, point):
"""identify the midpoint between two mapPoints"""
x = (self.x + point.x)/2.0
y = (self.y + point.y)/2.0
z = (self.z + point.z)/2.0
return MapPoint(x,y,z) | [
"def",
"midPoint",
"(",
"self",
",",
"point",
")",
":",
"x",
"=",
"(",
"self",
".",
"x",
"+",
"point",
".",
"x",
")",
"/",
"2.0",
"y",
"=",
"(",
"self",
".",
"y",
"+",
"point",
".",
"y",
")",
"/",
"2.0",
"z",
"=",
"(",
"self",
".",
"z",
... | identify the midpoint between two mapPoints | [
"identify",
"the",
"midpoint",
"between",
"two",
"mapPoints"
] | python | train | 35.833333 |
tBuLi/symfit | symfit/contrib/interactive_guess/interactive_guess.py | https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/contrib/interactive_guess/interactive_guess.py#L278-L302 | def plot_data(self, proj, ax):
"""
Creates and plots the contourplot of the original data. This is done
by evaluating the density of projected datapoints on a grid.
"""
x, y = proj
x_data = self.ig.independent_data[x]
y_data = self.ig.dependent_data[y]
pro... | [
"def",
"plot_data",
"(",
"self",
",",
"proj",
",",
"ax",
")",
":",
"x",
",",
"y",
"=",
"proj",
"x_data",
"=",
"self",
".",
"ig",
".",
"independent_data",
"[",
"x",
"]",
"y_data",
"=",
"self",
".",
"ig",
".",
"dependent_data",
"[",
"y",
"]",
"proj... | Creates and plots the contourplot of the original data. This is done
by evaluating the density of projected datapoints on a grid. | [
"Creates",
"and",
"plots",
"the",
"contourplot",
"of",
"the",
"original",
"data",
".",
"This",
"is",
"done",
"by",
"evaluating",
"the",
"density",
"of",
"projected",
"datapoints",
"on",
"a",
"grid",
"."
] | python | train | 37.76 |
edx/edx-drf-extensions | edx_rest_framework_extensions/auth/bearer/authentication.py | https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/bearer/authentication.py#L54-L83 | def authenticate_credentials(self, token):
"""
Validate the bearer token against the OAuth provider.
Arguments:
token (str): Access token to validate
Returns:
(tuple): tuple containing:
user (User): User associated with the access token
... | [
"def",
"authenticate_credentials",
"(",
"self",
",",
"token",
")",
":",
"try",
":",
"user_info",
"=",
"self",
".",
"get_user_info",
"(",
"token",
")",
"except",
"UserInfoRetrievalFailed",
":",
"msg",
"=",
"'Failed to retrieve user info. Unable to authenticate.'",
"log... | Validate the bearer token against the OAuth provider.
Arguments:
token (str): Access token to validate
Returns:
(tuple): tuple containing:
user (User): User associated with the access token
access_token (str): Access token
Raises:
... | [
"Validate",
"the",
"bearer",
"token",
"against",
"the",
"OAuth",
"provider",
"."
] | python | train | 32.1 |
slhck/ffmpeg-normalize | ffmpeg_normalize/_media_file.py | https://github.com/slhck/ffmpeg-normalize/blob/18477a7f2d092777ee238340be40c04ecb45c132/ffmpeg_normalize/_media_file.py#L160-L179 | def _get_audio_filter_cmd(self):
"""
Return filter_complex command and output labels needed
"""
all_filters = []
output_labels = []
for audio_stream in self.streams['audio'].values():
if self.ffmpeg_normalize.normalization_type == 'ebu':
strea... | [
"def",
"_get_audio_filter_cmd",
"(",
"self",
")",
":",
"all_filters",
"=",
"[",
"]",
"output_labels",
"=",
"[",
"]",
"for",
"audio_stream",
"in",
"self",
".",
"streams",
"[",
"'audio'",
"]",
".",
"values",
"(",
")",
":",
"if",
"self",
".",
"ffmpeg_normal... | Return filter_complex command and output labels needed | [
"Return",
"filter_complex",
"command",
"and",
"output",
"labels",
"needed"
] | python | train | 40.2 |
Knoema/knoema-python-driver | knoema/api_client.py | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L104-L108 | def get_dimension(self, dataset, dimension):
"""The method is getting information about dimension with items"""
path = '/api/1.0/meta/dataset/{}/dimension/{}'
return self._api_get(definition.Dimension, path.format(dataset, dimension)) | [
"def",
"get_dimension",
"(",
"self",
",",
"dataset",
",",
"dimension",
")",
":",
"path",
"=",
"'/api/1.0/meta/dataset/{}/dimension/{}'",
"return",
"self",
".",
"_api_get",
"(",
"definition",
".",
"Dimension",
",",
"path",
".",
"format",
"(",
"dataset",
",",
"d... | The method is getting information about dimension with items | [
"The",
"method",
"is",
"getting",
"information",
"about",
"dimension",
"with",
"items"
] | python | train | 51.8 |
erdewit/ib_insync | ib_insync/ib.py | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/ib.py#L530-L571 | def bracketOrder(
self, action: str, quantity: float,
limitPrice: float, takeProfitPrice: float,
stopLossPrice: float, **kwargs) -> BracketOrder:
"""
Create a limit order that is bracketed by a take-profit order and
a stop-loss order. Submit the bracket like:
... | [
"def",
"bracketOrder",
"(",
"self",
",",
"action",
":",
"str",
",",
"quantity",
":",
"float",
",",
"limitPrice",
":",
"float",
",",
"takeProfitPrice",
":",
"float",
",",
"stopLossPrice",
":",
"float",
",",
"*",
"*",
"kwargs",
")",
"->",
"BracketOrder",
"... | Create a limit order that is bracketed by a take-profit order and
a stop-loss order. Submit the bracket like:
.. code-block:: python
for o in bracket:
ib.placeOrder(contract, o)
https://interactivebrokers.github.io/tws-api/bracket_order.html
Args:
... | [
"Create",
"a",
"limit",
"order",
"that",
"is",
"bracketed",
"by",
"a",
"take",
"-",
"profit",
"order",
"and",
"a",
"stop",
"-",
"loss",
"order",
".",
"Submit",
"the",
"bracket",
"like",
":"
] | python | train | 35.166667 |
materialsproject/pymatgen | pymatgen/io/abinit/tasks.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L4238-L4273 | def reset_from_scratch(self):
"""
restart from scratch, this is to be used if a job is restarted with more resources after a crash
"""
# Move output files produced in workdir to _reset otherwise check_status continues
# to see the task as crashed even if the job did not run
... | [
"def",
"reset_from_scratch",
"(",
"self",
")",
":",
"# Move output files produced in workdir to _reset otherwise check_status continues",
"# to see the task as crashed even if the job did not run",
"# Create reset directory if not already done.",
"reset_dir",
"=",
"os",
".",
"path",
".",... | restart from scratch, this is to be used if a job is restarted with more resources after a crash | [
"restart",
"from",
"scratch",
"this",
"is",
"to",
"be",
"used",
"if",
"a",
"job",
"is",
"restarted",
"with",
"more",
"resources",
"after",
"a",
"crash"
] | python | train | 38.25 |
blockstack/virtualchain | virtualchain/lib/indexer.py | https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/indexer.py#L1536-L1552 | def get_block_from_consensus( self, consensus_hash ):
"""
Get the block number with the given consensus hash.
Return None if there is no such block.
"""
query = 'SELECT block_id FROM snapshots WHERE consensus_hash = ?;'
args = (consensus_hash,)
con = self.db_open... | [
"def",
"get_block_from_consensus",
"(",
"self",
",",
"consensus_hash",
")",
":",
"query",
"=",
"'SELECT block_id FROM snapshots WHERE consensus_hash = ?;'",
"args",
"=",
"(",
"consensus_hash",
",",
")",
"con",
"=",
"self",
".",
"db_open",
"(",
"self",
".",
"impl",
... | Get the block number with the given consensus hash.
Return None if there is no such block. | [
"Get",
"the",
"block",
"number",
"with",
"the",
"given",
"consensus",
"hash",
".",
"Return",
"None",
"if",
"there",
"is",
"no",
"such",
"block",
"."
] | python | train | 30.470588 |
rdussurget/py-altimetry | altimetry/data/hydro.py | https://github.com/rdussurget/py-altimetry/blob/57ce7f2d63c6bbc4993821af0bbe46929e3a2d98/altimetry/data/hydro.py#L409-L417 | def delete_Variable(self,name):
'''
pops a variable from class and delete it from parameter list
:parameter name: name of the parameter to delete
'''
self.message(1,'Deleting variable {0}'.format(name))
self.par_list=self.par_list[self.par_list != name]
... | [
"def",
"delete_Variable",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"message",
"(",
"1",
",",
"'Deleting variable {0}'",
".",
"format",
"(",
"name",
")",
")",
"self",
".",
"par_list",
"=",
"self",
".",
"par_list",
"[",
"self",
".",
"par_list",
"... | pops a variable from class and delete it from parameter list
:parameter name: name of the parameter to delete | [
"pops",
"a",
"variable",
"from",
"class",
"and",
"delete",
"it",
"from",
"parameter",
"list",
":",
"parameter",
"name",
":",
"name",
"of",
"the",
"parameter",
"to",
"delete"
] | python | train | 38.777778 |
sentinel-hub/sentinelhub-py | sentinelhub/commands.py | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/commands.py#L83-L121 | def config(show, reset, **params):
"""Inspect and configure parameters in your local sentinelhub configuration file
\b
Example:
sentinelhub.config --show
sentinelhub.config --instance_id <new instance id>
sentinelhub.config --max_download_attempts 5 --download_sleep_time 20 --download_tim... | [
"def",
"config",
"(",
"show",
",",
"reset",
",",
"*",
"*",
"params",
")",
":",
"sh_config",
"=",
"SHConfig",
"(",
")",
"if",
"reset",
":",
"sh_config",
".",
"reset",
"(",
")",
"for",
"param",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
... | Inspect and configure parameters in your local sentinelhub configuration file
\b
Example:
sentinelhub.config --show
sentinelhub.config --instance_id <new instance id>
sentinelhub.config --max_download_attempts 5 --download_sleep_time 20 --download_timeout_seconds 120 | [
"Inspect",
"and",
"configure",
"parameters",
"in",
"your",
"local",
"sentinelhub",
"configuration",
"file"
] | python | train | 32.948718 |
pkgw/pwkit | pwkit/cli/__init__.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/cli/__init__.py#L261-L345 | def fork_detached_process ():
"""Fork this process, creating a subprocess detached from the current context.
Returns a :class:`pwkit.Holder` instance with information about what
happened. Its fields are:
whoami
A string, either "original" or "forked" depending on which process we are.
pipe
... | [
"def",
"fork_detached_process",
"(",
")",
":",
"import",
"os",
",",
"struct",
"from",
".",
".",
"import",
"Holder",
"payload",
"=",
"struct",
".",
"Struct",
"(",
"'L'",
")",
"info",
"=",
"Holder",
"(",
")",
"readfd",
",",
"writefd",
"=",
"os",
".",
"... | Fork this process, creating a subprocess detached from the current context.
Returns a :class:`pwkit.Holder` instance with information about what
happened. Its fields are:
whoami
A string, either "original" or "forked" depending on which process we are.
pipe
An open binary file descriptor. ... | [
"Fork",
"this",
"process",
"creating",
"a",
"subprocess",
"detached",
"from",
"the",
"current",
"context",
"."
] | python | train | 36.905882 |
AguaClara/aguaclara | aguaclara/research/environmental_processes_analysis.py | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L182-L203 | def O2_sat(P_air, temp):
"""Calculate saturaed oxygen concentration in mg/L for 278 K < T < 318 K
:param P_air: Air pressure with appropriate units
:type P_air: float
:param temp: Water temperature with appropriate units
:type temp: float
:return: Saturated oxygen concentration in mg/L
:rt... | [
"def",
"O2_sat",
"(",
"P_air",
",",
"temp",
")",
":",
"fraction_O2",
"=",
"0.21",
"P_O2",
"=",
"P_air",
"*",
"fraction_O2",
"return",
"(",
"(",
"P_O2",
".",
"to",
"(",
"u",
".",
"atm",
")",
".",
"magnitude",
")",
"*",
"u",
".",
"mg",
"/",
"u",
... | Calculate saturaed oxygen concentration in mg/L for 278 K < T < 318 K
:param P_air: Air pressure with appropriate units
:type P_air: float
:param temp: Water temperature with appropriate units
:type temp: float
:return: Saturated oxygen concentration in mg/L
:rtype: float
:Examples:
... | [
"Calculate",
"saturaed",
"oxygen",
"concentration",
"in",
"mg",
"/",
"L",
"for",
"278",
"K",
"<",
"T",
"<",
"318",
"K"
] | python | train | 33.272727 |
swift-nav/libsbp | python/sbp/msg.py | https://github.com/swift-nav/libsbp/blob/5a950608506b23e31b73ef7065da905b646055c1/python/sbp/msg.py#L84-L89 | def crc16_nojit(s, crc=0):
"""CRC16 implementation acording to CCITT standards."""
for ch in bytearray(s): # bytearray's elements are integers in both python 2 and 3
crc = ((crc << 8) & 0xFFFF) ^ _crc16_tab[((crc >> 8) & 0xFF) ^ (ch & 0xFF)]
crc &= 0xFFFF
return crc | [
"def",
"crc16_nojit",
"(",
"s",
",",
"crc",
"=",
"0",
")",
":",
"for",
"ch",
"in",
"bytearray",
"(",
"s",
")",
":",
"# bytearray's elements are integers in both python 2 and 3",
"crc",
"=",
"(",
"(",
"crc",
"<<",
"8",
")",
"&",
"0xFFFF",
")",
"^",
"_crc1... | CRC16 implementation acording to CCITT standards. | [
"CRC16",
"implementation",
"acording",
"to",
"CCITT",
"standards",
"."
] | python | train | 46 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/DFReader.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/DFReader.py#L121-L135 | def get_msgbuf(self):
'''create a binary message buffer for a message'''
values = []
for i in range(len(self.fmt.columns)):
if i >= len(self.fmt.msg_mults):
continue
mul = self.fmt.msg_mults[i]
name = self.fmt.columns[i]
if name == ... | [
"def",
"get_msgbuf",
"(",
"self",
")",
":",
"values",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"fmt",
".",
"columns",
")",
")",
":",
"if",
"i",
">=",
"len",
"(",
"self",
".",
"fmt",
".",
"msg_mults",
")",
":",
"... | create a binary message buffer for a message | [
"create",
"a",
"binary",
"message",
"buffer",
"for",
"a",
"message"
] | python | train | 40.666667 |
websocket-client/websocket-client | websocket/_core.py | https://github.com/websocket-client/websocket-client/blob/3c25814664fef5b78716ed8841123ed1c0d17824/websocket/_core.py#L186-L239 | def connect(self, url, **options):
"""
Connect to url. url is websocket url scheme.
ie. ws://host:port/resource
You can customize using 'options'.
If you set "header" list object, you can set your own custom header.
>>> ws = WebSocket()
>>> ws.connect("ws://echo.... | [
"def",
"connect",
"(",
"self",
",",
"url",
",",
"*",
"*",
"options",
")",
":",
"# FIXME: \"subprotocols\" are getting lost, not passed down",
"# FIXME: \"header\", \"cookie\", \"origin\" and \"host\" too",
"self",
".",
"sock_opt",
".",
"timeout",
"=",
"options",
".",
"get... | Connect to url. url is websocket url scheme.
ie. ws://host:port/resource
You can customize using 'options'.
If you set "header" list object, you can set your own custom header.
>>> ws = WebSocket()
>>> ws.connect("ws://echo.websocket.org/",
... header=["User-... | [
"Connect",
"to",
"url",
".",
"url",
"is",
"websocket",
"url",
"scheme",
".",
"ie",
".",
"ws",
":",
"//",
"host",
":",
"port",
"/",
"resource",
"You",
"can",
"customize",
"using",
"options",
".",
"If",
"you",
"set",
"header",
"list",
"object",
"you",
... | python | train | 48.333333 |
RedFantom/ttkwidgets | ttkwidgets/table.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/table.py#L460-L463 | def _config_options(self):
"""Apply options set in attributes to Treeview"""
self._config_sortable(self._sortable)
self._config_drag_cols(self._drag_cols) | [
"def",
"_config_options",
"(",
"self",
")",
":",
"self",
".",
"_config_sortable",
"(",
"self",
".",
"_sortable",
")",
"self",
".",
"_config_drag_cols",
"(",
"self",
".",
"_drag_cols",
")"
] | Apply options set in attributes to Treeview | [
"Apply",
"options",
"set",
"in",
"attributes",
"to",
"Treeview"
] | python | train | 43.75 |
lowandrew/OLCTools | databasesetup/database_setup.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/database_setup.py#L261-L286 | def url_request(target_url, output_file):
"""
Use urllib to download the requested file from the target URL. Use the click progress bar to print download
progress
:param target_url: URL from which the file is to be downloaded
:param output_file: Name and path of local copy of fil... | [
"def",
"url_request",
"(",
"target_url",
",",
"output_file",
")",
":",
"# Create the request",
"request",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"target_url",
")",
"# Open the destination file to write",
"with",
"open",
"(",
"output_file",
",",
"'wb'",
... | Use urllib to download the requested file from the target URL. Use the click progress bar to print download
progress
:param target_url: URL from which the file is to be downloaded
:param output_file: Name and path of local copy of file | [
"Use",
"urllib",
"to",
"download",
"the",
"requested",
"file",
"from",
"the",
"target",
"URL",
".",
"Use",
"the",
"click",
"progress",
"bar",
"to",
"print",
"download",
"progress",
":",
"param",
"target_url",
":",
"URL",
"from",
"which",
"the",
"file",
"is... | python | train | 49.730769 |
emencia/emencia-django-forum | forum/views/post.py | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/views/post.py#L42-L47 | def get_object(self, *args, **kwargs):
"""
Should memoize the object to avoid multiple query if get_object is used many times in the view
"""
self.category_instance = get_object_or_404(Category, slug=self.kwargs['category_slug'])
return get_object_or_404(Post, thread__id=self.kwa... | [
"def",
"get_object",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"category_instance",
"=",
"get_object_or_404",
"(",
"Category",
",",
"slug",
"=",
"self",
".",
"kwargs",
"[",
"'category_slug'",
"]",
")",
"return",
"get_... | Should memoize the object to avoid multiple query if get_object is used many times in the view | [
"Should",
"memoize",
"the",
"object",
"to",
"avoid",
"multiple",
"query",
"if",
"get_object",
"is",
"used",
"many",
"times",
"in",
"the",
"view"
] | python | train | 66.666667 |
pypa/bandersnatch | src/bandersnatch_filter_plugins/whitelist_name.py | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch_filter_plugins/whitelist_name.py#L50-L76 | def check_match(self, **kwargs):
"""
Check if the package name matches against a project that is blacklisted
in the configuration.
Parameters
==========
name: str
The normalized package name of the package/project to check against
the blacklist.
... | [
"def",
"check_match",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"whitelist_package_names",
":",
"return",
"False",
"name",
"=",
"kwargs",
".",
"get",
"(",
"\"name\"",
",",
"None",
")",
"if",
"not",
"name",
":",
"return",... | Check if the package name matches against a project that is blacklisted
in the configuration.
Parameters
==========
name: str
The normalized package name of the package/project to check against
the blacklist.
Returns
=======
bool:
... | [
"Check",
"if",
"the",
"package",
"name",
"matches",
"against",
"a",
"project",
"that",
"is",
"blacklisted",
"in",
"the",
"configuration",
"."
] | python | train | 26.37037 |
django-fluent/django-fluent-contents | fluent_contents/plugins/commentsarea/models.py | https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/commentsarea/models.py#L27-L33 | def clear_commentarea_cache(comment):
"""
Clean the plugin output cache of a rendered plugin.
"""
parent = comment.content_object
for instance in CommentsAreaItem.objects.parent(parent):
instance.clear_cache() | [
"def",
"clear_commentarea_cache",
"(",
"comment",
")",
":",
"parent",
"=",
"comment",
".",
"content_object",
"for",
"instance",
"in",
"CommentsAreaItem",
".",
"objects",
".",
"parent",
"(",
"parent",
")",
":",
"instance",
".",
"clear_cache",
"(",
")"
] | Clean the plugin output cache of a rendered plugin. | [
"Clean",
"the",
"plugin",
"output",
"cache",
"of",
"a",
"rendered",
"plugin",
"."
] | python | train | 33 |
shalabhms/reliable-collections-cli | rcctl/rcctl/custom_cluster.py | https://github.com/shalabhms/reliable-collections-cli/blob/195d69816fb5a6e1e9ab0ab66b606b1248b4780d/rcctl/rcctl/custom_cluster.py#L101-L134 | def get_aad_token(endpoint, no_verify):
#pylint: disable-msg=too-many-locals
"""Get AAD token"""
from azure.servicefabric.service_fabric_client_ap_is import (
ServiceFabricClientAPIs
)
from sfctl.auth import ClientCertAuthentication
from sfctl.config import set_aad_metadata
auth = C... | [
"def",
"get_aad_token",
"(",
"endpoint",
",",
"no_verify",
")",
":",
"#pylint: disable-msg=too-many-locals",
"from",
"azure",
".",
"servicefabric",
".",
"service_fabric_client_ap_is",
"import",
"(",
"ServiceFabricClientAPIs",
")",
"from",
"sfctl",
".",
"auth",
"import",... | Get AAD token | [
"Get",
"AAD",
"token"
] | python | valid | 33.382353 |
ChargePoint/pydnp3 | examples/master.py | https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/master.py#L117-L127 | def send_select_and_operate_command(self, command, index, callback=asiodnp3.PrintingCommandCallback.Get(),
config=opendnp3.TaskConfig().Default()):
"""
Select and operate a single command
:param command: command to operate
:param index: index ... | [
"def",
"send_select_and_operate_command",
"(",
"self",
",",
"command",
",",
"index",
",",
"callback",
"=",
"asiodnp3",
".",
"PrintingCommandCallback",
".",
"Get",
"(",
")",
",",
"config",
"=",
"opendnp3",
".",
"TaskConfig",
"(",
")",
".",
"Default",
"(",
")"... | Select and operate a single command
:param command: command to operate
:param index: index of the command
:param callback: callback that will be invoked upon completion or failure
:param config: optional configuration that controls normal callbacks and allows the user to be specified fo... | [
"Select",
"and",
"operate",
"a",
"single",
"command"
] | python | valid | 55.363636 |
SmokinCaterpillar/pypet | pypet/utils/helpful_functions.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/helpful_functions.py#L208-L256 | def progressbar(index, total, percentage_step=10, logger='print', log_level=logging.INFO,
reprint=True, time=True, length=20, fmt_string=None, reset=False):
"""Plots a progress bar to the given `logger` for large for loops.
To be used inside a for-loop at the end of the loop:
.. code-bloc... | [
"def",
"progressbar",
"(",
"index",
",",
"total",
",",
"percentage_step",
"=",
"10",
",",
"logger",
"=",
"'print'",
",",
"log_level",
"=",
"logging",
".",
"INFO",
",",
"reprint",
"=",
"True",
",",
"time",
"=",
"True",
",",
"length",
"=",
"20",
",",
"... | Plots a progress bar to the given `logger` for large for loops.
To be used inside a for-loop at the end of the loop:
.. code-block:: python
for irun in range(42):
my_costly_job() # Your expensive function
progressbar(index=irun, total=42, reprint=True) # shows a growing progre... | [
"Plots",
"a",
"progress",
"bar",
"to",
"the",
"given",
"logger",
"for",
"large",
"for",
"loops",
"."
] | python | test | 40.693878 |
f3at/feat | src/feat/common/reflect.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/common/reflect.py#L45-L52 | def named_function(name):
"""Gets a fully named module-global object."""
name_parts = name.split('.')
module = named_object('.'.join(name_parts[:-1]))
func = getattr(module, name_parts[-1])
if hasattr(func, 'original_func'):
func = func.original_func
return func | [
"def",
"named_function",
"(",
"name",
")",
":",
"name_parts",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"module",
"=",
"named_object",
"(",
"'.'",
".",
"join",
"(",
"name_parts",
"[",
":",
"-",
"1",
"]",
")",
")",
"func",
"=",
"getattr",
"(",
"mo... | Gets a fully named module-global object. | [
"Gets",
"a",
"fully",
"named",
"module",
"-",
"global",
"object",
"."
] | python | train | 35.875 |
zero-os/zerotier_client | zerotier/client_utils.py | https://github.com/zero-os/zerotier_client/blob/03993da11e69d837a0308a2f41ae7b378692fd82/zerotier/client_utils.py#L62-L82 | def _generate_timezone(date, local_tz):
"""
input :
date : date type
local_tz : bool
offset generated from _calculate_offset
offset in seconds
offset = 0 -> +00:00
offset = 1800 -> +00:30
offset = -3600 -> -01:00
"""
offset = _calculate_offset(date, local_tz)
hour = abs... | [
"def",
"_generate_timezone",
"(",
"date",
",",
"local_tz",
")",
":",
"offset",
"=",
"_calculate_offset",
"(",
"date",
",",
"local_tz",
")",
"hour",
"=",
"abs",
"(",
"offset",
")",
"//",
"3600",
"minute",
"=",
"abs",
"(",
"offset",
")",
"%",
"3600",
"//... | input :
date : date type
local_tz : bool
offset generated from _calculate_offset
offset in seconds
offset = 0 -> +00:00
offset = 1800 -> +00:30
offset = -3600 -> -01:00 | [
"input",
":",
"date",
":",
"date",
"type",
"local_tz",
":",
"bool"
] | python | train | 23.142857 |
duguyue100/minesweeper | minesweeper/msgame.py | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/msgame.py#L231-L241 | def play_move_msg(self, move_msg):
"""Another play move function for move message.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
"""
move_type, move_x, move_y = self.parse_move(move_msg)
self... | [
"def",
"play_move_msg",
"(",
"self",
",",
"move_msg",
")",
":",
"move_type",
",",
"move_x",
",",
"move_y",
"=",
"self",
".",
"parse_move",
"(",
"move_msg",
")",
"self",
".",
"play_move",
"(",
"move_type",
",",
"move_x",
",",
"move_y",
")"
] | Another play move function for move message.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]" | [
"Another",
"play",
"move",
"function",
"for",
"move",
"message",
"."
] | python | train | 31.545455 |
boronine/discipline | discipline/models.py | https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L398-L412 | def __summary(self):
"""A plaintext summary of the Action, useful for debugging."""
text = "Time: %s\n" % self.when
text += "Comitter: %s\n" % self.editor
inst = self.timemachine.presently
if self.action_type == "dl":
text += "Deleted %s\n" % inst._object_type_text(... | [
"def",
"__summary",
"(",
"self",
")",
":",
"text",
"=",
"\"Time: %s\\n\"",
"%",
"self",
".",
"when",
"text",
"+=",
"\"Comitter: %s\\n\"",
"%",
"self",
".",
"editor",
"inst",
"=",
"self",
".",
"timemachine",
".",
"presently",
"if",
"self",
".",
"action_type... | A plaintext summary of the Action, useful for debugging. | [
"A",
"plaintext",
"summary",
"of",
"the",
"Action",
"useful",
"for",
"debugging",
"."
] | python | train | 36.533333 |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L328-L337 | def make_signature(params, hmac_key):
"""
Calculate a HMAC-SHA-1 (using hmac_key) of all the params except "h=".
Returns base64 encoded signature as string.
"""
# produce a list of "key=value" for all entries in params except `h'
pairs = [x + "=" + ''.join(params[x]) for x in sorted(params.keys... | [
"def",
"make_signature",
"(",
"params",
",",
"hmac_key",
")",
":",
"# produce a list of \"key=value\" for all entries in params except `h'",
"pairs",
"=",
"[",
"x",
"+",
"\"=\"",
"+",
"''",
".",
"join",
"(",
"params",
"[",
"x",
"]",
")",
"for",
"x",
"in",
"sor... | Calculate a HMAC-SHA-1 (using hmac_key) of all the params except "h=".
Returns base64 encoded signature as string. | [
"Calculate",
"a",
"HMAC",
"-",
"SHA",
"-",
"1",
"(",
"using",
"hmac_key",
")",
"of",
"all",
"the",
"params",
"except",
"h",
"=",
"."
] | python | train | 42.9 |
openstack/horizon | horizon/utils/validators.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/validators.py#L58-L64 | def validate_port_or_colon_separated_port_range(port_range):
"""Accepts a port number or a single-colon separated range."""
if port_range.count(':') > 1:
raise ValidationError(_("One colon allowed in port range"))
ports = port_range.split(':')
for port in ports:
validate_port_range(port) | [
"def",
"validate_port_or_colon_separated_port_range",
"(",
"port_range",
")",
":",
"if",
"port_range",
".",
"count",
"(",
"':'",
")",
">",
"1",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"\"One colon allowed in port range\"",
")",
")",
"ports",
"=",
"port_ran... | Accepts a port number or a single-colon separated range. | [
"Accepts",
"a",
"port",
"number",
"or",
"a",
"single",
"-",
"colon",
"separated",
"range",
"."
] | python | train | 44.857143 |
saltstack/salt | salt/states/zabbix_hostgroup.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_hostgroup.py#L24-L88 | def present(name, **kwargs):
'''
Ensures that the host group exists, eventually creates new host group.
.. versionadded:: 2016.3.0
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_... | [
"def",
"present",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"connection_args",
"=",
"{",
"}",
"if",
"'_connection_user'",
"in",
"kwargs",
":",
"connection_args",
"[",
"'_connection_user'",
"]",
"=",
"kwargs",
"[",
"'_connection_user'",
"]",
"if",
"'_co... | Ensures that the host group exists, eventually creates new host group.
.. versionadded:: 2016.3.0
:param name: name of the host group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can... | [
"Ensures",
"that",
"the",
"host",
"group",
"exists",
"eventually",
"creates",
"new",
"host",
"group",
"."
] | python | train | 39.646154 |
pyQode/pyqode.core | pyqode/core/widgets/splittable_tab_widget.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L571-L577 | def addTab(self, tab, *args):
"""
Adds a tab to the tab widget, this function set the parent_tab_widget
attribute on the tab instance.
"""
tab.parent_tab_widget = self
super(BaseTabWidget, self).addTab(tab, *args) | [
"def",
"addTab",
"(",
"self",
",",
"tab",
",",
"*",
"args",
")",
":",
"tab",
".",
"parent_tab_widget",
"=",
"self",
"super",
"(",
"BaseTabWidget",
",",
"self",
")",
".",
"addTab",
"(",
"tab",
",",
"*",
"args",
")"
] | Adds a tab to the tab widget, this function set the parent_tab_widget
attribute on the tab instance. | [
"Adds",
"a",
"tab",
"to",
"the",
"tab",
"widget",
"this",
"function",
"set",
"the",
"parent_tab_widget",
"attribute",
"on",
"the",
"tab",
"instance",
"."
] | python | train | 36.428571 |
PolyJIT/benchbuild | benchbuild/utils/unionfs.py | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/unionfs.py#L122-L126 | def __is_outside_of_builddir(project, path_to_check):
"""Check if a project lies outside of its expected directory."""
bdir = project.builddir
cprefix = os.path.commonprefix([path_to_check, bdir])
return cprefix != bdir | [
"def",
"__is_outside_of_builddir",
"(",
"project",
",",
"path_to_check",
")",
":",
"bdir",
"=",
"project",
".",
"builddir",
"cprefix",
"=",
"os",
".",
"path",
".",
"commonprefix",
"(",
"[",
"path_to_check",
",",
"bdir",
"]",
")",
"return",
"cprefix",
"!=",
... | Check if a project lies outside of its expected directory. | [
"Check",
"if",
"a",
"project",
"lies",
"outside",
"of",
"its",
"expected",
"directory",
"."
] | python | train | 46.2 |
tanghaibao/jcvi | jcvi/graphics/tree.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/tree.py#L73-L202 | def draw_tree(ax, tx, rmargin=.3,
treecolor="k", leafcolor="k", supportcolor="k",
outgroup=None, reroot=True, gffdir=None, sizes=None,
trunc_name=None, SH=None, scutoff=0, barcodefile=None,
leafcolorfile=None, leaffont=12):
"""
main function for drawing ph... | [
"def",
"draw_tree",
"(",
"ax",
",",
"tx",
",",
"rmargin",
"=",
".3",
",",
"treecolor",
"=",
"\"k\"",
",",
"leafcolor",
"=",
"\"k\"",
",",
"supportcolor",
"=",
"\"k\"",
",",
"outgroup",
"=",
"None",
",",
"reroot",
"=",
"True",
",",
"gffdir",
"=",
"Non... | main function for drawing phylogenetic tree | [
"main",
"function",
"for",
"drawing",
"phylogenetic",
"tree"
] | python | train | 31.638462 |
undertheseanlp/underthesea | underthesea/classification/__init__.py | https://github.com/undertheseanlp/underthesea/blob/3663427da65e2b449e9135e3812edecb938b2319/underthesea/classification/__init__.py#L6-L43 | def classify(X, domain=None):
"""
Text classification
Parameters
==========
X: {unicode, str}
raw sentence
domain: {None, 'bank'}
domain of text
* None: general domain
* bank: bank domain
Returns
=======
tokens: list
categories of sen... | [
"def",
"classify",
"(",
"X",
",",
"domain",
"=",
"None",
")",
":",
"if",
"X",
"==",
"\"\"",
":",
"return",
"None",
"if",
"domain",
"==",
"'bank'",
":",
"return",
"bank",
".",
"classify",
"(",
"X",
")",
"# domain is general",
"clf",
"=",
"FastTextPredic... | Text classification
Parameters
==========
X: {unicode, str}
raw sentence
domain: {None, 'bank'}
domain of text
* None: general domain
* bank: bank domain
Returns
=======
tokens: list
categories of sentence
Examples
--------
>>> ... | [
"Text",
"classification"
] | python | train | 21.947368 |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/rst/dis/distree.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/rst/dis/distree.py#L37-L44 | def fromstring(cls, dis_string):
"""Create a DisRSTTree instance from a string containing a *.dis parse."""
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(dis_string)
temp.close()
dis_tree = cls(dis_filepath=temp.name)
os.unlink(temp.name)
return dis_... | [
"def",
"fromstring",
"(",
"cls",
",",
"dis_string",
")",
":",
"temp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
"temp",
".",
"write",
"(",
"dis_string",
")",
"temp",
".",
"close",
"(",
")",
"dis_tree",
"=",
"cls",
"(... | Create a DisRSTTree instance from a string containing a *.dis parse. | [
"Create",
"a",
"DisRSTTree",
"instance",
"from",
"a",
"string",
"containing",
"a",
"*",
".",
"dis",
"parse",
"."
] | python | train | 39.625 |
oksome/Tumulus | tumulus/element.py | https://github.com/oksome/Tumulus/blob/20fca0e251d6f1825c33e61a8d497b62a8cbc0da/tumulus/element.py#L42-L57 | def soup(self):
'''
Returns HTML as a BeautifulSoup element.
'''
components_soup = Tag(name=self.tagname, builder=BUILDER)
components_soup.attrs = self.attributes
for c in flatten(self.components):
if hasattr(c, 'soup'):
components_soup.app... | [
"def",
"soup",
"(",
"self",
")",
":",
"components_soup",
"=",
"Tag",
"(",
"name",
"=",
"self",
".",
"tagname",
",",
"builder",
"=",
"BUILDER",
")",
"components_soup",
".",
"attrs",
"=",
"self",
".",
"attributes",
"for",
"c",
"in",
"flatten",
"(",
"self... | Returns HTML as a BeautifulSoup element. | [
"Returns",
"HTML",
"as",
"a",
"BeautifulSoup",
"element",
"."
] | python | train | 37.0625 |
readbeyond/aeneas | aeneas/tools/abstract_cli_program.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L427-L435 | def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
self.log(u"This function should be overloaded in derived classes")
self.log([u"Invoked with %s", self.actual_arguments])
return self.NO_ERROR_EXIT_CODE | [
"def",
"perform_command",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"This function should be overloaded in derived classes\"",
")",
"self",
".",
"log",
"(",
"[",
"u\"Invoked with %s\"",
",",
"self",
".",
"actual_arguments",
"]",
")",
"return",
"self",
"."... | Perform command and return the appropriate exit code.
:rtype: int | [
"Perform",
"command",
"and",
"return",
"the",
"appropriate",
"exit",
"code",
"."
] | python | train | 33.444444 |
staticdev/django-pagination-bootstrap | pagination_bootstrap/paginator.py | https://github.com/staticdev/django-pagination-bootstrap/blob/b4bf8352a364b223babbc5f33e14ecabd82c0886/pagination_bootstrap/paginator.py#L157-L165 | def has_next(self):
"""
Checks for one more item than last on this page.
"""
try:
next_item = self.paginator.object_list[self.paginator.per_page]
except IndexError:
return False
return True | [
"def",
"has_next",
"(",
"self",
")",
":",
"try",
":",
"next_item",
"=",
"self",
".",
"paginator",
".",
"object_list",
"[",
"self",
".",
"paginator",
".",
"per_page",
"]",
"except",
"IndexError",
":",
"return",
"False",
"return",
"True"
] | Checks for one more item than last on this page. | [
"Checks",
"for",
"one",
"more",
"item",
"than",
"last",
"on",
"this",
"page",
"."
] | python | train | 28.111111 |
ssato/python-anyconfig | src/anyconfig/api.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L351-L432 | def multi_load(inputs, ac_parser=None, ac_template=False, ac_context=None,
**options):
r"""
Load multiple config files.
.. note::
:func:`load` is a preferable alternative and this API should be used
only if there is a need to emphasize given inputs are multiple ones.
The ... | [
"def",
"multi_load",
"(",
"inputs",
",",
"ac_parser",
"=",
"None",
",",
"ac_template",
"=",
"False",
",",
"ac_context",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"marker",
"=",
"options",
".",
"setdefault",
"(",
"\"ac_marker\"",
",",
"options",
".... | r"""
Load multiple config files.
.. note::
:func:`load` is a preferable alternative and this API should be used
only if there is a need to emphasize given inputs are multiple ones.
The first argument 'inputs' may be a list of a file paths or a glob pattern
specifying them or a pathlib.P... | [
"r",
"Load",
"multiple",
"config",
"files",
"."
] | python | train | 40.621951 |
jaraco/jaraco.mongodb | jaraco/mongodb/sharding.py | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/sharding.py#L16-L43 | def create_db_in_shard(db_name, shard, client=None):
"""
In a sharded cluster, create a database in a particular shard.
"""
client = client or pymongo.MongoClient()
# flush the router config to ensure it's not stale
res = client.admin.command('flushRouterConfig')
if not res.get('ok'):
... | [
"def",
"create_db_in_shard",
"(",
"db_name",
",",
"shard",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"client",
"or",
"pymongo",
".",
"MongoClient",
"(",
")",
"# flush the router config to ensure it's not stale",
"res",
"=",
"client",
".",
"admin",
"."... | In a sharded cluster, create a database in a particular shard. | [
"In",
"a",
"sharded",
"cluster",
"create",
"a",
"database",
"in",
"a",
"particular",
"shard",
"."
] | python | train | 43.535714 |
mbr/tinyrpc | tinyrpc/client.py | https://github.com/mbr/tinyrpc/blob/59ccf62452b3f37e8411ff0309a3a99857d05e19/tinyrpc/client.py#L131-L138 | def batch_call(self, calls):
"""Experimental, use at your own peril."""
req = self.protocol.create_batch_request()
for call_args in calls:
req.append(self.protocol.create_request(*call_args))
return self._send_and_handle_reply(req) | [
"def",
"batch_call",
"(",
"self",
",",
"calls",
")",
":",
"req",
"=",
"self",
".",
"protocol",
".",
"create_batch_request",
"(",
")",
"for",
"call_args",
"in",
"calls",
":",
"req",
".",
"append",
"(",
"self",
".",
"protocol",
".",
"create_request",
"(",
... | Experimental, use at your own peril. | [
"Experimental",
"use",
"at",
"your",
"own",
"peril",
"."
] | python | train | 33.75 |
yyuu/botornado | boto/rds/dbsecuritygroup.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/rds/dbsecuritygroup.py#L68-L91 | def authorize(self, cidr_ip=None, ec2_group=None):
"""
Add a new rule to this DBSecurity group.
You need to pass in either a CIDR block to authorize or
and EC2 SecurityGroup.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP range to authorize
@type ec2_grou... | [
"def",
"authorize",
"(",
"self",
",",
"cidr_ip",
"=",
"None",
",",
"ec2_group",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"ec2_group",
",",
"SecurityGroup",
")",
":",
"group_name",
"=",
"ec2_group",
".",
"name",
"group_owner_id",
"=",
"ec2_group",
".... | Add a new rule to this DBSecurity group.
You need to pass in either a CIDR block to authorize or
and EC2 SecurityGroup.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP range to authorize
@type ec2_group: :class:`boto.ec2.securitygroup.SecurityGroup>`
@rtype: bool... | [
"Add",
"a",
"new",
"rule",
"to",
"this",
"DBSecurity",
"group",
".",
"You",
"need",
"to",
"pass",
"in",
"either",
"a",
"CIDR",
"block",
"to",
"authorize",
"or",
"and",
"EC2",
"SecurityGroup",
"."
] | python | train | 38 |
limodou/ido | ido/commands.py | https://github.com/limodou/ido/blob/7fcf5c20b47993b6c16eb6007f77ad1c868a6d68/ido/commands.py#L56-L76 | def get_input(prompt, default=None, choices=None, option_value=None):
"""
If option_value is not None, then return it. Otherwise get the result from
input.
"""
if option_value is not None:
return option_value
choices = choices or []
while 1:
r = input(prompt+' ').strip(... | [
"def",
"get_input",
"(",
"prompt",
",",
"default",
"=",
"None",
",",
"choices",
"=",
"None",
",",
"option_value",
"=",
"None",
")",
":",
"if",
"option_value",
"is",
"not",
"None",
":",
"return",
"option_value",
"choices",
"=",
"choices",
"or",
"[",
"]",
... | If option_value is not None, then return it. Otherwise get the result from
input. | [
"If",
"option_value",
"is",
"not",
"None",
"then",
"return",
"it",
".",
"Otherwise",
"get",
"the",
"result",
"from",
"input",
"."
] | python | train | 25.380952 |
DistrictDataLabs/yellowbrick | yellowbrick/classifier/threshold.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/threshold.py#L403-L412 | def _check_quantiles(self, val):
"""
Validate the quantiles passed in. Returns the np array if valid.
"""
if len(val) != 3 or not is_monotonic(val) or not np.all(val < 1):
raise YellowbrickValueError(
"quantiles must be a sequence of three "
"m... | [
"def",
"_check_quantiles",
"(",
"self",
",",
"val",
")",
":",
"if",
"len",
"(",
"val",
")",
"!=",
"3",
"or",
"not",
"is_monotonic",
"(",
"val",
")",
"or",
"not",
"np",
".",
"all",
"(",
"val",
"<",
"1",
")",
":",
"raise",
"YellowbrickValueError",
"(... | Validate the quantiles passed in. Returns the np array if valid. | [
"Validate",
"the",
"quantiles",
"passed",
"in",
".",
"Returns",
"the",
"np",
"array",
"if",
"valid",
"."
] | python | train | 39.9 |
deepmind/sonnet | sonnet/examples/dataset_shakespeare.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L81-L86 | def tokenize(self, token_list):
"""Produces the list of integer indices corresponding to a token list."""
return [
self._vocab_dict.get(token, self._vocab_dict[self.UNK])
for token in token_list
] | [
"def",
"tokenize",
"(",
"self",
",",
"token_list",
")",
":",
"return",
"[",
"self",
".",
"_vocab_dict",
".",
"get",
"(",
"token",
",",
"self",
".",
"_vocab_dict",
"[",
"self",
".",
"UNK",
"]",
")",
"for",
"token",
"in",
"token_list",
"]"
] | Produces the list of integer indices corresponding to a token list. | [
"Produces",
"the",
"list",
"of",
"integer",
"indices",
"corresponding",
"to",
"a",
"token",
"list",
"."
] | python | train | 36.5 |
consbio/ncdjango | ncdjango/views.py | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L148-L162 | def _normalize_bbox(self, bbox, size):
"""Returns this bbox normalized to match the ratio of the given size."""
bbox_ratio = float(bbox.width) / float(bbox.height)
size_ratio = float(size[0]) / float(size[1])
if round(size_ratio, 4) == round(bbox_ratio, 4):
return bbox
... | [
"def",
"_normalize_bbox",
"(",
"self",
",",
"bbox",
",",
"size",
")",
":",
"bbox_ratio",
"=",
"float",
"(",
"bbox",
".",
"width",
")",
"/",
"float",
"(",
"bbox",
".",
"height",
")",
"size_ratio",
"=",
"float",
"(",
"size",
"[",
"0",
"]",
")",
"/",
... | Returns this bbox normalized to match the ratio of the given size. | [
"Returns",
"this",
"bbox",
"normalized",
"to",
"match",
"the",
"ratio",
"of",
"the",
"given",
"size",
"."
] | python | train | 48.6 |
fakedrake/overlay_parse | overlay_parse/matchers.py | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L218-L227 | def _maybe_run_matchers(self, text, run_matchers):
"""
OverlayedText should be smart enough to not run twice the same
matchers but this is an extra handle of control over that.
"""
if run_matchers is True or \
(run_matchers is not False and text not in self._overlayed... | [
"def",
"_maybe_run_matchers",
"(",
"self",
",",
"text",
",",
"run_matchers",
")",
":",
"if",
"run_matchers",
"is",
"True",
"or",
"(",
"run_matchers",
"is",
"not",
"False",
"and",
"text",
"not",
"in",
"self",
".",
"_overlayed_already",
")",
":",
"text",
"."... | OverlayedText should be smart enough to not run twice the same
matchers but this is an extra handle of control over that. | [
"OverlayedText",
"should",
"be",
"smart",
"enough",
"to",
"not",
"run",
"twice",
"the",
"same",
"matchers",
"but",
"this",
"is",
"an",
"extra",
"handle",
"of",
"control",
"over",
"that",
"."
] | python | train | 41 |
coinbase/coinbase-python | coinbase/wallet/model.py | https://github.com/coinbase/coinbase-python/blob/497c28158f529e8c7d0228521b4386a890baf088/coinbase/wallet/model.py#L181-L183 | def get_transaction(self, transaction_id, **params):
"""https://developers.coinbase.com/api/v2#show-a-transaction"""
return self.api_client.get_transaction(self.id, transaction_id, **params) | [
"def",
"get_transaction",
"(",
"self",
",",
"transaction_id",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"api_client",
".",
"get_transaction",
"(",
"self",
".",
"id",
",",
"transaction_id",
",",
"*",
"*",
"params",
")"
] | https://developers.coinbase.com/api/v2#show-a-transaction | [
"https",
":",
"//",
"developers",
".",
"coinbase",
".",
"com",
"/",
"api",
"/",
"v2#show",
"-",
"a",
"-",
"transaction"
] | python | train | 68 |
symphonyoss/python-symphony | symphony/Pod/streams.py | https://github.com/symphonyoss/python-symphony/blob/b939f35fbda461183ec0c01790c754f89a295be0/symphony/Pod/streams.py#L46-L53 | def stream_info(self, stream_id):
''' get stream info '''
response, status_code = self.__pod__.Streams.get_v2_room_id_info(
sessionToken=self.__session__,
id=stream_id
).result()
self.logger.debug('%s: %s' % (status_code, response))
return status_code, res... | [
"def",
"stream_info",
"(",
"self",
",",
"stream_id",
")",
":",
"response",
",",
"status_code",
"=",
"self",
".",
"__pod__",
".",
"Streams",
".",
"get_v2_room_id_info",
"(",
"sessionToken",
"=",
"self",
".",
"__session__",
",",
"id",
"=",
"stream_id",
")",
... | get stream info | [
"get",
"stream",
"info"
] | python | train | 39.75 |
google/grr | grr/server/grr_response_server/databases/mysql_flows.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_flows.py#L501-L561 | def UpdateFlow(self,
client_id,
flow_id,
flow_obj=db.Database.unchanged,
flow_state=db.Database.unchanged,
client_crash_info=db.Database.unchanged,
pending_termination=db.Database.unchanged,
processing... | [
"def",
"UpdateFlow",
"(",
"self",
",",
"client_id",
",",
"flow_id",
",",
"flow_obj",
"=",
"db",
".",
"Database",
".",
"unchanged",
",",
"flow_state",
"=",
"db",
".",
"Database",
".",
"unchanged",
",",
"client_crash_info",
"=",
"db",
".",
"Database",
".",
... | Updates flow objects in the database. | [
"Updates",
"flow",
"objects",
"in",
"the",
"database",
"."
] | python | train | 40.983607 |
scrapinghub/exporters | exporters/writers/base_writer.py | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/base_writer.py#L118-L124 | def _check_items_limit(self):
"""
Raise ItemsLimitReached if the writer reached the configured items limit.
"""
if self.items_limit and self.items_limit == self.get_metadata('items_count'):
raise ItemsLimitReached('Finishing job after items_limit reached:'
... | [
"def",
"_check_items_limit",
"(",
"self",
")",
":",
"if",
"self",
".",
"items_limit",
"and",
"self",
".",
"items_limit",
"==",
"self",
".",
"get_metadata",
"(",
"'items_count'",
")",
":",
"raise",
"ItemsLimitReached",
"(",
"'Finishing job after items_limit reached:'... | Raise ItemsLimitReached if the writer reached the configured items limit. | [
"Raise",
"ItemsLimitReached",
"if",
"the",
"writer",
"reached",
"the",
"configured",
"items",
"limit",
"."
] | python | train | 56.142857 |
limodou/uliweb | uliweb/contrib/rbac/rbac.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/rbac/rbac.py#L42-L78 | def has_role(user, *roles, **kwargs):
"""
Judge is the user belongs to the role, and if does, then return the role object
if not then return False. kwargs will be passed to role_func.
"""
Role = get_model('role')
if isinstance(user, (unicode, str)):
User = get_model('user')
... | [
"def",
"has_role",
"(",
"user",
",",
"*",
"roles",
",",
"*",
"*",
"kwargs",
")",
":",
"Role",
"=",
"get_model",
"(",
"'role'",
")",
"if",
"isinstance",
"(",
"user",
",",
"(",
"unicode",
",",
"str",
")",
")",
":",
"User",
"=",
"get_model",
"(",
"'... | Judge is the user belongs to the role, and if does, then return the role object
if not then return False. kwargs will be passed to role_func. | [
"Judge",
"is",
"the",
"user",
"belongs",
"to",
"the",
"role",
"and",
"if",
"does",
"then",
"return",
"the",
"role",
"object",
"if",
"not",
"then",
"return",
"False",
".",
"kwargs",
"will",
"be",
"passed",
"to",
"role_func",
"."
] | python | train | 30.351351 |
gem/oq-engine | openquake/calculators/export/risk.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/risk.py#L526-L542 | def get_loss_maps(dstore, kind):
"""
:param dstore: a DataStore instance
:param kind: 'rlzs' or 'stats'
"""
oq = dstore['oqparam']
name = 'loss_maps-%s' % kind
if name in dstore: # event_based risk
return _to_loss_maps(dstore[name].value, oq.loss_maps_dt())
name = 'loss_curves-%... | [
"def",
"get_loss_maps",
"(",
"dstore",
",",
"kind",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"name",
"=",
"'loss_maps-%s'",
"%",
"kind",
"if",
"name",
"in",
"dstore",
":",
"# event_based risk",
"return",
"_to_loss_maps",
"(",
"dstore",
"[",
"n... | :param dstore: a DataStore instance
:param kind: 'rlzs' or 'stats' | [
":",
"param",
"dstore",
":",
"a",
"DataStore",
"instance",
":",
"param",
"kind",
":",
"rlzs",
"or",
"stats"
] | python | train | 38.941176 |
datastax/python-driver | cassandra/query.py | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/query.py#L787-L798 | def clear(self):
"""
This is a convenience method to clear a batch statement for reuse.
*Note:* it should not be used concurrently with uncompleted execution futures executing the same
``BatchStatement``.
"""
del self._statements_and_parameters[:]
self.keyspace =... | [
"def",
"clear",
"(",
"self",
")",
":",
"del",
"self",
".",
"_statements_and_parameters",
"[",
":",
"]",
"self",
".",
"keyspace",
"=",
"None",
"self",
".",
"routing_key",
"=",
"None",
"if",
"self",
".",
"custom_payload",
":",
"self",
".",
"custom_payload",
... | This is a convenience method to clear a batch statement for reuse.
*Note:* it should not be used concurrently with uncompleted execution futures executing the same
``BatchStatement``. | [
"This",
"is",
"a",
"convenience",
"method",
"to",
"clear",
"a",
"batch",
"statement",
"for",
"reuse",
"."
] | python | train | 34.833333 |
Alignak-monitoring/alignak | alignak/external_command.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/external_command.py#L2618-L2630 | def enable_hostgroup_host_notifications(self, hostgroup):
"""Enable host notifications for a hostgroup
Format of the line that triggers function call::
ENABLE_HOSTGROUP_HOST_NOTIFICATIONS;<hostgroup_name>
:param hostgroup: hostgroup to enable
:type hostgroup: alignak.objects.ho... | [
"def",
"enable_hostgroup_host_notifications",
"(",
"self",
",",
"hostgroup",
")",
":",
"for",
"host_id",
"in",
"hostgroup",
".",
"get_hosts",
"(",
")",
":",
"if",
"host_id",
"in",
"self",
".",
"daemon",
".",
"hosts",
":",
"self",
".",
"enable_host_notification... | Enable host notifications for a hostgroup
Format of the line that triggers function call::
ENABLE_HOSTGROUP_HOST_NOTIFICATIONS;<hostgroup_name>
:param hostgroup: hostgroup to enable
:type hostgroup: alignak.objects.hostgroup.Hostgroup
:return: None | [
"Enable",
"host",
"notifications",
"for",
"a",
"hostgroup",
"Format",
"of",
"the",
"line",
"that",
"triggers",
"function",
"call",
"::"
] | python | train | 40.384615 |
speechinformaticslab/vfclust | vfclust/vfclust.py | https://github.com/speechinformaticslab/vfclust/blob/7ca733dea4782c828024765726cce65de095d33c/vfclust/vfclust.py#L792-L805 | def get_collections(self):
"""Helper function for determining what the clusters/chains/other collections are."""
if not self.quiet:
print
print "Finding " + self.current_collection_type + "s..."
self.compute_collections()
if not self.quiet:
print sel... | [
"def",
"get_collections",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"quiet",
":",
"print",
"print",
"\"Finding \"",
"+",
"self",
".",
"current_collection_type",
"+",
"\"s...\"",
"self",
".",
"compute_collections",
"(",
")",
"if",
"not",
"self",
".",
... | Helper function for determining what the clusters/chains/other collections are. | [
"Helper",
"function",
"for",
"determining",
"what",
"the",
"clusters",
"/",
"chains",
"/",
"other",
"collections",
"are",
"."
] | python | train | 47.071429 |
dgketchum/satellite_image | sat_image/fmask.py | https://github.com/dgketchum/satellite_image/blob/0207fbb7b2bbf14f4307db65489bb4d4c5b92f52/sat_image/fmask.py#L224-L254 | def potential_cloud_pixels(self):
"""Determine potential cloud pixels (PCPs)
Combine basic spectral testsr to get a premliminary cloud mask
First pass, section 3.1.1 in Zhu and Woodcock 2012
Equation 6 (Zhu and Woodcock, 2012)
Parameters
----------
ndvi: ndarray
... | [
"def",
"potential_cloud_pixels",
"(",
"self",
")",
":",
"eq1",
"=",
"self",
".",
"basic_test",
"(",
")",
"eq2",
"=",
"self",
".",
"whiteness_test",
"(",
")",
"eq3",
"=",
"self",
".",
"hot_test",
"(",
")",
"eq4",
"=",
"self",
".",
"nirswir_test",
"(",
... | Determine potential cloud pixels (PCPs)
Combine basic spectral testsr to get a premliminary cloud mask
First pass, section 3.1.1 in Zhu and Woodcock 2012
Equation 6 (Zhu and Woodcock, 2012)
Parameters
----------
ndvi: ndarray
ndsi: ndarray
blue: ndarray
... | [
"Determine",
"potential",
"cloud",
"pixels",
"(",
"PCPs",
")",
"Combine",
"basic",
"spectral",
"testsr",
"to",
"get",
"a",
"premliminary",
"cloud",
"mask",
"First",
"pass",
"section",
"3",
".",
"1",
".",
"1",
"in",
"Zhu",
"and",
"Woodcock",
"2012",
"Equati... | python | train | 28.83871 |
ktbyers/netmiko | netmiko/scp_handler.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/scp_handler.py#L301-L306 | def transfer_file(self):
"""SCP transfer file."""
if self.direction == "put":
self.put_file()
elif self.direction == "get":
self.get_file() | [
"def",
"transfer_file",
"(",
"self",
")",
":",
"if",
"self",
".",
"direction",
"==",
"\"put\"",
":",
"self",
".",
"put_file",
"(",
")",
"elif",
"self",
".",
"direction",
"==",
"\"get\"",
":",
"self",
".",
"get_file",
"(",
")"
] | SCP transfer file. | [
"SCP",
"transfer",
"file",
"."
] | python | train | 30.333333 |
a2liu/mr-clean | mr_clean/core/functions/basics.py | https://github.com/a2liu/mr-clean/blob/0ee4ee5639f834dec4b59b94442fa84373f3c176/mr_clean/core/functions/basics.py#L287-L299 | def cols_rename(df,col_names, new_col_names):
""" Rename a set of columns in a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_names - list of strings
names of columns to change
new_col_names - list of strings
new names for old columns (order should be same a... | [
"def",
"cols_rename",
"(",
"df",
",",
"col_names",
",",
"new_col_names",
")",
":",
"assert",
"len",
"(",
"col_names",
")",
"==",
"len",
"(",
"new_col_names",
")",
"for",
"old_name",
",",
"new_name",
"in",
"zip",
"(",
"col_names",
",",
"new_col_names",
")",... | Rename a set of columns in a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_names - list of strings
names of columns to change
new_col_names - list of strings
new names for old columns (order should be same as col_names) | [
"Rename",
"a",
"set",
"of",
"columns",
"in",
"a",
"DataFrame",
"Parameters",
":",
"df",
"-",
"DataFrame",
"DataFrame",
"to",
"operate",
"on",
"col_names",
"-",
"list",
"of",
"strings",
"names",
"of",
"columns",
"to",
"change",
"new_col_names",
"-",
"list",
... | python | train | 36.615385 |
ejeschke/ginga | ginga/misc/Task.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L1112-L1128 | def register_up(self):
"""Called by WorkerThread objects to register themselves.
Acquire the condition variable for the WorkerThread objects.
Increment the running-thread count. If we are the last thread to
start, set status to 'up'. This allows startall() to complete
if it wa... | [
"def",
"register_up",
"(",
"self",
")",
":",
"with",
"self",
".",
"regcond",
":",
"self",
".",
"runningcount",
"+=",
"1",
"tid",
"=",
"thread",
".",
"get_ident",
"(",
")",
"self",
".",
"tids",
".",
"append",
"(",
"tid",
")",
"self",
".",
"logger",
... | Called by WorkerThread objects to register themselves.
Acquire the condition variable for the WorkerThread objects.
Increment the running-thread count. If we are the last thread to
start, set status to 'up'. This allows startall() to complete
if it was called with wait=True. | [
"Called",
"by",
"WorkerThread",
"objects",
"to",
"register",
"themselves",
"."
] | python | train | 42.058824 |
delfick/nose-of-yeti | noseOfYeti/tokeniser/containers.py | https://github.com/delfick/nose-of-yeti/blob/0b545ff350cebd59b40b601333c13033ce40d6dc/noseOfYeti/tokeniser/containers.py#L165-L167 | def start_group(self, scol, typ):
"""Start a new group"""
return Group(parent=self, level=scol, typ=typ) | [
"def",
"start_group",
"(",
"self",
",",
"scol",
",",
"typ",
")",
":",
"return",
"Group",
"(",
"parent",
"=",
"self",
",",
"level",
"=",
"scol",
",",
"typ",
"=",
"typ",
")"
] | Start a new group | [
"Start",
"a",
"new",
"group"
] | python | train | 39.333333 |
log2timeline/plaso | plaso/lib/pfilter.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/lib/pfilter.py#L89-L110 | def _GetMessage(self, event_object):
"""Returns a properly formatted message string.
Args:
event_object: the event object (instance od EventObject).
Returns:
A formatted message string.
"""
# TODO: move this somewhere where the mediator can be instantiated once.
formatter_mediator ... | [
"def",
"_GetMessage",
"(",
"self",
",",
"event_object",
")",
":",
"# TODO: move this somewhere where the mediator can be instantiated once.",
"formatter_mediator",
"=",
"formatters_mediator",
".",
"FormatterMediator",
"(",
")",
"result",
"=",
"''",
"try",
":",
"result",
"... | Returns a properly formatted message string.
Args:
event_object: the event object (instance od EventObject).
Returns:
A formatted message string. | [
"Returns",
"a",
"properly",
"formatted",
"message",
"string",
"."
] | python | train | 29.954545 |
mollie/mollie-api-python | mollie/api/resources/chargebacks.py | https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/resources/chargebacks.py#L12-L19 | def get(self, chargeback_id, **params):
"""Verify the chargeback ID and retrieve the chargeback from the API."""
if not chargeback_id or not chargeback_id.startswith(self.RESOURCE_ID_PREFIX):
raise IdentifierError(
"Invalid chargeback ID: '{id}'. A chargeback ID should start ... | [
"def",
"get",
"(",
"self",
",",
"chargeback_id",
",",
"*",
"*",
"params",
")",
":",
"if",
"not",
"chargeback_id",
"or",
"not",
"chargeback_id",
".",
"startswith",
"(",
"self",
".",
"RESOURCE_ID_PREFIX",
")",
":",
"raise",
"IdentifierError",
"(",
"\"Invalid c... | Verify the chargeback ID and retrieve the chargeback from the API. | [
"Verify",
"the",
"chargeback",
"ID",
"and",
"retrieve",
"the",
"chargeback",
"from",
"the",
"API",
"."
] | python | train | 61.375 |
twilio/twilio-python | twilio/rest/api/v2010/account/outgoing_caller_id.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/outgoing_caller_id.py#L327-L341 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: OutgoingCallerIdContext for this OutgoingCallerIdInstance
:rtype: twilio.rest.api.v2010.account.o... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"OutgoingCallerIdContext",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: OutgoingCallerIdContext for this OutgoingCallerIdInstance
:rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdCont... | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train | 41.466667 |
ga4gh/ga4gh-server | ga4gh/server/frontend.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/frontend.py#L368-L379 | def handleHttpPost(request, endpoint):
"""
Handles the specified HTTP POST request, which maps to the specified
protocol handler endpoint and protocol request class.
"""
if request.mimetype and request.mimetype != MIMETYPE:
raise exceptions.UnsupportedMediaTypeException()
request = reque... | [
"def",
"handleHttpPost",
"(",
"request",
",",
"endpoint",
")",
":",
"if",
"request",
".",
"mimetype",
"and",
"request",
".",
"mimetype",
"!=",
"MIMETYPE",
":",
"raise",
"exceptions",
".",
"UnsupportedMediaTypeException",
"(",
")",
"request",
"=",
"request",
".... | Handles the specified HTTP POST request, which maps to the specified
protocol handler endpoint and protocol request class. | [
"Handles",
"the",
"specified",
"HTTP",
"POST",
"request",
"which",
"maps",
"to",
"the",
"specified",
"protocol",
"handler",
"endpoint",
"and",
"protocol",
"request",
"class",
"."
] | python | train | 38.583333 |
chrislit/abydos | abydos/stats/_mean.py | https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L571-L611 | def aghmean(nums):
"""Return arithmetic-geometric-harmonic mean.
Iterates over arithmetic, geometric, & harmonic means until they
converge to a single value (rounded to 12 digits), following the
method described in :cite:`Raissouli:2009`.
Parameters
----------
nums : list
A series ... | [
"def",
"aghmean",
"(",
"nums",
")",
":",
"m_a",
"=",
"amean",
"(",
"nums",
")",
"m_g",
"=",
"gmean",
"(",
"nums",
")",
"m_h",
"=",
"hmean",
"(",
"nums",
")",
"if",
"math",
".",
"isnan",
"(",
"m_a",
")",
"or",
"math",
".",
"isnan",
"(",
"m_g",
... | Return arithmetic-geometric-harmonic mean.
Iterates over arithmetic, geometric, & harmonic means until they
converge to a single value (rounded to 12 digits), following the
method described in :cite:`Raissouli:2009`.
Parameters
----------
nums : list
A series of numbers
Returns
... | [
"Return",
"arithmetic",
"-",
"geometric",
"-",
"harmonic",
"mean",
"."
] | python | valid | 23.926829 |
openai/baselines | baselines/common/atari_wrappers.py | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/atari_wrappers.py#L235-L249 | def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False):
"""Configure environment for DeepMind-style Atari.
"""
if episode_life:
env = EpisodicLifeEnv(env)
if 'FIRE' in env.unwrapped.get_action_meanings():
env = FireResetEnv(env)
env = WarpFrame(e... | [
"def",
"wrap_deepmind",
"(",
"env",
",",
"episode_life",
"=",
"True",
",",
"clip_rewards",
"=",
"True",
",",
"frame_stack",
"=",
"False",
",",
"scale",
"=",
"False",
")",
":",
"if",
"episode_life",
":",
"env",
"=",
"EpisodicLifeEnv",
"(",
"env",
")",
"if... | Configure environment for DeepMind-style Atari. | [
"Configure",
"environment",
"for",
"DeepMind",
"-",
"style",
"Atari",
"."
] | python | valid | 32.066667 |
broadinstitute/fiss | firecloud/workspace.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/workspace.py#L296-L300 | def acl(self):
"""Get the access control list for this workspace."""
r = fapi.get_workspace_acl(self.namespace, self.name, self.api_url)
fapi._check_response_code(r, 200)
return r.json() | [
"def",
"acl",
"(",
"self",
")",
":",
"r",
"=",
"fapi",
".",
"get_workspace_acl",
"(",
"self",
".",
"namespace",
",",
"self",
".",
"name",
",",
"self",
".",
"api_url",
")",
"fapi",
".",
"_check_response_code",
"(",
"r",
",",
"200",
")",
"return",
"r",... | Get the access control list for this workspace. | [
"Get",
"the",
"access",
"control",
"list",
"for",
"this",
"workspace",
"."
] | python | train | 42.8 |
mohan3d/PyOpenload | openload/openload.py | https://github.com/mohan3d/PyOpenload/blob/7f9353915ca5546926ef07be9395c6de60e761b1/openload/openload.py#L263-L288 | def remote_upload(self, remote_url, folder_id=None, headers=None):
"""Used to make a remote file upload to openload.co
Note:
If folder_id is not provided, the file will be uploaded to ``Home`` folder.
Args:
remote_url (str): direct link of file to be remotely downloaded... | [
"def",
"remote_upload",
"(",
"self",
",",
"remote_url",
",",
"folder_id",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'folder'",
":",
"folder_id",
",",
"'headers'",
":",
"headers",
"}",
"params",
"=",
"{",
"'url'",
":",
"re... | Used to make a remote file upload to openload.co
Note:
If folder_id is not provided, the file will be uploaded to ``Home`` folder.
Args:
remote_url (str): direct link of file to be remotely downloaded.
folder_id (:obj:`str`, optional): folder-ID to upload to.
... | [
"Used",
"to",
"make",
"a",
"remote",
"file",
"upload",
"to",
"openload",
".",
"co"
] | python | test | 35.423077 |
mrcagney/gtfstk | gtfstk/miscellany.py | https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/miscellany.py#L601-L608 | def compute_bounds(feed: "Feed") -> Tuple:
"""
Return the tuple (min longitude, min latitude, max longitude,
max latitude) where the longitudes and latitude vary across all
the Feed's stop coordinates.
"""
lons, lats = feed.stops["stop_lon"], feed.stops["stop_lat"]
return lons.min(), lats.mi... | [
"def",
"compute_bounds",
"(",
"feed",
":",
"\"Feed\"",
")",
"->",
"Tuple",
":",
"lons",
",",
"lats",
"=",
"feed",
".",
"stops",
"[",
"\"stop_lon\"",
"]",
",",
"feed",
".",
"stops",
"[",
"\"stop_lat\"",
"]",
"return",
"lons",
".",
"min",
"(",
")",
","... | Return the tuple (min longitude, min latitude, max longitude,
max latitude) where the longitudes and latitude vary across all
the Feed's stop coordinates. | [
"Return",
"the",
"tuple",
"(",
"min",
"longitude",
"min",
"latitude",
"max",
"longitude",
"max",
"latitude",
")",
"where",
"the",
"longitudes",
"and",
"latitude",
"vary",
"across",
"all",
"the",
"Feed",
"s",
"stop",
"coordinates",
"."
] | python | train | 42.5 |
ibis-project/ibis | ibis/impala/kudu_support.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/impala/kudu_support.py#L39-L69 | def connect(
self,
host_or_hosts,
port_or_ports=7051,
rpc_timeout=None,
admin_timeout=None,
):
"""
Pass-through connection interface to the Kudu client
Parameters
----------
host_or_hosts : string or list of strings
If you ha... | [
"def",
"connect",
"(",
"self",
",",
"host_or_hosts",
",",
"port_or_ports",
"=",
"7051",
",",
"rpc_timeout",
"=",
"None",
",",
"admin_timeout",
"=",
"None",
",",
")",
":",
"self",
".",
"client",
"=",
"kudu",
".",
"connect",
"(",
"host_or_hosts",
",",
"por... | Pass-through connection interface to the Kudu client
Parameters
----------
host_or_hosts : string or list of strings
If you have multiple Kudu masters for HA, pass a list
port_or_ports : int or list of int, default 7051
If you pass multiple host names, pass multiple ... | [
"Pass",
"-",
"through",
"connection",
"interface",
"to",
"the",
"Kudu",
"client"
] | python | train | 28.258065 |
postlund/pyatv | examples/autodiscover.py | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/examples/autodiscover.py#L11-L29 | async def print_what_is_playing(loop):
"""Find a device and print what is playing."""
print('Discovering devices on network...')
atvs = await pyatv.scan_for_apple_tvs(loop, timeout=5)
if not atvs:
print('no device found', file=sys.stderr)
return
print('Connecting to {0}'.format(atv... | [
"async",
"def",
"print_what_is_playing",
"(",
"loop",
")",
":",
"print",
"(",
"'Discovering devices on network...'",
")",
"atvs",
"=",
"await",
"pyatv",
".",
"scan_for_apple_tvs",
"(",
"loop",
",",
"timeout",
"=",
"5",
")",
"if",
"not",
"atvs",
":",
"print",
... | Find a device and print what is playing. | [
"Find",
"a",
"device",
"and",
"print",
"what",
"is",
"playing",
"."
] | python | train | 29.315789 |
tensorflow/hub | tensorflow_hub/tensor_info.py | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L133-L151 | def convert_dict_to_compatible_tensor(values, targets):
"""Converts dict `values` in tensors that are compatible with `targets`.
Args:
values: A dict to objects to convert with same keys as `targets`.
targets: A dict returned by `parse_tensor_info_map`.
Returns:
A map with the same keys as `values` ... | [
"def",
"convert_dict_to_compatible_tensor",
"(",
"values",
",",
"targets",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"values",
".",
"items",
"(",
")",
")",
":",
"result",
"[",
"key",
"]",
"=",
"_convert_to_compat... | Converts dict `values` in tensors that are compatible with `targets`.
Args:
values: A dict to objects to convert with same keys as `targets`.
targets: A dict returned by `parse_tensor_info_map`.
Returns:
A map with the same keys as `values` but values converted into
Tensor/SparseTensors that can b... | [
"Converts",
"dict",
"values",
"in",
"tensors",
"that",
"are",
"compatible",
"with",
"targets",
"."
] | python | train | 33.263158 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/message.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/message.py#L72-L90 | def _maybe_add_read_preference(spec, read_preference):
"""Add $readPreference to spec when appropriate."""
mode = read_preference.mode
tag_sets = read_preference.tag_sets
max_staleness = read_preference.max_staleness
# Only add $readPreference if it's something other than primary to avoid
# prob... | [
"def",
"_maybe_add_read_preference",
"(",
"spec",
",",
"read_preference",
")",
":",
"mode",
"=",
"read_preference",
".",
"mode",
"tag_sets",
"=",
"read_preference",
".",
"tag_sets",
"max_staleness",
"=",
"read_preference",
".",
"max_staleness",
"# Only add $readPreferen... | Add $readPreference to spec when appropriate. | [
"Add",
"$readPreference",
"to",
"spec",
"when",
"appropriate",
"."
] | python | train | 45.052632 |
noahbenson/neuropythy | neuropythy/util/core.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/util/core.py#L926-L949 | def arcsine(x, null=(-np.inf, np.inf)):
'''
arcsine(x) is equivalent to asin(x) except that it also works on sparse arrays.
The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what
value(s) should be assigned when x < -1 or x > 1. If only one number is given, then... | [
"def",
"arcsine",
"(",
"x",
",",
"null",
"=",
"(",
"-",
"np",
".",
"inf",
",",
"np",
".",
"inf",
")",
")",
":",
"if",
"sps",
".",
"issparse",
"(",
"x",
")",
":",
"x",
"=",
"x",
".",
"copy",
"(",
")",
"x",
".",
"data",
"=",
"arcsine",
"(",... | arcsine(x) is equivalent to asin(x) except that it also works on sparse arrays.
The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what
value(s) should be assigned when x < -1 or x > 1. If only one number is given, then it is used
for both values; otherwise the first... | [
"arcsine",
"(",
"x",
")",
"is",
"equivalent",
"to",
"asin",
"(",
"x",
")",
"except",
"that",
"it",
"also",
"works",
"on",
"sparse",
"arrays",
"."
] | python | train | 39.208333 |
delfick/nose-of-yeti | noseOfYeti/tokeniser/containers.py | https://github.com/delfick/nose-of-yeti/blob/0b545ff350cebd59b40b601333c13033ce40d6dc/noseOfYeti/tokeniser/containers.py#L10-L25 | def acceptable(value, capitalize=False):
"""Convert a string into something that can be used as a valid python variable name"""
name = regexes['punctuation'].sub("", regexes['joins'].sub("_", value))
# Clean up irregularities in underscores.
name = regexes['repeated_underscore'].sub("_", name.strip('_')... | [
"def",
"acceptable",
"(",
"value",
",",
"capitalize",
"=",
"False",
")",
":",
"name",
"=",
"regexes",
"[",
"'punctuation'",
"]",
".",
"sub",
"(",
"\"\"",
",",
"regexes",
"[",
"'joins'",
"]",
".",
"sub",
"(",
"\"_\"",
",",
"value",
")",
")",
"# Clean ... | Convert a string into something that can be used as a valid python variable name | [
"Convert",
"a",
"string",
"into",
"something",
"that",
"can",
"be",
"used",
"as",
"a",
"valid",
"python",
"variable",
"name"
] | python | train | 48.375 |
log2timeline/dfvfs | dfvfs/vfs/tsk_file_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_system.py#L101-L137 | def GetFileEntryByPathSpec(self, path_spec):
"""Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
TSKFileEntry: a file entry or None if not available.
"""
# Opening a file by inode number is faster than opening a file by location.... | [
"def",
"GetFileEntryByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"# Opening a file by inode number is faster than opening a file by location.",
"tsk_file",
"=",
"None",
"inode",
"=",
"getattr",
"(",
"path_spec",
",",
"'inode'",
",",
"None",
")",
"location",
"="... | Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
TSKFileEntry: a file entry or None if not available. | [
"Retrieves",
"a",
"file",
"entry",
"for",
"a",
"path",
"specification",
"."
] | python | train | 32.675676 |
garicchi/arff2pandas | arff2pandas/a2p.py | https://github.com/garicchi/arff2pandas/blob/6698a3f57a9c227c8f38deb827b53b80b8c6a231/arff2pandas/a2p.py#L5-L21 | def __load(arff):
"""
load liac-arff to pandas DataFrame
:param dict arff:arff dict created liac-arff
:rtype: DataFrame
:return: pandas DataFrame
"""
attrs = arff['attributes']
attrs_t = []
for attr in attrs:
if isinstance(attr[1], list):
attrs_t.append("%s@{%s}" ... | [
"def",
"__load",
"(",
"arff",
")",
":",
"attrs",
"=",
"arff",
"[",
"'attributes'",
"]",
"attrs_t",
"=",
"[",
"]",
"for",
"attr",
"in",
"attrs",
":",
"if",
"isinstance",
"(",
"attr",
"[",
"1",
"]",
",",
"list",
")",
":",
"attrs_t",
".",
"append",
... | load liac-arff to pandas DataFrame
:param dict arff:arff dict created liac-arff
:rtype: DataFrame
:return: pandas DataFrame | [
"load",
"liac",
"-",
"arff",
"to",
"pandas",
"DataFrame",
":",
"param",
"dict",
"arff",
":",
"arff",
"dict",
"created",
"liac",
"-",
"arff",
":",
"rtype",
":",
"DataFrame",
":",
"return",
":",
"pandas",
"DataFrame"
] | python | train | 28.176471 |
ask/redish | redish/client.py | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L80-L93 | def Dict(self, name, initial=None, **extra):
"""The dictionary datatype (Hash).
:param name: The name of the dictionary.
:keyword initial: Initial contents.
:keyword \*\*extra: Initial contents as keyword arguments.
The ``initial``, and ``**extra`` keyword arguments
wil... | [
"def",
"Dict",
"(",
"self",
",",
"name",
",",
"initial",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"return",
"types",
".",
"Dict",
"(",
"name",
",",
"self",
".",
"api",
",",
"initial",
"=",
"initial",
",",
"*",
"*",
"extra",
")"
] | The dictionary datatype (Hash).
:param name: The name of the dictionary.
:keyword initial: Initial contents.
:keyword \*\*extra: Initial contents as keyword arguments.
The ``initial``, and ``**extra`` keyword arguments
will be merged (keyword arguments has priority).
S... | [
"The",
"dictionary",
"datatype",
"(",
"Hash",
")",
"."
] | python | train | 33.857143 |
dsandersAzure/python_cowbull_game | python_cowbull_game/GameController.py | https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/GameController.py#L118-L171 | def load(self, game_json=None, mode=None):
"""
Load a game from a serialized JSON representation. The game expects a well defined
structure as follows (Note JSON string format):
'{
"guesses_made": int,
"key": "str:a 4 word",
"status": "str: one of pla... | [
"def",
"load",
"(",
"self",
",",
"game_json",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"if",
"game_json",
"is",
"None",
":",
"# New game_json",
"if",
"mode",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"mode",
",",
"str",
")",
":",
"... | Load a game from a serialized JSON representation. The game expects a well defined
structure as follows (Note JSON string format):
'{
"guesses_made": int,
"key": "str:a 4 word",
"status": "str: one of playing, won, lost",
"mode": {
"digits... | [
"Load",
"a",
"game",
"from",
"a",
"serialized",
"JSON",
"representation",
".",
"The",
"game",
"expects",
"a",
"well",
"defined",
"structure",
"as",
"follows",
"(",
"Note",
"JSON",
"string",
"format",
")",
":"
] | python | valid | 37.555556 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L393-L396 | def set_header(self, msg):
""" Set second head line text """
self.s.move(1, 0)
self.overwrite_line(msg, attr=curses.A_NORMAL) | [
"def",
"set_header",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"s",
".",
"move",
"(",
"1",
",",
"0",
")",
"self",
".",
"overwrite_line",
"(",
"msg",
",",
"attr",
"=",
"curses",
".",
"A_NORMAL",
")"
] | Set second head line text | [
"Set",
"second",
"head",
"line",
"text"
] | python | train | 36.5 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py#L4946-L4961 | def get_stp_mst_detail_output_msti_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
... | [
"def",
"get_stp_mst_detail_output_msti_port_oper_bpdu_guard",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_stp_mst_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_stp_mst_detail\"",
")",
"config"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 45 |
adewes/blitzdb | blitzdb/backends/file/queries.py | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L150-L167 | def in_query(expression):
"""Match any of the values that exist in an array specified in query."""
def _in(index, expression=expression):
"""Return store key for documents that satisfy expression."""
ev = expression() if callable(expression) else expression
try:
iter(ev)
... | [
"def",
"in_query",
"(",
"expression",
")",
":",
"def",
"_in",
"(",
"index",
",",
"expression",
"=",
"expression",
")",
":",
"\"\"\"Return store key for documents that satisfy expression.\"\"\"",
"ev",
"=",
"expression",
"(",
")",
"if",
"callable",
"(",
"expression",... | Match any of the values that exist in an array specified in query. | [
"Match",
"any",
"of",
"the",
"values",
"that",
"exist",
"in",
"an",
"array",
"specified",
"in",
"query",
"."
] | python | train | 34.222222 |
tensorflow/mesh | mesh_tensorflow/placement_mesh_impl.py | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/placement_mesh_impl.py#L339-L348 | def export_to_tf_tensor(self, x, laid_out_x):
"""Turn a Tensor into a tf.Tensor.
Args:
x: a Tensor
laid_out_x: a LaidOutTensor
Returns:
a tf.Tensor
"""
return self.combine_slices(laid_out_x.all_slices, x.shape) | [
"def",
"export_to_tf_tensor",
"(",
"self",
",",
"x",
",",
"laid_out_x",
")",
":",
"return",
"self",
".",
"combine_slices",
"(",
"laid_out_x",
".",
"all_slices",
",",
"x",
".",
"shape",
")"
] | Turn a Tensor into a tf.Tensor.
Args:
x: a Tensor
laid_out_x: a LaidOutTensor
Returns:
a tf.Tensor | [
"Turn",
"a",
"Tensor",
"into",
"a",
"tf",
".",
"Tensor",
"."
] | python | train | 24 |
googledatalab/pydatalab | datalab/bigquery/_query.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L531-L543 | def to_view(self, view_name):
""" Create a View from this Query.
Args:
view_name: the name of the View either as a string or a 3-part tuple
(projectid, datasetid, name).
Returns:
A View for the Query.
"""
# Do the import here to avoid circular dependencies at top-level.
f... | [
"def",
"to_view",
"(",
"self",
",",
"view_name",
")",
":",
"# Do the import here to avoid circular dependencies at top-level.",
"from",
".",
"import",
"_view",
"return",
"_view",
".",
"View",
"(",
"view_name",
",",
"self",
".",
"_context",
")",
".",
"create",
"(",... | Create a View from this Query.
Args:
view_name: the name of the View either as a string or a 3-part tuple
(projectid, datasetid, name).
Returns:
A View for the Query. | [
"Create",
"a",
"View",
"from",
"this",
"Query",
"."
] | python | train | 30.153846 |
F-Secure/see | see/context/resources/helpers.py | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/helpers.py#L18-L39 | def subelement(element, xpath, tag, text, **kwargs):
"""
Searches element matching the *xpath* in *parent* and replaces it's *tag*,
*text* and *kwargs* attributes.
If the element in *xpath* is not found a new child element is created
with *kwargs* attributes and added.
Returns the found/create... | [
"def",
"subelement",
"(",
"element",
",",
"xpath",
",",
"tag",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"subelm",
"=",
"element",
".",
"find",
"(",
"xpath",
")",
"if",
"subelm",
"is",
"None",
":",
"subelm",
"=",
"etree",
".",
"SubElement",
"... | Searches element matching the *xpath* in *parent* and replaces it's *tag*,
*text* and *kwargs* attributes.
If the element in *xpath* is not found a new child element is created
with *kwargs* attributes and added.
Returns the found/created element. | [
"Searches",
"element",
"matching",
"the",
"*",
"xpath",
"*",
"in",
"*",
"parent",
"*",
"and",
"replaces",
"it",
"s",
"*",
"tag",
"*",
"*",
"text",
"*",
"and",
"*",
"kwargs",
"*",
"attributes",
"."
] | python | train | 25.954545 |
hendrix/hendrix | hendrix/contrib/concurrency/messaging.py | https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/messaging.py#L41-L46 | def remove(self, transport):
"""
removes a transport if a member of this group
"""
if transport.uid in self.transports:
del (self.transports[transport.uid]) | [
"def",
"remove",
"(",
"self",
",",
"transport",
")",
":",
"if",
"transport",
".",
"uid",
"in",
"self",
".",
"transports",
":",
"del",
"(",
"self",
".",
"transports",
"[",
"transport",
".",
"uid",
"]",
")"
] | removes a transport if a member of this group | [
"removes",
"a",
"transport",
"if",
"a",
"member",
"of",
"this",
"group"
] | python | train | 33.166667 |
ResidentMario/geoplot | geoplot/geoplot.py | https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2482-L2527 | def _paint_carto_legend(ax, values, legend_values, legend_labels, scale_func, legend_kwargs):
"""
Creates a legend and attaches it to the axis. Meant to be used when a ``legend=True`` parameter is passed.
Parameters
----------
ax : matplotlib.Axes instance
The ``matplotlib.Axes`` instance o... | [
"def",
"_paint_carto_legend",
"(",
"ax",
",",
"values",
",",
"legend_values",
",",
"legend_labels",
",",
"scale_func",
",",
"legend_kwargs",
")",
":",
"# Set up the legend values.",
"if",
"legend_values",
"is",
"not",
"None",
":",
"display_values",
"=",
"legend_valu... | Creates a legend and attaches it to the axis. Meant to be used when a ``legend=True`` parameter is passed.
Parameters
----------
ax : matplotlib.Axes instance
The ``matplotlib.Axes`` instance on which a legend is being painted.
values : list
A list of values being plotted. May be either... | [
"Creates",
"a",
"legend",
"and",
"attaches",
"it",
"to",
"the",
"axis",
".",
"Meant",
"to",
"be",
"used",
"when",
"a",
"legend",
"=",
"True",
"parameter",
"is",
"passed",
"."
] | python | train | 47.369565 |
atztogo/phono3py | phono3py/phonon3/displacement_fc3.py | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/displacement_fc3.py#L218-L228 | def get_least_orbits(atom_index, cell, site_symmetry, symprec=1e-5):
"""Find least orbits for a centering atom"""
orbits = _get_orbits(atom_index, cell, site_symmetry, symprec)
mapping = np.arange(cell.get_number_of_atoms())
for i, orb in enumerate(orbits):
for num in np.unique(orb):
... | [
"def",
"get_least_orbits",
"(",
"atom_index",
",",
"cell",
",",
"site_symmetry",
",",
"symprec",
"=",
"1e-5",
")",
":",
"orbits",
"=",
"_get_orbits",
"(",
"atom_index",
",",
"cell",
",",
"site_symmetry",
",",
"symprec",
")",
"mapping",
"=",
"np",
".",
"ara... | Find least orbits for a centering atom | [
"Find",
"least",
"orbits",
"for",
"a",
"centering",
"atom"
] | python | train | 37.636364 |
mdavidsaver/p4p | src/p4p/client/raw.py | https://github.com/mdavidsaver/p4p/blob/c5e45eac01edfdad9cc2857bc283c7f2695802b8/src/p4p/client/raw.py#L253-L264 | def get(self, name, handler, request=None):
"""Begin Fetch of current value of a PV
:param name: A single name string or list of name strings
:param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default.
:param callable handler: Completion notifica... | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"handler",
",",
"request",
"=",
"None",
")",
":",
"chan",
"=",
"self",
".",
"_channel",
"(",
"name",
")",
"return",
"_p4p",
".",
"ClientOperation",
"(",
"chan",
",",
"handler",
"=",
"unwrapHandler",
"(",
"... | Begin Fetch of current value of a PV
:param name: A single name string or list of name strings
:param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default.
:param callable handler: Completion notification. Called with a Value, RemoteError, or Cancelled
... | [
"Begin",
"Fetch",
"of",
"current",
"value",
"of",
"a",
"PV"
] | python | train | 56.25 |
sorgerlab/indra | indra/literature/deft_tools.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/deft_tools.py#L46-L84 | def get_text_content_for_pmids(pmids):
"""Get text content for articles given a list of their pmids
Parameters
----------
pmids : list of str
Returns
-------
text_content : list of str
"""
pmc_pmids = set(pmc_client.filter_pmids(pmids, source_type='fulltext'))
pmc_ids = []
... | [
"def",
"get_text_content_for_pmids",
"(",
"pmids",
")",
":",
"pmc_pmids",
"=",
"set",
"(",
"pmc_client",
".",
"filter_pmids",
"(",
"pmids",
",",
"source_type",
"=",
"'fulltext'",
")",
")",
"pmc_ids",
"=",
"[",
"]",
"for",
"pmid",
"in",
"pmc_pmids",
":",
"p... | Get text content for articles given a list of their pmids
Parameters
----------
pmids : list of str
Returns
-------
text_content : list of str | [
"Get",
"text",
"content",
"for",
"articles",
"given",
"a",
"list",
"of",
"their",
"pmids"
] | python | train | 26.846154 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.