repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
kivy/python-for-android | pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/compiler.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/compiler.py#L861-L878 | def visit_Block(self, node, frame):
"""Call a block and register it for the template."""
level = 1
if frame.toplevel:
# if we know that we are a child template, there is no need to
# check if we are one
if self.has_known_extends:
return
... | [
"def",
"visit_Block",
"(",
"self",
",",
"node",
",",
"frame",
")",
":",
"level",
"=",
"1",
"if",
"frame",
".",
"toplevel",
":",
"# if we know that we are a child template, there is no need to",
"# check if we are one",
"if",
"self",
".",
"has_known_extends",
":",
"r... | Call a block and register it for the template. | [
"Call",
"a",
"block",
"and",
"register",
"it",
"for",
"the",
"template",
"."
] | python | train |
evhub/coconut | coconut/compiler/grammar.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/grammar.py#L445-L461 | def op_funcdef_handle(tokens):
"""Process infix defs."""
func, base_args = get_infix_items(tokens)
args = []
for arg in base_args[:-1]:
rstrip_arg = arg.rstrip()
if not rstrip_arg.endswith(unwrapper):
if not rstrip_arg.endswith(","):
arg += ", "
el... | [
"def",
"op_funcdef_handle",
"(",
"tokens",
")",
":",
"func",
",",
"base_args",
"=",
"get_infix_items",
"(",
"tokens",
")",
"args",
"=",
"[",
"]",
"for",
"arg",
"in",
"base_args",
"[",
":",
"-",
"1",
"]",
":",
"rstrip_arg",
"=",
"arg",
".",
"rstrip",
... | Process infix defs. | [
"Process",
"infix",
"defs",
"."
] | python | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/reference_device.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_device.py#L160-L169 | def close_streaming_interface(self):
"""Called when someone closes the streaming interface to the device.
This method will automatically notify sensor_graph that there is a no
longer a streaming interface opened.
"""
super(ReferenceDevice, self).close_streaming_interface()
... | [
"def",
"close_streaming_interface",
"(",
"self",
")",
":",
"super",
"(",
"ReferenceDevice",
",",
"self",
")",
".",
"close_streaming_interface",
"(",
")",
"self",
".",
"rpc",
"(",
"8",
",",
"rpcs",
".",
"SG_GRAPH_INPUT",
",",
"8",
",",
"streams",
".",
"COMM... | Called when someone closes the streaming interface to the device.
This method will automatically notify sensor_graph that there is a no
longer a streaming interface opened. | [
"Called",
"when",
"someone",
"closes",
"the",
"streaming",
"interface",
"to",
"the",
"device",
"."
] | python | train |
saltstack/salt | salt/runners/bgp.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/bgp.py#L203-L225 | def _display_runner(rows,
labels,
title,
display=_DEFAULT_DISPLAY,
outputter=_DEFAULT_OUTPUTTER):
'''
Display or return the rows.
'''
if display:
if outputter == 'table':
ret = salt.output.out_format({'ro... | [
"def",
"_display_runner",
"(",
"rows",
",",
"labels",
",",
"title",
",",
"display",
"=",
"_DEFAULT_DISPLAY",
",",
"outputter",
"=",
"_DEFAULT_OUTPUTTER",
")",
":",
"if",
"display",
":",
"if",
"outputter",
"==",
"'table'",
":",
"ret",
"=",
"salt",
".",
"out... | Display or return the rows. | [
"Display",
"or",
"return",
"the",
"rows",
"."
] | python | train |
saltstack/salt | salt/modules/elasticsearch.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L517-L537 | def index_delete(index, hosts=None, profile=None):
'''
Delete an index
index
Index name
CLI example::
salt myminion elasticsearch.index_delete testindex
'''
es = _get_instance(hosts, profile)
try:
result = es.indices.delete(index=index)
return result.get(... | [
"def",
"index_delete",
"(",
"index",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"es",
"=",
"_get_instance",
"(",
"hosts",
",",
"profile",
")",
"try",
":",
"result",
"=",
"es",
".",
"indices",
".",
"delete",
"(",
"index",
"=",
... | Delete an index
index
Index name
CLI example::
salt myminion elasticsearch.index_delete testindex | [
"Delete",
"an",
"index"
] | python | train |
insightindustry/validator-collection | validator_collection/validators.py | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2422-L2471 | def ip_address(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid IP address.
.. note::
First, the validator will check if the address is a valid IPv6 address.
If that doesn't work, the validator will check if the address is a valid
IPv... | [
"def",
"ip_address",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"el... | Validate that ``value`` is a valid IP address.
.. note::
First, the validator will check if the address is a valid IPv6 address.
If that doesn't work, the validator will check if the address is a valid
IPv4 address.
If neither works, the validator will raise an error (as always).
:pa... | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"IP",
"address",
"."
] | python | train |
openstates/billy | billy/web/public/views/bills.py | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/bills.py#L404-L425 | def vote(request, abbr, vote_id):
'''
Context:
- abbr
- metadata
- bill
- vote
- nav_active
Templates:
- vote.html
'''
vote = db.votes.find_one(vote_id)
if vote is None:
raise Http404('no such vote: {0}'.format(vote_id))
bill = vote.bi... | [
"def",
"vote",
"(",
"request",
",",
"abbr",
",",
"vote_id",
")",
":",
"vote",
"=",
"db",
".",
"votes",
".",
"find_one",
"(",
"vote_id",
")",
"if",
"vote",
"is",
"None",
":",
"raise",
"Http404",
"(",
"'no such vote: {0}'",
".",
"format",
"(",
"vote_id",... | Context:
- abbr
- metadata
- bill
- vote
- nav_active
Templates:
- vote.html | [
"Context",
":",
"-",
"abbr",
"-",
"metadata",
"-",
"bill",
"-",
"vote",
"-",
"nav_active"
] | python | train |
tanghaibao/goatools | goatools/gosubdag/godag_rcnt_init.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/godag_rcnt_init.py#L71-L83 | def get_depth2goobjs(go2obj, max_depth=2):
"""Init depth2goobjs using list sorted by depth, get level-00/01 GO terms."""
depth2goobjs = {d:list() for d in range(max_depth+1)}
goid_seen = set()
for _, goobj in sorted(go2obj.items(), key=lambda t: t[1].depth):
# Save depth-00, ... | [
"def",
"get_depth2goobjs",
"(",
"go2obj",
",",
"max_depth",
"=",
"2",
")",
":",
"depth2goobjs",
"=",
"{",
"d",
":",
"list",
"(",
")",
"for",
"d",
"in",
"range",
"(",
"max_depth",
"+",
"1",
")",
"}",
"goid_seen",
"=",
"set",
"(",
")",
"for",
"_",
... | Init depth2goobjs using list sorted by depth, get level-00/01 GO terms. | [
"Init",
"depth2goobjs",
"using",
"list",
"sorted",
"by",
"depth",
"get",
"level",
"-",
"00",
"/",
"01",
"GO",
"terms",
"."
] | python | train |
dshean/demcoreg | demcoreg/dem_mask.py | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L143-L158 | def get_bareground_mask(bareground_ds, bareground_thresh=60, out_fn=None):
"""Generate raster mask for exposed bare ground from global bareground data
"""
print("Loading bareground")
b = bareground_ds.GetRasterBand(1)
l = b.ReadAsArray()
print("Masking pixels with <%0.1f%% bare ground" % baregro... | [
"def",
"get_bareground_mask",
"(",
"bareground_ds",
",",
"bareground_thresh",
"=",
"60",
",",
"out_fn",
"=",
"None",
")",
":",
"print",
"(",
"\"Loading bareground\"",
")",
"b",
"=",
"bareground_ds",
".",
"GetRasterBand",
"(",
"1",
")",
"l",
"=",
"b",
".",
... | Generate raster mask for exposed bare ground from global bareground data | [
"Generate",
"raster",
"mask",
"for",
"exposed",
"bare",
"ground",
"from",
"global",
"bareground",
"data"
] | python | train |
PyCQA/pylint | pylint/graph.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/graph.py#L158-L170 | def get_cycles(graph_dict, vertices=None):
"""given a dictionary representing an ordered graph (i.e. key are vertices
and values is a list of destination vertices representing edges), return a
list of detected cycles
"""
if not graph_dict:
return ()
result = []
if vertices is None:
... | [
"def",
"get_cycles",
"(",
"graph_dict",
",",
"vertices",
"=",
"None",
")",
":",
"if",
"not",
"graph_dict",
":",
"return",
"(",
")",
"result",
"=",
"[",
"]",
"if",
"vertices",
"is",
"None",
":",
"vertices",
"=",
"graph_dict",
".",
"keys",
"(",
")",
"f... | given a dictionary representing an ordered graph (i.e. key are vertices
and values is a list of destination vertices representing edges), return a
list of detected cycles | [
"given",
"a",
"dictionary",
"representing",
"an",
"ordered",
"graph",
"(",
"i",
".",
"e",
".",
"key",
"are",
"vertices",
"and",
"values",
"is",
"a",
"list",
"of",
"destination",
"vertices",
"representing",
"edges",
")",
"return",
"a",
"list",
"of",
"detect... | python | test |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1290-L1434 | def get_relaxation(self, level, objective=None, inequalities=None,
equalities=None, substitutions=None,
momentinequalities=None, momentequalities=None,
momentsubstitutions=None,
removeequalities=False, extramonomials=None,
... | [
"def",
"get_relaxation",
"(",
"self",
",",
"level",
",",
"objective",
"=",
"None",
",",
"inequalities",
"=",
"None",
",",
"equalities",
"=",
"None",
",",
"substitutions",
"=",
"None",
",",
"momentinequalities",
"=",
"None",
",",
"momentequalities",
"=",
"Non... | Get the SDP relaxation of a noncommutative polynomial optimization
problem.
:param level: The level of the relaxation. The value -1 will skip
automatic monomial generation and use only the monomials
supplied by the option `extramonomials`.
:type level... | [
"Get",
"the",
"SDP",
"relaxation",
"of",
"a",
"noncommutative",
"polynomial",
"optimization",
"problem",
"."
] | python | train |
Grk0/python-libconf | libconf.py | https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L575-L606 | def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64... | [
"def",
"get_dump_type",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"'d'",
"if",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"return",
"'l'",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
"... | Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances. | [
"Get",
"the",
"libconfig",
"datatype",
"of",
"a",
"value"
] | python | train |
oceanprotocol/squid-py | squid_py/ocean/ocean_conditions.py | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_conditions.py#L28-L40 | def grant_access(self, agreement_id, did, grantee_address, account):
"""
Grant access condition.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param grantee_address: Address, hex str
:param account: Account
:return:
"""
r... | [
"def",
"grant_access",
"(",
"self",
",",
"agreement_id",
",",
"did",
",",
"grantee_address",
",",
"account",
")",
":",
"return",
"self",
".",
"_keeper",
".",
"access_secret_store_condition",
".",
"fulfill",
"(",
"agreement_id",
",",
"add_0x_prefix",
"(",
"did_to... | Grant access condition.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param grantee_address: Address, hex str
:param account: Account
:return: | [
"Grant",
"access",
"condition",
"."
] | python | train |
GPflow/GPflow | gpflow/training/monitor.py | https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/training/monitor.py#L238-L246 | def global_step(self) -> int:
"""
Evaluates the value of the global step variable if it is set, otherwise returns the
current iteration number.
"""
if self.session is None or self.global_step_tensor is None:
return self.iteration_no + self.init_global_step
els... | [
"def",
"global_step",
"(",
"self",
")",
"->",
"int",
":",
"if",
"self",
".",
"session",
"is",
"None",
"or",
"self",
".",
"global_step_tensor",
"is",
"None",
":",
"return",
"self",
".",
"iteration_no",
"+",
"self",
".",
"init_global_step",
"else",
":",
"r... | Evaluates the value of the global step variable if it is set, otherwise returns the
current iteration number. | [
"Evaluates",
"the",
"value",
"of",
"the",
"global",
"step",
"variable",
"if",
"it",
"is",
"set",
"otherwise",
"returns",
"the",
"current",
"iteration",
"number",
"."
] | python | train |
textX/textX | textx/metamodel.py | https://github.com/textX/textX/blob/5796ac38116ad86584392dbecdbf923ede746361/textx/metamodel.py#L619-L634 | def metamodel_from_file(file_name, **kwargs):
"""
Creates new metamodel from the given file.
Args:
file_name(str): The name of the file with textX language description.
other params: See metamodel_from_str.
"""
with codecs.open(file_name, 'r', 'utf-8') as f:
lang_desc = f.re... | [
"def",
"metamodel_from_file",
"(",
"file_name",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"file_name",
",",
"'r'",
",",
"'utf-8'",
")",
"as",
"f",
":",
"lang_desc",
"=",
"f",
".",
"read",
"(",
")",
"metamodel",
"=",
"meta... | Creates new metamodel from the given file.
Args:
file_name(str): The name of the file with textX language description.
other params: See metamodel_from_str. | [
"Creates",
"new",
"metamodel",
"from",
"the",
"given",
"file",
"."
] | python | train |
sailthru/relay | relay/plugins/__init__.py | https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/relay/plugins/__init__.py#L155-L172 | def stop_if_mostly_diverging(errdata):
"""This is an example stop condition that asks Relay to quit if
the error difference between consecutive samples is increasing more than
half of the time.
It's quite sensitive and designed for the demo, so you probably shouldn't
use this is a production settin... | [
"def",
"stop_if_mostly_diverging",
"(",
"errdata",
")",
":",
"n_increases",
"=",
"sum",
"(",
"[",
"abs",
"(",
"y",
")",
"-",
"abs",
"(",
"x",
")",
">",
"0",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"errdata",
",",
"errdata",
"[",
"1",
":",
"]",
... | This is an example stop condition that asks Relay to quit if
the error difference between consecutive samples is increasing more than
half of the time.
It's quite sensitive and designed for the demo, so you probably shouldn't
use this is a production setting | [
"This",
"is",
"an",
"example",
"stop",
"condition",
"that",
"asks",
"Relay",
"to",
"quit",
"if",
"the",
"error",
"difference",
"between",
"consecutive",
"samples",
"is",
"increasing",
"more",
"than",
"half",
"of",
"the",
"time",
"."
] | python | train |
tensorflow/mesh | mesh_tensorflow/ops.py | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4456-L4483 | def _parse_string_to_list_of_pairs(s, seconds_to_int=False):
r"""Parses a string into a list of pairs.
In the input string, each pair is separated by a colon, and the delimiters
between pairs are any of " ,.;".
e.g. "rows:32,cols:32"
Args:
s: str to parse.
seconds_to_int: Boolean. If True, then the... | [
"def",
"_parse_string_to_list_of_pairs",
"(",
"s",
",",
"seconds_to_int",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"p",
"in",
"[",
"s",
".",
"split",
"(",
"\":\"",
")",
"for",
"s",
"in",
"re",
".",
"sub",
"(",
"\"[,.;]\"",
",",
"\" \"",
... | r"""Parses a string into a list of pairs.
In the input string, each pair is separated by a colon, and the delimiters
between pairs are any of " ,.;".
e.g. "rows:32,cols:32"
Args:
s: str to parse.
seconds_to_int: Boolean. If True, then the second elements are returned
as integers; otherwise the... | [
"r",
"Parses",
"a",
"string",
"into",
"a",
"list",
"of",
"pairs",
"."
] | python | train |
openstack/python-scciclient | scciclient/irmc/elcm.py | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L821-L842 | def set_secure_boot_mode(irmc_info, enable):
"""Enable/Disable secure boot on the server.
:param irmc_info: node info
:param enable: True, if secure boot needs to be
enabled for next boot, else False.
"""
bios_config_data = {
'Server': {
'@Version': '1.01',
... | [
"def",
"set_secure_boot_mode",
"(",
"irmc_info",
",",
"enable",
")",
":",
"bios_config_data",
"=",
"{",
"'Server'",
":",
"{",
"'@Version'",
":",
"'1.01'",
",",
"'SystemConfig'",
":",
"{",
"'BiosConfig'",
":",
"{",
"'@Version'",
":",
"'1.01'",
",",
"'SecurityCo... | Enable/Disable secure boot on the server.
:param irmc_info: node info
:param enable: True, if secure boot needs to be
enabled for next boot, else False. | [
"Enable",
"/",
"Disable",
"secure",
"boot",
"on",
"the",
"server",
"."
] | python | train |
rabitt/pysox | sox/core.py | https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/core.py#L65-L85 | def _get_valid_formats():
''' Calls SoX help for a lists of audio formats available with the current
install of SoX.
Returns:
--------
formats : list
List of audio file extensions that SoX can process.
'''
if NO_SOX:
return []
so = subprocess.check_output(['sox', '-h']... | [
"def",
"_get_valid_formats",
"(",
")",
":",
"if",
"NO_SOX",
":",
"return",
"[",
"]",
"so",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'sox'",
",",
"'-h'",
"]",
")",
"if",
"type",
"(",
"so",
")",
"is",
"not",
"str",
":",
"so",
"=",
"str",
... | Calls SoX help for a lists of audio formats available with the current
install of SoX.
Returns:
--------
formats : list
List of audio file extensions that SoX can process. | [
"Calls",
"SoX",
"help",
"for",
"a",
"lists",
"of",
"audio",
"formats",
"available",
"with",
"the",
"current",
"install",
"of",
"SoX",
"."
] | python | valid |
ibis-project/ibis | ibis/expr/rules.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/rules.py#L55-L69 | def cast(source, target):
"""Currently Literal to *Scalar implicit casts are allowed"""
import ibis.expr.operations as ops # TODO: don't use ops here
if not castable(source, target):
raise com.IbisTypeError('Source is not castable to target type!')
# currently it prevents column -> scalar imp... | [
"def",
"cast",
"(",
"source",
",",
"target",
")",
":",
"import",
"ibis",
".",
"expr",
".",
"operations",
"as",
"ops",
"# TODO: don't use ops here",
"if",
"not",
"castable",
"(",
"source",
",",
"target",
")",
":",
"raise",
"com",
".",
"IbisTypeError",
"(",
... | Currently Literal to *Scalar implicit casts are allowed | [
"Currently",
"Literal",
"to",
"*",
"Scalar",
"implicit",
"casts",
"are",
"allowed"
] | python | train |
tensorflow/cleverhans | cleverhans/future/tf2/utils_tf.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/utils_tf.py#L5-L33 | def clip_eta(eta, ord, eps):
"""
Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation.
"""
# Clipping p... | [
"def",
"clip_eta",
"(",
"eta",
",",
"ord",
",",
"eps",
")",
":",
"# Clipping perturbation eta to self.ord norm ball",
"if",
"ord",
"not",
"in",
"[",
"np",
".",
"inf",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"'ord must be np.inf, 1, or 2.'",
... | Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation. | [
"Helper",
"function",
"to",
"clip",
"the",
"perturbation",
"to",
"epsilon",
"norm",
"ball",
".",
":",
"param",
"eta",
":",
"A",
"tensor",
"with",
"the",
"current",
"perturbation",
".",
":",
"param",
"ord",
":",
"Order",
"of",
"the",
"norm",
"(",
"mimics"... | python | train |
TurboGears/gearbox | gearbox/commands/serve.py | https://github.com/TurboGears/gearbox/blob/df496ab28050ce6a4cc4c502488f5c5812f2baff/gearbox/commands/serve.py#L313-L326 | def parse_vars(self, args):
"""
Given variables like ``['a=b', 'c=d']`` turns it into ``{'a':
'b', 'c': 'd'}``
"""
result = {}
for arg in args:
if '=' not in arg:
raise ValueError(
'Variable assignment %r invalid (no "=")'
... | [
"def",
"parse_vars",
"(",
"self",
",",
"args",
")",
":",
"result",
"=",
"{",
"}",
"for",
"arg",
"in",
"args",
":",
"if",
"'='",
"not",
"in",
"arg",
":",
"raise",
"ValueError",
"(",
"'Variable assignment %r invalid (no \"=\")'",
"%",
"arg",
")",
"name",
"... | Given variables like ``['a=b', 'c=d']`` turns it into ``{'a':
'b', 'c': 'd'}`` | [
"Given",
"variables",
"like",
"[",
"a",
"=",
"b",
"c",
"=",
"d",
"]",
"turns",
"it",
"into",
"{",
"a",
":",
"b",
"c",
":",
"d",
"}"
] | python | train |
draperjames/qtpandas | qtpandas/models/DataFrameModelManager.py | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModelManager.py#L111-L129 | def set_model(self, df_model, file_path):
"""
Sets a DataFrameModel and registers it to the given file_path.
:param df_model: (DataFrameModel)
The DataFrameModel to register.
:param file_path:
The file path to associate with the DataFrameModel.
*Overri... | [
"def",
"set_model",
"(",
"self",
",",
"df_model",
",",
"file_path",
")",
":",
"assert",
"isinstance",
"(",
"df_model",
",",
"DataFrameModel",
")",
",",
"\"df_model argument must be a DataFrameModel!\"",
"df_model",
".",
"_filePath",
"=",
"file_path",
"try",
":",
"... | Sets a DataFrameModel and registers it to the given file_path.
:param df_model: (DataFrameModel)
The DataFrameModel to register.
:param file_path:
The file path to associate with the DataFrameModel.
*Overrides the current filePath on the DataFrameModel (if any)
... | [
"Sets",
"a",
"DataFrameModel",
"and",
"registers",
"it",
"to",
"the",
"given",
"file_path",
".",
":",
"param",
"df_model",
":",
"(",
"DataFrameModel",
")",
"The",
"DataFrameModel",
"to",
"register",
".",
":",
"param",
"file_path",
":",
"The",
"file",
"path",... | python | train |
Beyond-Digital/django-gaekit | gaekit/boot.py | https://github.com/Beyond-Digital/django-gaekit/blob/b587acd52b5cfd48217a70920d4b61d5f923c8c5/gaekit/boot.py#L1-L17 | def break_sandbox():
"""Patches sandbox to add match-all regex to sandbox whitelist
"""
class EvilCM(object):
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
import re
tb.tb_next.tb_next.tb_next.tb_frame.f_locals[
'... | [
"def",
"break_sandbox",
"(",
")",
":",
"class",
"EvilCM",
"(",
"object",
")",
":",
"def",
"__enter__",
"(",
"self",
")",
":",
"return",
"self",
"def",
"__exit__",
"(",
"self",
",",
"exc_type",
",",
"exc",
",",
"tb",
")",
":",
"import",
"re",
"tb",
... | Patches sandbox to add match-all regex to sandbox whitelist | [
"Patches",
"sandbox",
"to",
"add",
"match",
"-",
"all",
"regex",
"to",
"sandbox",
"whitelist"
] | python | train |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L635-L654 | def defUtilityFuncs(self):
'''
Defines CRRA utility function for this period (and its derivatives,
and their inverses), saving them as attributes of self for other methods
to use.
Parameters
----------
none
Returns
-------
none
''... | [
"def",
"defUtilityFuncs",
"(",
"self",
")",
":",
"ConsPerfForesightSolver",
".",
"defUtilityFuncs",
"(",
"self",
")",
"self",
".",
"uPinv",
"=",
"lambda",
"u",
":",
"utilityP_inv",
"(",
"u",
",",
"gam",
"=",
"self",
".",
"CRRA",
")",
"self",
".",
"uPinvP... | Defines CRRA utility function for this period (and its derivatives,
and their inverses), saving them as attributes of self for other methods
to use.
Parameters
----------
none
Returns
-------
none | [
"Defines",
"CRRA",
"utility",
"function",
"for",
"this",
"period",
"(",
"and",
"its",
"derivatives",
"and",
"their",
"inverses",
")",
"saving",
"them",
"as",
"attributes",
"of",
"self",
"for",
"other",
"methods",
"to",
"use",
"."
] | python | train |
mbedmicro/pyOCD | pyocd/flash/flash_builder.py | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/flash/flash_builder.py#L174-L212 | def add_data(self, addr, data):
"""! @brief Add a block of data to be programmed.
@note Programming does not start until the method program() is called.
@param self
@param addr Base address of the block of data passed to this method. The entire block of
data must be... | [
"def",
"add_data",
"(",
"self",
",",
"addr",
",",
"data",
")",
":",
"# Ignore empty data.",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"# Sanity check",
"if",
"not",
"self",
".",
"flash",
".",
"region",
".",
"contains_range",
"(",
"start",
... | ! @brief Add a block of data to be programmed.
@note Programming does not start until the method program() is called.
@param self
@param addr Base address of the block of data passed to this method. The entire block of
data must be contained within the flash memory region a... | [
"!",
"@brief",
"Add",
"a",
"block",
"of",
"data",
"to",
"be",
"programmed",
"."
] | python | train |
django-danceschool/django-danceschool | danceschool/financial/admin.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/admin.py#L382-L389 | def resetStaffCompensationInfo(self, request, queryset):
'''
This action is added to the list for staff member to permit bulk
reseting to category defaults of compensation information for staff members.
'''
selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
ct = ContentType.objects.get_... | [
"def",
"resetStaffCompensationInfo",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"selected",
"=",
"request",
".",
"POST",
".",
"getlist",
"(",
"admin",
".",
"ACTION_CHECKBOX_NAME",
")",
"ct",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model"... | This action is added to the list for staff member to permit bulk
reseting to category defaults of compensation information for staff members. | [
"This",
"action",
"is",
"added",
"to",
"the",
"list",
"for",
"staff",
"member",
"to",
"permit",
"bulk",
"reseting",
"to",
"category",
"defaults",
"of",
"compensation",
"information",
"for",
"staff",
"members",
"."
] | python | train |
burnash/gspread | gspread/models.py | https://github.com/burnash/gspread/blob/0e8debe208095aeed3e3e7136c2fa5cd74090946/gspread/models.py#L675-L705 | def col_values(self, col, value_render_option='FORMATTED_VALUE'):
"""Returns a list of all values in column `col`.
Empty cells in this list will be rendered as :const:`None`.
:param col: Column number.
:type col: int
:param value_render_option: (optional) Determines how values ... | [
"def",
"col_values",
"(",
"self",
",",
"col",
",",
"value_render_option",
"=",
"'FORMATTED_VALUE'",
")",
":",
"start_label",
"=",
"rowcol_to_a1",
"(",
"1",
",",
"col",
")",
"range_label",
"=",
"'%s!%s:%s'",
"%",
"(",
"self",
".",
"title",
",",
"start_label",... | Returns a list of all values in column `col`.
Empty cells in this list will be rendered as :const:`None`.
:param col: Column number.
:type col: int
:param value_render_option: (optional) Determines how values should be
rendered in the the output. See... | [
"Returns",
"a",
"list",
"of",
"all",
"values",
"in",
"column",
"col",
"."
] | python | train |
jangler/readlike | readlike.py | https://github.com/jangler/readlike/blob/2901260c50bd1aecfb981c3990e0c6333de8aac8/readlike.py#L51-L55 | def _backward_delete_char(text, pos):
"""Delete the character behind pos."""
if pos == 0:
return text, pos
return text[:pos - 1] + text[pos:], pos - 1 | [
"def",
"_backward_delete_char",
"(",
"text",
",",
"pos",
")",
":",
"if",
"pos",
"==",
"0",
":",
"return",
"text",
",",
"pos",
"return",
"text",
"[",
":",
"pos",
"-",
"1",
"]",
"+",
"text",
"[",
"pos",
":",
"]",
",",
"pos",
"-",
"1"
] | Delete the character behind pos. | [
"Delete",
"the",
"character",
"behind",
"pos",
"."
] | python | train |
O365/python-o365 | O365/mailbox.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/mailbox.py#L434-L468 | def move_folder(self, to_folder, *, update_parent_if_changed=True):
""" Move this folder to another folder
:param to_folder: the destination Folder/folder_id to move into
:type to_folder: mailbox.Folder or str
:param bool update_parent_if_changed: updates self.parent with the
n... | [
"def",
"move_folder",
"(",
"self",
",",
"to_folder",
",",
"*",
",",
"update_parent_if_changed",
"=",
"True",
")",
":",
"to_folder_id",
"=",
"to_folder",
".",
"folder_id",
"if",
"isinstance",
"(",
"to_folder",
",",
"Folder",
")",
"else",
"to_folder",
"if",
"s... | Move this folder to another folder
:param to_folder: the destination Folder/folder_id to move into
:type to_folder: mailbox.Folder or str
:param bool update_parent_if_changed: updates self.parent with the
new parent Folder if changed
:return: The new folder after copying
... | [
"Move",
"this",
"folder",
"to",
"another",
"folder"
] | python | train |
Nic30/hwt | hwt/simulator/hdlSimulator.py | https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L532-L536 | def add_process(self, proc) -> None:
"""
Add process to events with default priority on current time
"""
self._events.push(self.now, PRIORITY_NORMAL, proc) | [
"def",
"add_process",
"(",
"self",
",",
"proc",
")",
"->",
"None",
":",
"self",
".",
"_events",
".",
"push",
"(",
"self",
".",
"now",
",",
"PRIORITY_NORMAL",
",",
"proc",
")"
] | Add process to events with default priority on current time | [
"Add",
"process",
"to",
"events",
"with",
"default",
"priority",
"on",
"current",
"time"
] | python | test |
gatagat/lap | lap/lapmod.py | https://github.com/gatagat/lap/blob/c2b6309ba246d18205a71228cdaea67210e1a039/lap/lapmod.py#L273-L341 | def lapmod(n, cc, ii, kk, fast=True, return_cost=True,
fp_version=FP_DYNAMIC):
"""Solve sparse linear assignment problem using Jonker-Volgenant algorithm.
n: number of rows of the assignment cost matrix
cc: 1D array of all finite elements of the assignement cost matrix
ii: 1D array of indice... | [
"def",
"lapmod",
"(",
"n",
",",
"cc",
",",
"ii",
",",
"kk",
",",
"fast",
"=",
"True",
",",
"return_cost",
"=",
"True",
",",
"fp_version",
"=",
"FP_DYNAMIC",
")",
":",
"# log = logging.getLogger('lapmod')",
"check_cost",
"(",
"n",
",",
"cc",
",",
"ii",
... | Solve sparse linear assignment problem using Jonker-Volgenant algorithm.
n: number of rows of the assignment cost matrix
cc: 1D array of all finite elements of the assignement cost matrix
ii: 1D array of indices of the row starts in cc. The following must hold:
ii[0] = 0 and ii[n+1] = len(cc).
... | [
"Solve",
"sparse",
"linear",
"assignment",
"problem",
"using",
"Jonker",
"-",
"Volgenant",
"algorithm",
"."
] | python | train |
edx/completion | completion/services.py | https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/services.py#L114-L120 | def blocks_to_mark_complete_on_view(self, blocks):
"""
Returns a set of blocks which should be marked complete on view and haven't been yet.
"""
blocks = {block for block in blocks if self.can_mark_block_complete_on_view(block)}
completions = self.get_completions({block.location ... | [
"def",
"blocks_to_mark_complete_on_view",
"(",
"self",
",",
"blocks",
")",
":",
"blocks",
"=",
"{",
"block",
"for",
"block",
"in",
"blocks",
"if",
"self",
".",
"can_mark_block_complete_on_view",
"(",
"block",
")",
"}",
"completions",
"=",
"self",
".",
"get_com... | Returns a set of blocks which should be marked complete on view and haven't been yet. | [
"Returns",
"a",
"set",
"of",
"blocks",
"which",
"should",
"be",
"marked",
"complete",
"on",
"view",
"and",
"haven",
"t",
"been",
"yet",
"."
] | python | train |
i3visio/osrframework | osrframework/thirdparties/pipl_com/lib/search.py | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/search.py#L180-L207 | def _prepare_filtering_params(domain=None, category=None,
sponsored_source=None, has_field=None,
has_fields=None, query_params_match=None,
query_person_match=None, **kwargs):
"""Transform the params to th... | [
"def",
"_prepare_filtering_params",
"(",
"domain",
"=",
"None",
",",
"category",
"=",
"None",
",",
"sponsored_source",
"=",
"None",
",",
"has_field",
"=",
"None",
",",
"has_fields",
"=",
"None",
",",
"query_params_match",
"=",
"None",
",",
"query_person_match",
... | Transform the params to the API format, return a list of params. | [
"Transform",
"the",
"params",
"to",
"the",
"API",
"format",
"return",
"a",
"list",
"of",
"params",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/util/serialization.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/util/serialization.py#L77-L98 | def persistent_load(self, pid):
"""
This method is invoked whenever a persistent ID is encountered.
Here, pid is the tuple returned by PmgPickler.
"""
try:
type_tag, key_id = pid
except Exception as exc:
# Sometimes we get a string such as ('Elemen... | [
"def",
"persistent_load",
"(",
"self",
",",
"pid",
")",
":",
"try",
":",
"type_tag",
",",
"key_id",
"=",
"pid",
"except",
"Exception",
"as",
"exc",
":",
"# Sometimes we get a string such as ('Element', u'C') instead",
"# of a real tuple. Use ast to evalute the expression (m... | This method is invoked whenever a persistent ID is encountered.
Here, pid is the tuple returned by PmgPickler. | [
"This",
"method",
"is",
"invoked",
"whenever",
"a",
"persistent",
"ID",
"is",
"encountered",
".",
"Here",
"pid",
"is",
"the",
"tuple",
"returned",
"by",
"PmgPickler",
"."
] | python | train |
quikmile/trellio | trellio/utils/log.py | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/utils/log.py#L21-L32 | def formatTime(self, record, datefmt=None): # noqa
"""
Overrides formatTime method to use datetime module instead of time module
to display time in microseconds. Time module by default does not resolve
time to microseconds.
"""
if datefmt:
s = datetime.dateti... | [
"def",
"formatTime",
"(",
"self",
",",
"record",
",",
"datefmt",
"=",
"None",
")",
":",
"# noqa",
"if",
"datefmt",
":",
"s",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"datefmt",
")",
"else",
":",
"t",
"=",
"datet... | Overrides formatTime method to use datetime module instead of time module
to display time in microseconds. Time module by default does not resolve
time to microseconds. | [
"Overrides",
"formatTime",
"method",
"to",
"use",
"datetime",
"module",
"instead",
"of",
"time",
"module",
"to",
"display",
"time",
"in",
"microseconds",
".",
"Time",
"module",
"by",
"default",
"does",
"not",
"resolve",
"time",
"to",
"microseconds",
"."
] | python | train |
iotaledger/iota.lib.py | iota/adapter/wrappers.py | https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/adapter/wrappers.py#L77-L98 | def add_route(self, command, adapter):
# type: (Text, AdapterSpec) -> RoutingWrapper
"""
Adds a route to the wrapper.
:param command:
The name of the command to route (e.g., "attachToTangle").
:param adapter:
The adapter object or URI to route requests t... | [
"def",
"add_route",
"(",
"self",
",",
"command",
",",
"adapter",
")",
":",
"# type: (Text, AdapterSpec) -> RoutingWrapper",
"if",
"not",
"isinstance",
"(",
"adapter",
",",
"BaseAdapter",
")",
":",
"try",
":",
"adapter",
"=",
"self",
".",
"adapter_aliases",
"[",
... | Adds a route to the wrapper.
:param command:
The name of the command to route (e.g., "attachToTangle").
:param adapter:
The adapter object or URI to route requests to. | [
"Adds",
"a",
"route",
"to",
"the",
"wrapper",
"."
] | python | test |
RJT1990/pyflux | pyflux/arma/nnarx.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/nnarx.py#L430-L447 | def general_neg_loglik(self, beta):
""" Calculates the negative log-likelihood of the model
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model
... | [
"def",
"general_neg_loglik",
"(",
"self",
",",
"beta",
")",
":",
"mu",
",",
"Y",
"=",
"self",
".",
"_model",
"(",
"beta",
")",
"parm",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"latent_variables",
".",
"z_list",
"[",
"k",
"]",
".",
"prior",
... | Calculates the negative log-likelihood of the model
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model | [
"Calculates",
"the",
"negative",
"log",
"-",
"likelihood",
"of",
"the",
"model"
] | python | train |
bspaans/python-mingus | mingus/extra/tunings.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L95-L143 | def find_fingering(self, notes, max_distance=4, not_strings=[]):
"""Return a list [(string, fret)] of possible fingerings for
'notes'.
The notes parameter should be a list of strings or Notes or a
NoteContainer; max_distance denotes the maximum distance between
frets; not_string... | [
"def",
"find_fingering",
"(",
"self",
",",
"notes",
",",
"max_distance",
"=",
"4",
",",
"not_strings",
"=",
"[",
"]",
")",
":",
"if",
"notes",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"len",
"(",
"notes",
")",
"==",
"0",
":",
"return",
"[",
"... | Return a list [(string, fret)] of possible fingerings for
'notes'.
The notes parameter should be a list of strings or Notes or a
NoteContainer; max_distance denotes the maximum distance between
frets; not_strings can be used to disclude certain strings and is
used internally to ... | [
"Return",
"a",
"list",
"[",
"(",
"string",
"fret",
")",
"]",
"of",
"possible",
"fingerings",
"for",
"notes",
"."
] | python | train |
dpgaspar/Flask-AppBuilder | flask_appbuilder/security/sqla/manager.py | https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/security/sqla/manager.py#L344-L355 | def find_permission_view_menu(self, permission_name, view_menu_name):
"""
Finds and returns a PermissionView by names
"""
permission = self.find_permission(permission_name)
view_menu = self.find_view_menu(view_menu_name)
if permission and view_menu:
return... | [
"def",
"find_permission_view_menu",
"(",
"self",
",",
"permission_name",
",",
"view_menu_name",
")",
":",
"permission",
"=",
"self",
".",
"find_permission",
"(",
"permission_name",
")",
"view_menu",
"=",
"self",
".",
"find_view_menu",
"(",
"view_menu_name",
")",
"... | Finds and returns a PermissionView by names | [
"Finds",
"and",
"returns",
"a",
"PermissionView",
"by",
"names"
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/quaternion.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/quaternion.py#L551-L561 | def _dcm_array_to_matrix3(self, dcm):
"""
Converts dcm array into Matrix3
:param dcm: 3x3 dcm array
:returns: Matrix3
"""
assert(dcm.shape == (3, 3))
a = Vector3(dcm[0][0], dcm[0][1], dcm[0][2])
b = Vector3(dcm[1][0], dcm[1][1], dcm[1][2])
c = Vect... | [
"def",
"_dcm_array_to_matrix3",
"(",
"self",
",",
"dcm",
")",
":",
"assert",
"(",
"dcm",
".",
"shape",
"==",
"(",
"3",
",",
"3",
")",
")",
"a",
"=",
"Vector3",
"(",
"dcm",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"dcm",
"[",
"0",
"]",
"[",
"1",
"... | Converts dcm array into Matrix3
:param dcm: 3x3 dcm array
:returns: Matrix3 | [
"Converts",
"dcm",
"array",
"into",
"Matrix3",
":",
"param",
"dcm",
":",
"3x3",
"dcm",
"array",
":",
"returns",
":",
"Matrix3"
] | python | train |
openthread/openthread | tools/harness-thci/OpenThread.py | https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-thci/OpenThread.py#L1988-L2021 | def scanJoiner(self, xEUI='*', strPSKd='threadjpaketest'):
"""scan Joiner
Args:
xEUI: Joiner's EUI-64
strPSKd: Joiner's PSKd for commissioning
Returns:
True: successful to add Joiner's steering data
False: fail to add Joiner's steering data
... | [
"def",
"scanJoiner",
"(",
"self",
",",
"xEUI",
"=",
"'*'",
",",
"strPSKd",
"=",
"'threadjpaketest'",
")",
":",
"print",
"'%s call scanJoiner'",
"%",
"self",
".",
"port",
"# long timeout value to avoid automatic joiner removal (in seconds)",
"timeout",
"=",
"500",
"if"... | scan Joiner
Args:
xEUI: Joiner's EUI-64
strPSKd: Joiner's PSKd for commissioning
Returns:
True: successful to add Joiner's steering data
False: fail to add Joiner's steering data | [
"scan",
"Joiner"
] | python | train |
log2timeline/plaso | plaso/preprocessors/macos.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/preprocessors/macos.py#L47-L93 | def _ParseFileData(self, knowledge_base, file_object):
"""Parses file content (data) for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.
Raises... | [
"def",
"_ParseFileData",
"(",
"self",
",",
"knowledge_base",
",",
"file_object",
")",
":",
"plist_file",
"=",
"plist",
".",
"PlistFile",
"(",
")",
"try",
":",
"plist_file",
".",
"Read",
"(",
"file_object",
")",
"except",
"IOError",
"as",
"exception",
":",
... | Parses file content (data) for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. | [
"Parses",
"file",
"content",
"(",
"data",
")",
"for",
"a",
"preprocessing",
"attribute",
"."
] | python | train |
Clinical-Genomics/scout | scout/server/blueprints/cases/controllers.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/server/blueprints/cases/controllers.py#L261-L306 | def coverage_report_contents(store, institute_obj, case_obj, base_url):
"""Posts a request to chanjo-report and capture the body of the returned response to include it in case report
Args:
store(adapter.MongoAdapter)
institute_obj(models.Institute)
case_obj(models.Case)
base_url... | [
"def",
"coverage_report_contents",
"(",
"store",
",",
"institute_obj",
",",
"case_obj",
",",
"base_url",
")",
":",
"request_data",
"=",
"{",
"}",
"# extract sample ids from case_obj and add them to the post request object:",
"request_data",
"[",
"'sample_id'",
"]",
"=",
"... | Posts a request to chanjo-report and capture the body of the returned response to include it in case report
Args:
store(adapter.MongoAdapter)
institute_obj(models.Institute)
case_obj(models.Case)
base_url(str): base url of server
Returns:
coverage_data(str): string rend... | [
"Posts",
"a",
"request",
"to",
"chanjo",
"-",
"report",
"and",
"capture",
"the",
"body",
"of",
"the",
"returned",
"response",
"to",
"include",
"it",
"in",
"case",
"report"
] | python | test |
BoGoEngine/bogo-python | bogo/core.py | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L469-L489 | def _can_undo(comps, trans_list):
"""
Return whether a components can be undone with one of the transformation in
trans_list.
"""
comps = list(comps)
accent_list = list(map(accent.get_accent_char, comps[1]))
mark_list = list(map(mark.get_mark_char, utils.join(comps)))
action_list = list(... | [
"def",
"_can_undo",
"(",
"comps",
",",
"trans_list",
")",
":",
"comps",
"=",
"list",
"(",
"comps",
")",
"accent_list",
"=",
"list",
"(",
"map",
"(",
"accent",
".",
"get_accent_char",
",",
"comps",
"[",
"1",
"]",
")",
")",
"mark_list",
"=",
"list",
"(... | Return whether a components can be undone with one of the transformation in
trans_list. | [
"Return",
"whether",
"a",
"components",
"can",
"be",
"undone",
"with",
"one",
"of",
"the",
"transformation",
"in",
"trans_list",
"."
] | python | train |
noahbenson/neuropythy | neuropythy/geometry/util.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/geometry/util.py#L23-L31 | def vector_angle_cos(u, v):
'''
vector_angle_cos(u, v) yields the cosine of the angle between the two vectors u and v. If u
or v (or both) is a (d x n) matrix of n vectors, the result will be a length n vector of the
cosines.
'''
u = np.asarray(u)
v = np.asarray(v)
return (u * v).sum(0) ... | [
"def",
"vector_angle_cos",
"(",
"u",
",",
"v",
")",
":",
"u",
"=",
"np",
".",
"asarray",
"(",
"u",
")",
"v",
"=",
"np",
".",
"asarray",
"(",
"v",
")",
"return",
"(",
"u",
"*",
"v",
")",
".",
"sum",
"(",
"0",
")",
"/",
"np",
".",
"sqrt",
"... | vector_angle_cos(u, v) yields the cosine of the angle between the two vectors u and v. If u
or v (or both) is a (d x n) matrix of n vectors, the result will be a length n vector of the
cosines. | [
"vector_angle_cos",
"(",
"u",
"v",
")",
"yields",
"the",
"cosine",
"of",
"the",
"angle",
"between",
"the",
"two",
"vectors",
"u",
"and",
"v",
".",
"If",
"u",
"or",
"v",
"(",
"or",
"both",
")",
"is",
"a",
"(",
"d",
"x",
"n",
")",
"matrix",
"of",
... | python | train |
bioasp/ingranalyze | src/query.py | https://github.com/bioasp/ingranalyze/blob/60bdd679b6044a4d142abbca5bbe3cd5e9fd7596/src/query.py#L198-L214 | def whatsnew(instance,pred):
'''
[whatsnew(instance,pred)] is a TermSet equal to [pred] where all predicates
vlabel and elabel which have a corresponding obs_vlabel and obs_elabel in
[instance] have been deleted. This function is meant to see which of the invariants
are not a direct consequence of t... | [
"def",
"whatsnew",
"(",
"instance",
",",
"pred",
")",
":",
"accu",
"=",
"TermSet",
"(",
"pred",
")",
"for",
"t",
"in",
"instance",
":",
"if",
"t",
".",
"pred",
"(",
")",
"==",
"'obs_vlabel'",
":",
"[",
"_",
",",
"e",
",",
"v",
",",
"s",
"]",
... | [whatsnew(instance,pred)] is a TermSet equal to [pred] where all predicates
vlabel and elabel which have a corresponding obs_vlabel and obs_elabel in
[instance] have been deleted. This function is meant to see which of the invariants
are not a direct consequence of the observations. | [
"[",
"whatsnew",
"(",
"instance",
"pred",
")",
"]",
"is",
"a",
"TermSet",
"equal",
"to",
"[",
"pred",
"]",
"where",
"all",
"predicates",
"vlabel",
"and",
"elabel",
"which",
"have",
"a",
"corresponding",
"obs_vlabel",
"and",
"obs_elabel",
"in",
"[",
"instan... | python | train |
mnick/scikit-tensor | sktensor/sptensor.py | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/sptensor.py#L179-L195 | def _ttm_me_compute(self, V, edims, sdims, transp):
"""
Assume Y = T x_i V_i for i = 1...n can fit into memory
"""
shapeY = np.copy(self.shape)
# Determine size of Y
for n in np.union1d(edims, sdims):
shapeY[n] = V[n].shape[1] if transp else V[n].shape[0]
... | [
"def",
"_ttm_me_compute",
"(",
"self",
",",
"V",
",",
"edims",
",",
"sdims",
",",
"transp",
")",
":",
"shapeY",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"shape",
")",
"# Determine size of Y",
"for",
"n",
"in",
"np",
".",
"union1d",
"(",
"edims",
","... | Assume Y = T x_i V_i for i = 1...n can fit into memory | [
"Assume",
"Y",
"=",
"T",
"x_i",
"V_i",
"for",
"i",
"=",
"1",
"...",
"n",
"can",
"fit",
"into",
"memory"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2189-L2214 | def running_global_pool_1d(inputs, pooling_type="MAX"):
"""Same global pool, but only for the elements up to the current element.
Useful for outputs where the state of future elements is not known.
Takes no mask as all elements up to the current element are assumed to exist.
Currently only supports maximum. Eq... | [
"def",
"running_global_pool_1d",
"(",
"inputs",
",",
"pooling_type",
"=",
"\"MAX\"",
")",
":",
"del",
"pooling_type",
"with",
"tf",
".",
"name_scope",
"(",
"\"running_global_pool\"",
",",
"values",
"=",
"[",
"inputs",
"]",
")",
":",
"scan_fct",
"=",
"tf",
".... | Same global pool, but only for the elements up to the current element.
Useful for outputs where the state of future elements is not known.
Takes no mask as all elements up to the current element are assumed to exist.
Currently only supports maximum. Equivalent to using a lower triangle bias.
Args:
inputs:... | [
"Same",
"global",
"pool",
"but",
"only",
"for",
"the",
"elements",
"up",
"to",
"the",
"current",
"element",
"."
] | python | train |
rochacbruno/python-pagseguro | pagseguro/__init__.py | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L260-L277 | def query_transactions(self, initial_date, final_date,
page=None,
max_results=None):
""" query transaction by date range """
last_page = False
results = []
while last_page is False:
search_result = self._consume_query_tran... | [
"def",
"query_transactions",
"(",
"self",
",",
"initial_date",
",",
"final_date",
",",
"page",
"=",
"None",
",",
"max_results",
"=",
"None",
")",
":",
"last_page",
"=",
"False",
"results",
"=",
"[",
"]",
"while",
"last_page",
"is",
"False",
":",
"search_re... | query transaction by date range | [
"query",
"transaction",
"by",
"date",
"range"
] | python | train |
pandas-dev/pandas | pandas/core/base.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/base.py#L86-L95 | def _reset_cache(self, key=None):
"""
Reset cached properties. If ``key`` is passed, only clears that key.
"""
if getattr(self, '_cache', None) is None:
return
if key is None:
self._cache.clear()
else:
self._cache.pop(key, None) | [
"def",
"_reset_cache",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_cache'",
",",
"None",
")",
"is",
"None",
":",
"return",
"if",
"key",
"is",
"None",
":",
"self",
".",
"_cache",
".",
"clear",
"(",
")",
"e... | Reset cached properties. If ``key`` is passed, only clears that key. | [
"Reset",
"cached",
"properties",
".",
"If",
"key",
"is",
"passed",
"only",
"clears",
"that",
"key",
"."
] | python | train |
BD2KOnFHIR/fhirtordf | fhirtordf/loaders/fhirresourceloader.py | https://github.com/BD2KOnFHIR/fhirtordf/blob/f97b3df683fa4caacf5cf4f29699ab060bcc0fbf/fhirtordf/loaders/fhirresourceloader.py#L157-L185 | def add_value_node(self, subj: Node, pred: URIRef, val: Union[JsonObj, str, List],
valuetype: Optional[URIRef]= None) -> None:
"""
Expand val according to the range of pred and add it to the graph
:param subj: graph subject
:param pred: graph predicate
:par... | [
"def",
"add_value_node",
"(",
"self",
",",
"subj",
":",
"Node",
",",
"pred",
":",
"URIRef",
",",
"val",
":",
"Union",
"[",
"JsonObj",
",",
"str",
",",
"List",
"]",
",",
"valuetype",
":",
"Optional",
"[",
"URIRef",
"]",
"=",
"None",
")",
"->",
"None... | Expand val according to the range of pred and add it to the graph
:param subj: graph subject
:param pred: graph predicate
:param val: JSON representation of target object
:param valuetype: predicate type if it can't be directly determined | [
"Expand",
"val",
"according",
"to",
"the",
"range",
"of",
"pred",
"and",
"add",
"it",
"to",
"the",
"graph",
":",
"param",
"subj",
":",
"graph",
"subject",
":",
"param",
"pred",
":",
"graph",
"predicate",
":",
"param",
"val",
":",
"JSON",
"representation"... | python | train |
kovidgoyal/html5-parser | src/html5_parser/__init__.py | https://github.com/kovidgoyal/html5-parser/blob/65ce451652cbab71ed86a9b53ac8c8906f2a2d67/src/html5_parser/__init__.py#L121-L207 | def parse(
html,
transport_encoding=None,
namespace_elements=False,
treebuilder='lxml',
fallback_encoding=None,
keep_doctype=True,
maybe_xhtml=False,
return_root=True,
line_number_attr=None,
sanitize_names=True,
stack_size=16 * 1024
):
'''
Parse the specified :attr:`h... | [
"def",
"parse",
"(",
"html",
",",
"transport_encoding",
"=",
"None",
",",
"namespace_elements",
"=",
"False",
",",
"treebuilder",
"=",
"'lxml'",
",",
"fallback_encoding",
"=",
"None",
",",
"keep_doctype",
"=",
"True",
",",
"maybe_xhtml",
"=",
"False",
",",
"... | Parse the specified :attr:`html` and return the parsed representation.
:param html: The HTML to be parsed. Can be either bytes or a unicode string.
:param transport_encoding: If specified, assume the passed in bytes are in this encoding.
Ignored if :attr:`html` is unicode.
:param namespace_elemen... | [
"Parse",
"the",
"specified",
":",
"attr",
":",
"html",
"and",
"return",
"the",
"parsed",
"representation",
"."
] | python | train |
JIC-CSB/jicimagelib | jicimagelib/io.py | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/io.py#L148-L160 | def run_command(self, input_file, output_dir=None):
"""Return the command for running bfconvert as a list.
:param input_file: path to microscopy image to be converted
:param ouput_dir: directory to write output tiff files to
:returns: list
"""
base_name = os.path... | [
"def",
"run_command",
"(",
"self",
",",
"input_file",
",",
"output_dir",
"=",
"None",
")",
":",
"base_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"input_file",
")",
"name",
",",
"suffix",
"=",
"base_name",
".",
"split",
"(",
"'.'",
",",
"1",
... | Return the command for running bfconvert as a list.
:param input_file: path to microscopy image to be converted
:param ouput_dir: directory to write output tiff files to
:returns: list | [
"Return",
"the",
"command",
"for",
"running",
"bfconvert",
"as",
"a",
"list",
".",
":",
"param",
"input_file",
":",
"path",
"to",
"microscopy",
"image",
"to",
"be",
"converted",
":",
"param",
"ouput_dir",
":",
"directory",
"to",
"write",
"output",
"tiff",
... | python | train |
saltstack/salt | salt/renderers/pyobjects.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/pyobjects.py#L339-L365 | def load_states():
'''
This loads our states into the salt __context__
'''
states = {}
# the loader expects to find pillar & grain data
__opts__['grains'] = salt.loader.grains(__opts__)
__opts__['pillar'] = __pillar__
lazy_utils = salt.loader.utils(__opts__)
lazy_funcs = salt.loader... | [
"def",
"load_states",
"(",
")",
":",
"states",
"=",
"{",
"}",
"# the loader expects to find pillar & grain data",
"__opts__",
"[",
"'grains'",
"]",
"=",
"salt",
".",
"loader",
".",
"grains",
"(",
"__opts__",
")",
"__opts__",
"[",
"'pillar'",
"]",
"=",
"__pilla... | This loads our states into the salt __context__ | [
"This",
"loads",
"our",
"states",
"into",
"the",
"salt",
"__context__"
] | python | train |
monarch-initiative/dipper | dipper/sources/Decipher.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/Decipher.py#L101-L226 | def _process_ddg2p_annotations(self, limit):
"""
The ddg2p annotations associate a gene symbol to an omim disease,
along with some HPO ids and pubs. The gene symbols come from gencode,
which in turn come from HGNC official gene symbols. Therefore,
we use the HGNC source class to... | [
"def",
"_process_ddg2p_annotations",
"(",
"self",
",",
"limit",
")",
":",
"line_counter",
"=",
"0",
"if",
"self",
".",
"graph",
"is",
"not",
"None",
":",
"graph",
"=",
"self",
".",
"graph",
"else",
":",
"graph",
"=",
"self",
".",
"graph",
"# in order for... | The ddg2p annotations associate a gene symbol to an omim disease,
along with some HPO ids and pubs. The gene symbols come from gencode,
which in turn come from HGNC official gene symbols. Therefore,
we use the HGNC source class to get the id/symbol mapping for
use in our annotations her... | [
"The",
"ddg2p",
"annotations",
"associate",
"a",
"gene",
"symbol",
"to",
"an",
"omim",
"disease",
"along",
"with",
"some",
"HPO",
"ids",
"and",
"pubs",
".",
"The",
"gene",
"symbols",
"come",
"from",
"gencode",
"which",
"in",
"turn",
"come",
"from",
"HGNC",... | python | train |
cosven/feeluown-core | fuocore/xiami/api.py | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/xiami/api.py#L54-L72 | def _sign_payload(self, payload):
"""使用 appkey 对 payload 进行签名,返回新的请求参数
"""
app_key = self._app_key
t = int(time.time() * 1000)
requestStr = {
'header': self._req_header,
'model': payload
}
data = json.dumps({'requestStr': json.dumps(request... | [
"def",
"_sign_payload",
"(",
"self",
",",
"payload",
")",
":",
"app_key",
"=",
"self",
".",
"_app_key",
"t",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1000",
")",
"requestStr",
"=",
"{",
"'header'",
":",
"self",
".",
"_req_header",
",",
... | 使用 appkey 对 payload 进行签名,返回新的请求参数 | [
"使用",
"appkey",
"对",
"payload",
"进行签名,返回新的请求参数"
] | python | train |
gem/oq-engine | openquake/baselib/datastore.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L285-L301 | def extend(self, key, array, **attrs):
"""
Extend the dataset associated to the given key; create it if needed
:param key: name of the dataset
:param array: array to store
:param attrs: a dictionary of attributes
"""
try:
dset = self.hdf5[key]
... | [
"def",
"extend",
"(",
"self",
",",
"key",
",",
"array",
",",
"*",
"*",
"attrs",
")",
":",
"try",
":",
"dset",
"=",
"self",
".",
"hdf5",
"[",
"key",
"]",
"except",
"KeyError",
":",
"dset",
"=",
"hdf5",
".",
"create",
"(",
"self",
".",
"hdf5",
",... | Extend the dataset associated to the given key; create it if needed
:param key: name of the dataset
:param array: array to store
:param attrs: a dictionary of attributes | [
"Extend",
"the",
"dataset",
"associated",
"to",
"the",
"given",
"key",
";",
"create",
"it",
"if",
"needed"
] | python | train |
softlayer/softlayer-python | SoftLayer/CLI/order/package_locations.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/package_locations.py#L15-L32 | def cli(env, package_keyname):
"""List Datacenters a package can be ordered in.
Use the location Key Name to place orders
"""
manager = ordering.OrderingManager(env.client)
table = formatting.Table(COLUMNS)
locations = manager.package_locations(package_keyname)
for region in locations:
... | [
"def",
"cli",
"(",
"env",
",",
"package_keyname",
")",
":",
"manager",
"=",
"ordering",
".",
"OrderingManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"locations",
"=",
"manager",
".",
"package_locati... | List Datacenters a package can be ordered in.
Use the location Key Name to place orders | [
"List",
"Datacenters",
"a",
"package",
"can",
"be",
"ordered",
"in",
"."
] | python | train |
m-weigand/sip_models | lib/sip_models/res/cc.py | https://github.com/m-weigand/sip_models/blob/917da5d956215d9df2bf65b24123ba020e3e17c0/lib/sip_models/res/cc.py#L306-L334 | def dim_dc(self, pars):
r"""
:math:`\frac{\partial \hat{\rho''}(\omega)}{\partial c} = \rho_0
\frac{-m sin(\frac{c \pi}{2}) ln(\omega \tau)(\omega \tau)^c - m
(\omega \tau)^c \frac{\pi}{2} cos(\frac{\pi}{2}}{1 + 2 (\omega \tau)^c
cos(\frac{c \pi}{2}) + (\omega \tau)^{2 c}} + \rho... | [
"def",
"dim_dc",
"(",
"self",
",",
"pars",
")",
":",
"self",
".",
"_set_parameters",
"(",
"pars",
")",
"# term1",
"nom1a",
"=",
"-",
"self",
".",
"m",
"*",
"np",
".",
"log",
"(",
"self",
".",
"w",
"*",
"self",
".",
"tau",
")",
"*",
"self",
".",... | r"""
:math:`\frac{\partial \hat{\rho''}(\omega)}{\partial c} = \rho_0
\frac{-m sin(\frac{c \pi}{2}) ln(\omega \tau)(\omega \tau)^c - m
(\omega \tau)^c \frac{\pi}{2} cos(\frac{\pi}{2}}{1 + 2 (\omega \tau)^c
cos(\frac{c \pi}{2}) + (\omega \tau)^{2 c}} + \rho_0 \frac{\left[-m
(\omeg... | [
"r",
":",
"math",
":",
"\\",
"frac",
"{",
"\\",
"partial",
"\\",
"hat",
"{",
"\\",
"rho",
"}",
"(",
"\\",
"omega",
")",
"}",
"{",
"\\",
"partial",
"c",
"}",
"=",
"\\",
"rho_0",
"\\",
"frac",
"{",
"-",
"m",
"sin",
"(",
"\\",
"frac",
"{",
"c"... | python | train |
HumanCellAtlas/dcp-cli | hca/upload/upload_area.py | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_area.py#L159-L168 | def checksum_status(self, filename):
"""
Retrieve checksum status and values for a file
:param str filename: The name of the file within the Upload Area
:return: a dict with checksum information
:rtype: dict
:raises UploadApiException: if information could not be obtaine... | [
"def",
"checksum_status",
"(",
"self",
",",
"filename",
")",
":",
"return",
"self",
".",
"upload_service",
".",
"api_client",
".",
"checksum_status",
"(",
"area_uuid",
"=",
"self",
".",
"uuid",
",",
"filename",
"=",
"filename",
")"
] | Retrieve checksum status and values for a file
:param str filename: The name of the file within the Upload Area
:return: a dict with checksum information
:rtype: dict
:raises UploadApiException: if information could not be obtained | [
"Retrieve",
"checksum",
"status",
"and",
"values",
"for",
"a",
"file"
] | python | train |
pkgw/pwkit | pwkit/msmt.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/msmt.py#L806-L818 | def _lval_add_towards_polarity(x, polarity):
"""Compute the appropriate Lval "kind" for the limit of value `x` towards
`polarity`. Either 'toinf' or 'pastzero' depending on the sign of `x` and
the infinity direction of polarity.
"""
if x < 0:
if polarity < 0:
return Lval('toinf'... | [
"def",
"_lval_add_towards_polarity",
"(",
"x",
",",
"polarity",
")",
":",
"if",
"x",
"<",
"0",
":",
"if",
"polarity",
"<",
"0",
":",
"return",
"Lval",
"(",
"'toinf'",
",",
"x",
")",
"return",
"Lval",
"(",
"'pastzero'",
",",
"x",
")",
"elif",
"polarit... | Compute the appropriate Lval "kind" for the limit of value `x` towards
`polarity`. Either 'toinf' or 'pastzero' depending on the sign of `x` and
the infinity direction of polarity. | [
"Compute",
"the",
"appropriate",
"Lval",
"kind",
"for",
"the",
"limit",
"of",
"value",
"x",
"towards",
"polarity",
".",
"Either",
"toinf",
"or",
"pastzero",
"depending",
"on",
"the",
"sign",
"of",
"x",
"and",
"the",
"infinity",
"direction",
"of",
"polarity",... | python | train |
materialsproject/pymatgen | pymatgen/analysis/graphs.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/graphs.py#L1796-L1814 | def set_node_attributes(self):
"""
Replicates molecule site properties (specie, coords, etc.) in the
MoleculeGraph.
:return:
"""
species = {}
coords = {}
properties = {}
for node in self.graph.nodes():
species[node] = self.molecule[no... | [
"def",
"set_node_attributes",
"(",
"self",
")",
":",
"species",
"=",
"{",
"}",
"coords",
"=",
"{",
"}",
"properties",
"=",
"{",
"}",
"for",
"node",
"in",
"self",
".",
"graph",
".",
"nodes",
"(",
")",
":",
"species",
"[",
"node",
"]",
"=",
"self",
... | Replicates molecule site properties (specie, coords, etc.) in the
MoleculeGraph.
:return: | [
"Replicates",
"molecule",
"site",
"properties",
"(",
"specie",
"coords",
"etc",
".",
")",
"in",
"the",
"MoleculeGraph",
"."
] | python | train |
secdev/scapy | scapy/contrib/http2.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/http2.py#L2312-L2326 | def resize(self, ns):
# type: (int) -> None
"""Resize the dynamic table. If the new size (ns) must be between 0 and
the cap size. If the new size is lower than the current size of the
dynamic table, entries are evicted.
@param int ns: the new size of the dynamic table
@ra... | [
"def",
"resize",
"(",
"self",
",",
"ns",
")",
":",
"# type: (int) -> None",
"assert",
"0",
"<=",
"ns",
"<=",
"self",
".",
"_dynamic_table_cap_size",
",",
"'EINVAL: ns: out-of-range value; expected value is in the range [0;{}['",
".",
"format",
"(",
"self",
".",
"_dyna... | Resize the dynamic table. If the new size (ns) must be between 0 and
the cap size. If the new size is lower than the current size of the
dynamic table, entries are evicted.
@param int ns: the new size of the dynamic table
@raise AssertionError | [
"Resize",
"the",
"dynamic",
"table",
".",
"If",
"the",
"new",
"size",
"(",
"ns",
")",
"must",
"be",
"between",
"0",
"and",
"the",
"cap",
"size",
".",
"If",
"the",
"new",
"size",
"is",
"lower",
"than",
"the",
"current",
"size",
"of",
"the",
"dynamic",... | python | train |
calston/rhumba | rhumba/http_client.py | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/http_client.py#L69-L75 | def abort_request(self, request):
"""Called to abort request on timeout"""
self.timedout = True
try:
request.cancel()
except error.AlreadyCancelled:
return | [
"def",
"abort_request",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"timedout",
"=",
"True",
"try",
":",
"request",
".",
"cancel",
"(",
")",
"except",
"error",
".",
"AlreadyCancelled",
":",
"return"
] | Called to abort request on timeout | [
"Called",
"to",
"abort",
"request",
"on",
"timeout"
] | python | train |
EnergieID/smappy | smappy/smappy.py | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L173-L213 | def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
... | [
"def",
"get_consumption",
"(",
"self",
",",
"service_location_id",
",",
"start",
",",
"end",
",",
"aggregation",
",",
"raw",
"=",
"False",
")",
":",
"url",
"=",
"urljoin",
"(",
"URLS",
"[",
"'servicelocation'",
"]",
",",
"service_location_id",
",",
"\"consum... | Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
... | [
"Request",
"Elektricity",
"consumption",
"and",
"Solar",
"production",
"for",
"a",
"given",
"service",
"location",
"."
] | python | train |
SecurityInnovation/PGPy | pgpy/pgp.py | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L609-L636 | def new(cls, pn, comment="", email=""):
"""
Create a new User ID or photo.
:param pn: User ID name, or photo. If this is a ``bytearray``, it will be loaded as a photo.
Otherwise, it will be used as the name field for a User ID.
:type pn: ``bytearray``, ``str``, ``unic... | [
"def",
"new",
"(",
"cls",
",",
"pn",
",",
"comment",
"=",
"\"\"",
",",
"email",
"=",
"\"\"",
")",
":",
"uid",
"=",
"PGPUID",
"(",
")",
"if",
"isinstance",
"(",
"pn",
",",
"bytearray",
")",
":",
"uid",
".",
"_uid",
"=",
"UserAttribute",
"(",
")",
... | Create a new User ID or photo.
:param pn: User ID name, or photo. If this is a ``bytearray``, it will be loaded as a photo.
Otherwise, it will be used as the name field for a User ID.
:type pn: ``bytearray``, ``str``, ``unicode``
:param comment: The comment field for a User I... | [
"Create",
"a",
"new",
"User",
"ID",
"or",
"photo",
"."
] | python | train |
thiagopbueno/pyrddl | pyrddl/rddl.py | https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/rddl.py#L130-L139 | def action_fluent_variables(self) -> FluentParamsList:
'''Returns the instantiated action fluents in canonical order.
Returns:
Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name
and a list of instantiated fluents represented as strings.
'''
fluents ... | [
"def",
"action_fluent_variables",
"(",
"self",
")",
"->",
"FluentParamsList",
":",
"fluents",
"=",
"self",
".",
"domain",
".",
"action_fluents",
"ordering",
"=",
"self",
".",
"domain",
".",
"action_fluent_ordering",
"return",
"self",
".",
"_fluent_params",
"(",
... | Returns the instantiated action fluents in canonical order.
Returns:
Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name
and a list of instantiated fluents represented as strings. | [
"Returns",
"the",
"instantiated",
"action",
"fluents",
"in",
"canonical",
"order",
"."
] | python | train |
Esri/ArcREST | src/arcrest/manageags/_data.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/_data.py#L293-L310 | def validateDataStore(self, dataStoreName, machineName):
"""
Checks the status of ArcGIS Data Store and provides a health check
response.
Inputs:
dataStoreName - name of the datastore
machineName - name of the machine
"""
url = self._url + "/items/e... | [
"def",
"validateDataStore",
"(",
"self",
",",
"dataStoreName",
",",
"machineName",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/items/enterpriseDatabases/%s/machines/%s/validate\"",
"%",
"(",
"dataStoreName",
",",
"machineName",
")",
"params",
"=",
"{",
"\"... | Checks the status of ArcGIS Data Store and provides a health check
response.
Inputs:
dataStoreName - name of the datastore
machineName - name of the machine | [
"Checks",
"the",
"status",
"of",
"ArcGIS",
"Data",
"Store",
"and",
"provides",
"a",
"health",
"check",
"response",
"."
] | python | train |
biocore/burrito-fillings | bfillings/seqprep.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/seqprep.py#L185-L229 | def _get_result_paths(self, data):
"""Captures SeqPrep output.
"""
result = {}
# Always output:
result['UnassembledReads1'] = ResultPath(Path=
self._unassembled_reads1_out_file_name(
... | [
"def",
"_get_result_paths",
"(",
"self",
",",
"data",
")",
":",
"result",
"=",
"{",
"}",
"# Always output:",
"result",
"[",
"'UnassembledReads1'",
"]",
"=",
"ResultPath",
"(",
"Path",
"=",
"self",
".",
"_unassembled_reads1_out_file_name",
"(",
")",
",",
"IsWri... | Captures SeqPrep output. | [
"Captures",
"SeqPrep",
"output",
"."
] | python | train |
cjdrake/pyeda | pyeda/boolalg/bfarray.py | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L899-L906 | def _coord2offset(self, coord):
"""Convert a normalized coordinate to an item offset."""
size = self.size
offset = 0
for dim, index in enumerate(coord):
size //= self._normshape[dim]
offset += size * index
return offset | [
"def",
"_coord2offset",
"(",
"self",
",",
"coord",
")",
":",
"size",
"=",
"self",
".",
"size",
"offset",
"=",
"0",
"for",
"dim",
",",
"index",
"in",
"enumerate",
"(",
"coord",
")",
":",
"size",
"//=",
"self",
".",
"_normshape",
"[",
"dim",
"]",
"of... | Convert a normalized coordinate to an item offset. | [
"Convert",
"a",
"normalized",
"coordinate",
"to",
"an",
"item",
"offset",
"."
] | python | train |
ellmetha/neojsonrpc | neojsonrpc/client.py | https://github.com/ellmetha/neojsonrpc/blob/e369b633a727482d5f9e310f0c3337ae5f7265db/neojsonrpc/client.py#L74-L83 | def get_account_state(self, address, **kwargs):
""" Returns the account state information associated with a specific address.
:param address: a 34-bit length address (eg. AJBENSwajTzQtwyJFkiJSv7MAaaMc7DsRz)
:type address: str
:return: dictionary containing the account state information
... | [
"def",
"get_account_state",
"(",
"self",
",",
"address",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_call",
"(",
"JSONRPCMethods",
".",
"GET_ACCOUNT_STATE",
".",
"value",
",",
"params",
"=",
"[",
"address",
",",
"]",
",",
"*",
"*",
"kwa... | Returns the account state information associated with a specific address.
:param address: a 34-bit length address (eg. AJBENSwajTzQtwyJFkiJSv7MAaaMc7DsRz)
:type address: str
:return: dictionary containing the account state information
:rtype: dict | [
"Returns",
"the",
"account",
"state",
"information",
"associated",
"with",
"a",
"specific",
"address",
"."
] | python | test |
bitesofcode/projexui | projexui/widgets/xcombobox.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L167-L176 | def checkedItems( self ):
"""
Returns the checked items for this combobox.
:return [<str>, ..]
"""
if not self.isCheckable():
return []
return [nativestring(self.itemText(i)) for i in self.checkedIndexes()] | [
"def",
"checkedItems",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isCheckable",
"(",
")",
":",
"return",
"[",
"]",
"return",
"[",
"nativestring",
"(",
"self",
".",
"itemText",
"(",
"i",
")",
")",
"for",
"i",
"in",
"self",
".",
"checkedIndexes"... | Returns the checked items for this combobox.
:return [<str>, ..] | [
"Returns",
"the",
"checked",
"items",
"for",
"this",
"combobox",
".",
":",
"return",
"[",
"<str",
">",
"..",
"]"
] | python | train |
skibblenybbles/django-commando | commando/management/base.py | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L286-L307 | def handle(self, *arguments, **options):
"""
Parses arguments and options, runs validate_<action> for each action
named by self.get_actions(), then runs handle_<action> for each action
named by self.get_actions().
"""
self.arguments = arguments
self.optio... | [
"def",
"handle",
"(",
"self",
",",
"*",
"arguments",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"arguments",
"=",
"arguments",
"self",
".",
"options",
"=",
"options",
"self",
".",
"arguments",
"=",
"self",
".",
"parse_arguments",
"(",
"arguments",
... | Parses arguments and options, runs validate_<action> for each action
named by self.get_actions(), then runs handle_<action> for each action
named by self.get_actions(). | [
"Parses",
"arguments",
"and",
"options",
"runs",
"validate_<action",
">",
"for",
"each",
"action",
"named",
"by",
"self",
".",
"get_actions",
"()",
"then",
"runs",
"handle_<action",
">",
"for",
"each",
"action",
"named",
"by",
"self",
".",
"get_actions",
"()",... | python | train |
soimort/you-get | src/you_get/util/log.py | https://github.com/soimort/you-get/blob/b746ac01c9f39de94cac2d56f665285b0523b974/src/you_get/util/log.py#L72-L74 | def print_log(text, *colors):
"""Print a log message to standard error."""
sys.stderr.write(sprint("{}: {}".format(script_name, text), *colors) + "\n") | [
"def",
"print_log",
"(",
"text",
",",
"*",
"colors",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"sprint",
"(",
"\"{}: {}\"",
".",
"format",
"(",
"script_name",
",",
"text",
")",
",",
"*",
"colors",
")",
"+",
"\"\\n\"",
")"
] | Print a log message to standard error. | [
"Print",
"a",
"log",
"message",
"to",
"standard",
"error",
"."
] | python | test |
kubernetes-client/python | kubernetes/client/apis/admissionregistration_v1beta1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/admissionregistration_v1beta1_api.py#L1185-L1209 | def patch_validating_webhook_configuration(self, name, body, **kwargs):
"""
partially update the specified ValidatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.pat... | [
"def",
"patch_validating_webhook_configuration",
"(",
"self",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self"... | partially update the specified ValidatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_validating_webhook_configuration(name, body, async_req=True)
>>> result = thread.... | [
"partially",
"update",
"the",
"specified",
"ValidatingWebhookConfiguration",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
... | python | train |
Netflix-Skunkworks/swag-client | swag_client/cli.py | https://github.com/Netflix-Skunkworks/swag-client/blob/e43816a85c4f48011cf497a4eae14f9df71fee0f/swag_client/cli.py#L146-L154 | def list_service(ctx, name):
"""Retrieve accounts pertaining to named service."""
swag = create_swag_from_ctx(ctx)
accounts = swag.get_service_enabled(name)
_table = [[result['name'], result.get('id')] for result in accounts]
click.echo(
tabulate(_table, headers=["Account Name", "Account Nu... | [
"def",
"list_service",
"(",
"ctx",
",",
"name",
")",
":",
"swag",
"=",
"create_swag_from_ctx",
"(",
"ctx",
")",
"accounts",
"=",
"swag",
".",
"get_service_enabled",
"(",
"name",
")",
"_table",
"=",
"[",
"[",
"result",
"[",
"'name'",
"]",
",",
"result",
... | Retrieve accounts pertaining to named service. | [
"Retrieve",
"accounts",
"pertaining",
"to",
"named",
"service",
"."
] | python | train |
mlperf/training | rnn_translator/pytorch/seq2seq/data/tokenizer.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/tokenizer.py#L44-L56 | def pad_vocabulary(self, vocab, pad):
"""
Pads vocabulary to a multiple of 'pad' tokens.
:param vocab: list with vocabulary
:param pad: integer
"""
vocab_size = len(vocab)
padded_vocab_size = (vocab_size + pad - 1) // pad * pad
for i in range(0, padded_vo... | [
"def",
"pad_vocabulary",
"(",
"self",
",",
"vocab",
",",
"pad",
")",
":",
"vocab_size",
"=",
"len",
"(",
"vocab",
")",
"padded_vocab_size",
"=",
"(",
"vocab_size",
"+",
"pad",
"-",
"1",
")",
"//",
"pad",
"*",
"pad",
"for",
"i",
"in",
"range",
"(",
... | Pads vocabulary to a multiple of 'pad' tokens.
:param vocab: list with vocabulary
:param pad: integer | [
"Pads",
"vocabulary",
"to",
"a",
"multiple",
"of",
"pad",
"tokens",
"."
] | python | train |
vaexio/vaex | packages/vaex-core/vaex/functions.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/functions.py#L770-L805 | def str_get(x, i):
"""Extract a character from each sample at the specified position from a string column.
Note that if the specified position is out of bound of the string sample, this method returns '', while pandas retunrs nan.
:param int i: The index location, at which to extract the character.
:re... | [
"def",
"str_get",
"(",
"x",
",",
"i",
")",
":",
"x",
"=",
"_to_string_sequence",
"(",
"x",
")",
"if",
"i",
"==",
"-",
"1",
":",
"sl",
"=",
"x",
".",
"slice_string_end",
"(",
"-",
"1",
")",
"else",
":",
"sl",
"=",
"x",
".",
"slice_string",
"(",
... | Extract a character from each sample at the specified position from a string column.
Note that if the specified position is out of bound of the string sample, this method returns '', while pandas retunrs nan.
:param int i: The index location, at which to extract the character.
:returns: an expression conta... | [
"Extract",
"a",
"character",
"from",
"each",
"sample",
"at",
"the",
"specified",
"position",
"from",
"a",
"string",
"column",
".",
"Note",
"that",
"if",
"the",
"specified",
"position",
"is",
"out",
"of",
"bound",
"of",
"the",
"string",
"sample",
"this",
"m... | python | test |
abusque/qng | qng/generator.py | https://github.com/abusque/qng/blob/93d2efd637b2a6bba7d3872fb9ff2bb3fc5c979d/qng/generator.py#L111-L119 | def _get_surnames(self):
"""Get the list of surnames.
:return: A list of surname entries.
"""
names = self._read_name_file('surnames.json')
names = self._compute_weights(names)
return names | [
"def",
"_get_surnames",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"_read_name_file",
"(",
"'surnames.json'",
")",
"names",
"=",
"self",
".",
"_compute_weights",
"(",
"names",
")",
"return",
"names"
] | Get the list of surnames.
:return: A list of surname entries. | [
"Get",
"the",
"list",
"of",
"surnames",
"."
] | python | train |
tanghaibao/jcvi | jcvi/formats/psl.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/psl.py#L105-L113 | def _isProtein(self):
"""
check if blockSizes and scores are in the protein space or not
"""
last = self.blockCount - 1
return ((self.tEnd == self.tStarts[last] + 3 * self.blockSizes[last]) \
and self.strand == "+") or \
((self.tStart == self.tSize... | [
"def",
"_isProtein",
"(",
"self",
")",
":",
"last",
"=",
"self",
".",
"blockCount",
"-",
"1",
"return",
"(",
"(",
"self",
".",
"tEnd",
"==",
"self",
".",
"tStarts",
"[",
"last",
"]",
"+",
"3",
"*",
"self",
".",
"blockSizes",
"[",
"last",
"]",
")"... | check if blockSizes and scores are in the protein space or not | [
"check",
"if",
"blockSizes",
"and",
"scores",
"are",
"in",
"the",
"protein",
"space",
"or",
"not"
] | python | train |
ulule/django-badgify | badgify/recipe.py | https://github.com/ulule/django-badgify/blob/1bf233ffeb6293ee659454de7b3794682128b6ca/badgify/recipe.py#L174-L180 | def get_current_user_ids(self, db_read=None):
"""
Returns current user ids and the count.
"""
db_read = db_read or self.db_read
return self.user_ids.using(db_read) | [
"def",
"get_current_user_ids",
"(",
"self",
",",
"db_read",
"=",
"None",
")",
":",
"db_read",
"=",
"db_read",
"or",
"self",
".",
"db_read",
"return",
"self",
".",
"user_ids",
".",
"using",
"(",
"db_read",
")"
] | Returns current user ids and the count. | [
"Returns",
"current",
"user",
"ids",
"and",
"the",
"count",
"."
] | python | train |
has2k1/plotnine | plotnine/facets/facet.py | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/facet.py#L507-L553 | def draw_strip_text(self, text_lines, location, pid):
"""
Create a background patch and put a label on it
"""
ax = self.axs[pid]
themeable = self.figure._themeable
dim = self.strip_dimensions(text_lines, location, pid)
if location == 'right':
rotation... | [
"def",
"draw_strip_text",
"(",
"self",
",",
"text_lines",
",",
"location",
",",
"pid",
")",
":",
"ax",
"=",
"self",
".",
"axs",
"[",
"pid",
"]",
"themeable",
"=",
"self",
".",
"figure",
".",
"_themeable",
"dim",
"=",
"self",
".",
"strip_dimensions",
"(... | Create a background patch and put a label on it | [
"Create",
"a",
"background",
"patch",
"and",
"put",
"a",
"label",
"on",
"it"
] | python | train |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/mmax2.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/mmax2.py#L225-L227 | def get_token_nodes_from_sentence(self, sentence_root_node):
"""returns a list of token node IDs belonging to the given sentence"""
return spanstring2tokens(self, self.node[sentence_root_node][self.ns+':span']) | [
"def",
"get_token_nodes_from_sentence",
"(",
"self",
",",
"sentence_root_node",
")",
":",
"return",
"spanstring2tokens",
"(",
"self",
",",
"self",
".",
"node",
"[",
"sentence_root_node",
"]",
"[",
"self",
".",
"ns",
"+",
"':span'",
"]",
")"
] | returns a list of token node IDs belonging to the given sentence | [
"returns",
"a",
"list",
"of",
"token",
"node",
"IDs",
"belonging",
"to",
"the",
"given",
"sentence"
] | python | train |
CI-WATER/mapkit | mapkit/__init__.py | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/__init__.py#L22-L48 | def lookupSpatialReferenceID(wellKnownText):
"""
This function can be used to look up the EPSG spatial reference system using the web service available at:
http://prj2epsg.org
Args:
wellKnownText (str): The Well Known Text definition of the spatial reference system.
Returns:
int: S... | [
"def",
"lookupSpatialReferenceID",
"(",
"wellKnownText",
")",
":",
"payload",
"=",
"{",
"'mode'",
":",
"'wkt'",
",",
"'terms'",
":",
"wellKnownText",
"}",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"'http://prj2epsg.org/search.json'",
",",
"params",
"=... | This function can be used to look up the EPSG spatial reference system using the web service available at:
http://prj2epsg.org
Args:
wellKnownText (str): The Well Known Text definition of the spatial reference system.
Returns:
int: Spatial Reference ID | [
"This",
"function",
"can",
"be",
"used",
"to",
"look",
"up",
"the",
"EPSG",
"spatial",
"reference",
"system",
"using",
"the",
"web",
"service",
"available",
"at",
":",
"http",
":",
"//",
"prj2epsg",
".",
"org"
] | python | train |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L54-L77 | def _api_call(self, method, target, args=None):
"""Create a Request object and execute the call to the API Server.
Parameters
method (str)
HTTP request (e.g. 'POST').
target (str)
The target URL with leading slash (e.g. '/v1/products').
... | [
"def",
"_api_call",
"(",
"self",
",",
"method",
",",
"target",
",",
"args",
"=",
"None",
")",
":",
"self",
".",
"refresh_oauth_credential",
"(",
")",
"request",
"=",
"Request",
"(",
"auth_session",
"=",
"self",
".",
"session",
",",
"api_host",
"=",
"self... | Create a Request object and execute the call to the API Server.
Parameters
method (str)
HTTP request (e.g. 'POST').
target (str)
The target URL with leading slash (e.g. '/v1/products').
args (dict)
Optional dictionary of argumen... | [
"Create",
"a",
"Request",
"object",
"and",
"execute",
"the",
"call",
"to",
"the",
"API",
"Server",
".",
"Parameters",
"method",
"(",
"str",
")",
"HTTP",
"request",
"(",
"e",
".",
"g",
".",
"POST",
")",
".",
"target",
"(",
"str",
")",
"The",
"target",... | python | train |
cjdrake/pyeda | pyeda/boolalg/bdd.py | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L116-L131 | def _expr2bddnode(expr):
"""Convert an expression into a BDD node."""
if expr.is_zero():
return BDDNODEZERO
elif expr.is_one():
return BDDNODEONE
else:
top = expr.top
# Register this variable
_ = bddvar(top.names, top.indices)
root = top.uniqid
l... | [
"def",
"_expr2bddnode",
"(",
"expr",
")",
":",
"if",
"expr",
".",
"is_zero",
"(",
")",
":",
"return",
"BDDNODEZERO",
"elif",
"expr",
".",
"is_one",
"(",
")",
":",
"return",
"BDDNODEONE",
"else",
":",
"top",
"=",
"expr",
".",
"top",
"# Register this varia... | Convert an expression into a BDD node. | [
"Convert",
"an",
"expression",
"into",
"a",
"BDD",
"node",
"."
] | python | train |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L1260-L1272 | def abort_benchmark(self, name=None, params={}, body='', callback=None, **kwargs):
"""
Aborts a running benchmark.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_
:arg name: A benchmark name
"""
url = self.mk_url(*['_bench'... | [
"def",
"abort_benchmark",
"(",
"self",
",",
"name",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"body",
"=",
"''",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"mk_url",
"(",
"*",
"[",
"'_bench'",
... | Aborts a running benchmark.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_
:arg name: A benchmark name | [
"Aborts",
"a",
"running",
"benchmark",
".",
"<http",
":",
"//",
"www",
".",
"elasticsearch",
".",
"org",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"master",
"/",
"search",
"-",
"benchmark",
".",
"html",
">",
"_",
":",
"arg",... | python | train |
datadotworld/data.world-py | datadotworld/client/api.py | https://github.com/datadotworld/data.world-py/blob/ffaeb115f358731ab0b805b0c43b7ff2e3cf0a77/datadotworld/client/api.py#L162-L206 | def update_dataset(self, dataset_key, **kwargs):
"""Update an existing dataset
:param description: Dataset description
:type description: str, optional
:param summary: Dataset summary markdown
:type summary: str, optional
:param tags: Dataset tags
:type tags: lis... | [
"def",
"update_dataset",
"(",
"self",
",",
"dataset_key",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"self",
".",
"__build_dataset_obj",
"(",
"lambda",
":",
"_swagger",
".",
"DatasetPatchRequest",
"(",
")",
",",
"lambda",
"name",
",",
"url",
",",
... | Update an existing dataset
:param description: Dataset description
:type description: str, optional
:param summary: Dataset summary markdown
:type summary: str, optional
:param tags: Dataset tags
:type tags: list, optional
:param license: Dataset license
... | [
"Update",
"an",
"existing",
"dataset"
] | python | train |
echonest/pyechonest | pyechonest/song.py | https://github.com/echonest/pyechonest/blob/d8c7af6c1da699b50b2f4b1bd3c0febe72e7f1ee/pyechonest/song.py#L120-L143 | def get_song_hotttnesss(self, cache=True):
"""Get our numerical description of how hottt a song currently is
Args:
Kwargs:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
Returns:
... | [
"def",
"get_song_hotttnesss",
"(",
"self",
",",
"cache",
"=",
"True",
")",
":",
"if",
"not",
"(",
"cache",
"and",
"(",
"'song_hotttnesss'",
"in",
"self",
".",
"cache",
")",
")",
":",
"response",
"=",
"self",
".",
"get_attribute",
"(",
"'profile'",
",",
... | Get our numerical description of how hottt a song currently is
Args:
Kwargs:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
Returns:
A float representing hotttnesss.
... | [
"Get",
"our",
"numerical",
"description",
"of",
"how",
"hottt",
"a",
"song",
"currently",
"is",
"Args",
":",
"Kwargs",
":",
"cache",
"(",
"bool",
")",
":",
"A",
"boolean",
"indicating",
"whether",
"or",
"not",
"the",
"cached",
"value",
"should",
"be",
"u... | python | train |
miso-belica/sumy | sumy/evaluation/content_based.py | https://github.com/miso-belica/sumy/blob/099ab4938e2c1b6a011297375586bac2953641b9/sumy/evaluation/content_based.py#L36-L57 | def unit_overlap(evaluated_model, reference_model):
"""
Computes unit overlap of two text documents. Documents
has to be represented as TF models of non-empty document.
:returns float:
0 <= overlap <= 1, where 0 means no match and 1 means
exactly the same.
"""
if not (isinstance... | [
"def",
"unit_overlap",
"(",
"evaluated_model",
",",
"reference_model",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"evaluated_model",
",",
"TfModel",
")",
"and",
"isinstance",
"(",
"reference_model",
",",
"TfModel",
")",
")",
":",
"raise",
"ValueError",
"("... | Computes unit overlap of two text documents. Documents
has to be represented as TF models of non-empty document.
:returns float:
0 <= overlap <= 1, where 0 means no match and 1 means
exactly the same. | [
"Computes",
"unit",
"overlap",
"of",
"two",
"text",
"documents",
".",
"Documents",
"has",
"to",
"be",
"represented",
"as",
"TF",
"models",
"of",
"non",
"-",
"empty",
"document",
"."
] | python | train |
willkg/socorro-siggen | siggen/cmd_fetch_data.py | https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/cmd_fetch_data.py#L20-L39 | def _fill_text(self, text, width, indent):
"""Wraps text like HelpFormatter, but doesn't squash lines
This makes it easier to do lists and paragraphs.
"""
parts = text.split('\n\n')
for i, part in enumerate(parts):
# Check to see if it's a bulleted list--if so, then... | [
"def",
"_fill_text",
"(",
"self",
",",
"text",
",",
"width",
",",
"indent",
")",
":",
"parts",
"=",
"text",
".",
"split",
"(",
"'\\n\\n'",
")",
"for",
"i",
",",
"part",
"in",
"enumerate",
"(",
"parts",
")",
":",
"# Check to see if it's a bulleted list--if ... | Wraps text like HelpFormatter, but doesn't squash lines
This makes it easier to do lists and paragraphs. | [
"Wraps",
"text",
"like",
"HelpFormatter",
"but",
"doesn",
"t",
"squash",
"lines"
] | python | train |
sloria/environs | environs.py | https://github.com/sloria/environs/blob/cf0b5e865b0ce96ce77d459124a1dba84c9deda7/environs.py#L83-L94 | def _dict2schema(dct):
"""Generate a `marshmallow.Schema` class given a dictionary of
`Fields <marshmallow.fields.Field>`.
"""
attrs = dct.copy()
if MARSHMALLOW_VERSION_INFO[0] < 3:
class Meta(object):
strict = True
attrs["Meta"] = Meta
return type(str(""), (ma.Sche... | [
"def",
"_dict2schema",
"(",
"dct",
")",
":",
"attrs",
"=",
"dct",
".",
"copy",
"(",
")",
"if",
"MARSHMALLOW_VERSION_INFO",
"[",
"0",
"]",
"<",
"3",
":",
"class",
"Meta",
"(",
"object",
")",
":",
"strict",
"=",
"True",
"attrs",
"[",
"\"Meta\"",
"]",
... | Generate a `marshmallow.Schema` class given a dictionary of
`Fields <marshmallow.fields.Field>`. | [
"Generate",
"a",
"marshmallow",
".",
"Schema",
"class",
"given",
"a",
"dictionary",
"of",
"Fields",
"<marshmallow",
".",
"fields",
".",
"Field",
">",
"."
] | python | train |
Rikanishu/static-bundle | static_bundle/bundles.py | https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/bundles.py#L94-L105 | def add_prepare_handler(self, prepare_handlers):
"""
Add prepare handler to bundle
:type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler
"""
if not isinstance(prepare_handlers, static_bundle.BUNDLE_ITERABLE_TYPES):
prepare_handlers = [prepare_handlers... | [
"def",
"add_prepare_handler",
"(",
"self",
",",
"prepare_handlers",
")",
":",
"if",
"not",
"isinstance",
"(",
"prepare_handlers",
",",
"static_bundle",
".",
"BUNDLE_ITERABLE_TYPES",
")",
":",
"prepare_handlers",
"=",
"[",
"prepare_handlers",
"]",
"if",
"self",
"."... | Add prepare handler to bundle
:type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler | [
"Add",
"prepare",
"handler",
"to",
"bundle"
] | python | valid |
SmileyChris/easy-thumbnails | easy_thumbnails/files.py | https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L749-L769 | def save(self, name, content, *args, **kwargs):
"""
Save the image.
The image will be resized down using a ``ThumbnailField`` if
``resize_source`` (a dictionary of thumbnail options) is provided by
the field.
"""
options = getattr(self.field, 'resize_source', Non... | [
"def",
"save",
"(",
"self",
",",
"name",
",",
"content",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"getattr",
"(",
"self",
".",
"field",
",",
"'resize_source'",
",",
"None",
")",
"if",
"options",
":",
"if",
"'quality'",
"... | Save the image.
The image will be resized down using a ``ThumbnailField`` if
``resize_source`` (a dictionary of thumbnail options) is provided by
the field. | [
"Save",
"the",
"image",
"."
] | python | train |
tornadoweb/tornado | tornado/iostream.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L159-L179 | def append(self, data: Union[bytes, bytearray, memoryview]) -> None:
"""
Append the given piece of data (should be a buffer-compatible object).
"""
size = len(data)
if size > self._large_buf_threshold:
if not isinstance(data, memoryview):
data = memory... | [
"def",
"append",
"(",
"self",
",",
"data",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
",",
"memoryview",
"]",
")",
"->",
"None",
":",
"size",
"=",
"len",
"(",
"data",
")",
"if",
"size",
">",
"self",
".",
"_large_buf_threshold",
":",
"if",
"not",
... | Append the given piece of data (should be a buffer-compatible object). | [
"Append",
"the",
"given",
"piece",
"of",
"data",
"(",
"should",
"be",
"a",
"buffer",
"-",
"compatible",
"object",
")",
"."
] | python | train |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L362-L405 | def _get_var_decl_init_value_single(self, _ctype, child):
"""
Handling of a single child for initialization value.
Accepted types are expressions and declarations
"""
init_value = None
# FIXME: always return (child.kind, child.value)
log.debug(
'_get_v... | [
"def",
"_get_var_decl_init_value_single",
"(",
"self",
",",
"_ctype",
",",
"child",
")",
":",
"init_value",
"=",
"None",
"# FIXME: always return (child.kind, child.value)",
"log",
".",
"debug",
"(",
"'_get_var_decl_init_value_single: _ctype: %s Child.kind: %s'",
",",
"_ctype"... | Handling of a single child for initialization value.
Accepted types are expressions and declarations | [
"Handling",
"of",
"a",
"single",
"child",
"for",
"initialization",
"value",
".",
"Accepted",
"types",
"are",
"expressions",
"and",
"declarations"
] | python | train |
etcher-be/emiz | emiz/weather/custom_metar/custom_metar.py | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/weather/custom_metar/custom_metar.py#L118-L143 | def _handlePressure(self, d):
"""
Parse an altimeter-pressure group.
The following attributes are set:
press [int]
"""
press = d['press']
if press != '////':
press = float(press.replace('O', '0'))
if d['unit']:
if d[... | [
"def",
"_handlePressure",
"(",
"self",
",",
"d",
")",
":",
"press",
"=",
"d",
"[",
"'press'",
"]",
"if",
"press",
"!=",
"'////'",
":",
"press",
"=",
"float",
"(",
"press",
".",
"replace",
"(",
"'O'",
",",
"'0'",
")",
")",
"if",
"d",
"[",
"'unit'"... | Parse an altimeter-pressure group.
The following attributes are set:
press [int] | [
"Parse",
"an",
"altimeter",
"-",
"pressure",
"group",
"."
] | python | train |
MacHu-GWU/angora-project | angora/filesystem/filesystem.py | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/filesystem/filesystem.py#L942-L958 | def sort_by(self, attr_name, reverse=False):
"""Sort files by one of it's attributes.
**中文文档**
对容器内的WinFile根据其某一个属性升序或者降序排序。
"""
try:
d = dict()
for abspath, winfile in self.files.items():
d[abspath] = getattr(winfile, att... | [
"def",
"sort_by",
"(",
"self",
",",
"attr_name",
",",
"reverse",
"=",
"False",
")",
":",
"try",
":",
"d",
"=",
"dict",
"(",
")",
"for",
"abspath",
",",
"winfile",
"in",
"self",
".",
"files",
".",
"items",
"(",
")",
":",
"d",
"[",
"abspath",
"]",
... | Sort files by one of it's attributes.
**中文文档**
对容器内的WinFile根据其某一个属性升序或者降序排序。 | [
"Sort",
"files",
"by",
"one",
"of",
"it",
"s",
"attributes",
".",
"**",
"中文文档",
"**",
"对容器内的WinFile根据其某一个属性升序或者降序排序。"
] | python | train |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/request_parser.py | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/request_parser.py#L114-L124 | def _safe_read_meta_file(fn, error_protocol):
"""
Try to read MetadataFile. If the exception is raised, log the errors to
the `error_protocol` and return None.
"""
try:
return MetadataFile(fn)
except Exception, e:
error_protocol.append(
"Can't read MetadataFile '%s':\... | [
"def",
"_safe_read_meta_file",
"(",
"fn",
",",
"error_protocol",
")",
":",
"try",
":",
"return",
"MetadataFile",
"(",
"fn",
")",
"except",
"Exception",
",",
"e",
":",
"error_protocol",
".",
"append",
"(",
"\"Can't read MetadataFile '%s':\\n\\t%s\\n\"",
"%",
"(",
... | Try to read MetadataFile. If the exception is raised, log the errors to
the `error_protocol` and return None. | [
"Try",
"to",
"read",
"MetadataFile",
".",
"If",
"the",
"exception",
"is",
"raised",
"log",
"the",
"errors",
"to",
"the",
"error_protocol",
"and",
"return",
"None",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.