repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
fvdsn/py-xml-escpos | xmlescpos/escpos.py | https://github.com/fvdsn/py-xml-escpos/blob/7f77e039c960d5773fb919aed02ba392dccbc360/xmlescpos/escpos.py#L424-L430 | def image(self,path_img):
""" Open image file """
im_open = Image.open(path_img)
im = im_open.convert("RGB")
# Convert the RGB image in printable image
pix_line, img_size = self._convert_image(im)
self._print_image(pix_line, img_size) | [
"def",
"image",
"(",
"self",
",",
"path_img",
")",
":",
"im_open",
"=",
"Image",
".",
"open",
"(",
"path_img",
")",
"im",
"=",
"im_open",
".",
"convert",
"(",
"\"RGB\"",
")",
"# Convert the RGB image in printable image",
"pix_line",
",",
"img_size",
"=",
"se... | Open image file | [
"Open",
"image",
"file"
] | python | train | 39.428571 |
vertexproject/synapse | synapse/common.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/common.py#L571-L587 | def result(retn):
'''
Return a value or raise an exception from a retn tuple.
'''
ok, valu = retn
if ok:
return valu
name, info = valu
ctor = getattr(s_exc, name, None)
if ctor is not None:
raise ctor(**info)
info['errx'] = name
raise s_exc.SynErr(**info) | [
"def",
"result",
"(",
"retn",
")",
":",
"ok",
",",
"valu",
"=",
"retn",
"if",
"ok",
":",
"return",
"valu",
"name",
",",
"info",
"=",
"valu",
"ctor",
"=",
"getattr",
"(",
"s_exc",
",",
"name",
",",
"None",
")",
"if",
"ctor",
"is",
"not",
"None",
... | Return a value or raise an exception from a retn tuple. | [
"Return",
"a",
"value",
"or",
"raise",
"an",
"exception",
"from",
"a",
"retn",
"tuple",
"."
] | python | train | 17.588235 |
ampl/amplpy | amplpy/dataframe.py | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L235-L246 | def getRowByIndex(self, index):
"""
Get row by numeric index.
Args:
index: Zero-based index of the row to get.
Returns:
The corresponding row.
"""
assert isinstance(index, int)
return Row(self._impl.getRowByIndex(index)) | [
"def",
"getRowByIndex",
"(",
"self",
",",
"index",
")",
":",
"assert",
"isinstance",
"(",
"index",
",",
"int",
")",
"return",
"Row",
"(",
"self",
".",
"_impl",
".",
"getRowByIndex",
"(",
"index",
")",
")"
] | Get row by numeric index.
Args:
index: Zero-based index of the row to get.
Returns:
The corresponding row. | [
"Get",
"row",
"by",
"numeric",
"index",
"."
] | python | train | 24.25 |
lemieuxl/pyGenClean | pyGenClean/NoCallHetero/clean_noCall_hetero_snps.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/NoCallHetero/clean_noCall_hetero_snps.py#L32-L56 | def main(argString=None):
"""The main function of the module.
:param argString: the options.
:type argString: list
These are the steps:
1. Prints the options.
2. Reads the ``tfam`` and ``tped`` files and find all heterozygous and all
failed markers (:py:func:`processTPEDandTFAM`).
... | [
"def",
"main",
"(",
"argString",
"=",
"None",
")",
":",
"# Getting and checking the options",
"args",
"=",
"parseArgs",
"(",
"argString",
")",
"checkArgs",
"(",
"args",
")",
"logger",
".",
"info",
"(",
"\"Options used:\"",
")",
"for",
"key",
",",
"value",
"i... | The main function of the module.
:param argString: the options.
:type argString: list
These are the steps:
1. Prints the options.
2. Reads the ``tfam`` and ``tped`` files and find all heterozygous and all
failed markers (:py:func:`processTPEDandTFAM`). | [
"The",
"main",
"function",
"of",
"the",
"module",
"."
] | python | train | 28.4 |
OCR-D/core | ocrd/ocrd/cli/workspace.py | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L101-L113 | def workspace_create(ctx, clobber_mets, directory):
"""
Create a workspace with an empty METS file in DIRECTORY.
Use '.' for $PWD"
"""
workspace = ctx.resolver.workspace_from_nothing(
directory=os.path.abspath(directory),
mets_basename=ctx.mets_basename,
clobber_mets=clobber... | [
"def",
"workspace_create",
"(",
"ctx",
",",
"clobber_mets",
",",
"directory",
")",
":",
"workspace",
"=",
"ctx",
".",
"resolver",
".",
"workspace_from_nothing",
"(",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
",",
"mets_basen... | Create a workspace with an empty METS file in DIRECTORY.
Use '.' for $PWD" | [
"Create",
"a",
"workspace",
"with",
"an",
"empty",
"METS",
"file",
"in",
"DIRECTORY",
"."
] | python | train | 28.923077 |
mozilla/DeepSpeech | native_client/ctcdecode/__init__.py | https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/native_client/ctcdecode/__init__.py#L25-L59 | def ctc_beam_search_decoder(probs_seq,
alphabet,
beam_size,
cutoff_prob=1.0,
cutoff_top_n=40,
scorer=None):
"""Wrapper for the CTC Beam Search Decoder.
:param probs_seq: 2... | [
"def",
"ctc_beam_search_decoder",
"(",
"probs_seq",
",",
"alphabet",
",",
"beam_size",
",",
"cutoff_prob",
"=",
"1.0",
",",
"cutoff_top_n",
"=",
"40",
",",
"scorer",
"=",
"None",
")",
":",
"beam_results",
"=",
"swigwrapper",
".",
"ctc_beam_search_decoder",
"(",
... | Wrapper for the CTC Beam Search Decoder.
:param probs_seq: 2-D list of probability distributions over each time
step, with each element being a list of normalized
probabilities over alphabet and blank.
:type probs_seq: 2-D list
:param alphabet: alphabet list.
... | [
"Wrapper",
"for",
"the",
"CTC",
"Beam",
"Search",
"Decoder",
"."
] | python | train | 44.914286 |
Trebek/pydealer | pydealer/stack.py | https://github.com/Trebek/pydealer/blob/2ac583dd8c55715658c740b614387775f4dda333/pydealer/stack.py#L631-L643 | def shuffle(self, times=1):
"""
Shuffles the Stack.
.. note::
Shuffling large numbers of cards (100,000+) may take a while.
:arg int times:
The number of times to shuffle.
"""
for _ in xrange(times):
random.shuffle(self.cards) | [
"def",
"shuffle",
"(",
"self",
",",
"times",
"=",
"1",
")",
":",
"for",
"_",
"in",
"xrange",
"(",
"times",
")",
":",
"random",
".",
"shuffle",
"(",
"self",
".",
"cards",
")"
] | Shuffles the Stack.
.. note::
Shuffling large numbers of cards (100,000+) may take a while.
:arg int times:
The number of times to shuffle. | [
"Shuffles",
"the",
"Stack",
"."
] | python | train | 23.153846 |
saltstack/salt | salt/modules/vsphere.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1534-L1636 | def get_service_policy(host, username, password, service_name, protocol=None, port=None, host_names=None):
'''
Get the service name's policy for a given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
passwor... | [
"def",
"get_service_policy",
"(",
"host",
",",
"username",
",",
"password",
",",
"service_name",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",... | Get the service name's policy for a given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
service_name
The name of the service for which to retrie... | [
"Get",
"the",
"service",
"name",
"s",
"policy",
"for",
"a",
"given",
"host",
"or",
"list",
"of",
"hosts",
"."
] | python | train | 40.300971 |
pybel/pybel-tools | src/pybel_tools/mutation/collapse.py | https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/collapse.py#L50-L54 | def _collapse_variants_by_function(graph: BELGraph, func: str) -> None:
"""Collapse all of the given functions' variants' edges to their parents, in-place."""
for parent_node, variant_node, data in graph.edges(data=True):
if data[RELATION] == HAS_VARIANT and parent_node.function == func:
col... | [
"def",
"_collapse_variants_by_function",
"(",
"graph",
":",
"BELGraph",
",",
"func",
":",
"str",
")",
"->",
"None",
":",
"for",
"parent_node",
",",
"variant_node",
",",
"data",
"in",
"graph",
".",
"edges",
"(",
"data",
"=",
"True",
")",
":",
"if",
"data"... | Collapse all of the given functions' variants' edges to their parents, in-place. | [
"Collapse",
"all",
"of",
"the",
"given",
"functions",
"variants",
"edges",
"to",
"their",
"parents",
"in",
"-",
"place",
"."
] | python | valid | 75.6 |
globocom/GloboNetworkAPI-client-python | networkapiclient/OptionVIP.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/OptionVIP.py#L190-L224 | def associate(self, id_option_vip, id_environment_vip):
"""Create a relationship of OptionVip with EnvironmentVip.
:param id_option_vip: Identifier of the Option VIP. Integer value and greater than zero.
:param id_environment_vip: Identifier of the Environment VIP. Integer value and greater tha... | [
"def",
"associate",
"(",
"self",
",",
"id_option_vip",
",",
"id_environment_vip",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_option_vip",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'The identifier of Option VIP is invalid or was not informed.'",
")",
"i... | Create a relationship of OptionVip with EnvironmentVip.
:param id_option_vip: Identifier of the Option VIP. Integer value and greater than zero.
:param id_environment_vip: Identifier of the Environment VIP. Integer value and greater than zero.
:return: Following dictionary
::
... | [
"Create",
"a",
"relationship",
"of",
"OptionVip",
"with",
"EnvironmentVip",
"."
] | python | train | 45.085714 |
bitesofcode/projexui | projexui/widgets/xsnapshotwidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsnapshotwidget.py#L82-L92 | def keyPressEvent(self, event):
"""
Listens for the escape key to cancel out from this snapshot.
:param event | <QKeyPressEvent>
"""
# reject on a cancel
if event.key() == Qt.Key_Escape:
self.reject()
super(XSnapshotWid... | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"# reject on a cancel\r",
"if",
"event",
".",
"key",
"(",
")",
"==",
"Qt",
".",
"Key_Escape",
":",
"self",
".",
"reject",
"(",
")",
"super",
"(",
"XSnapshotWidget",
",",
"self",
")",
".",
"ke... | Listens for the escape key to cancel out from this snapshot.
:param event | <QKeyPressEvent> | [
"Listens",
"for",
"the",
"escape",
"key",
"to",
"cancel",
"out",
"from",
"this",
"snapshot",
".",
":",
"param",
"event",
"|",
"<QKeyPressEvent",
">"
] | python | train | 31 |
tgbugs/pyontutils | ilxutils/ilxutils/simple_rdflib.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L165-L191 | def add_triple(
self,
subj: Union[URIRef, str],
pred: Union[URIRef, str],
obj: Union[URIRef, Literal, str]
) -> None:
""" Adds triple to rdflib Graph
Triple can be of any subject, predicate, and object of the entity without a need for order.
... | [
"def",
"add_triple",
"(",
"self",
",",
"subj",
":",
"Union",
"[",
"URIRef",
",",
"str",
"]",
",",
"pred",
":",
"Union",
"[",
"URIRef",
",",
"str",
"]",
",",
"obj",
":",
"Union",
"[",
"URIRef",
",",
"Literal",
",",
"str",
"]",
")",
"->",
"None",
... | Adds triple to rdflib Graph
Triple can be of any subject, predicate, and object of the entity without a need for order.
Args:
subj: Entity subject
pred: Entity predicate
obj: Entity object
Example:
In [1]: add_triple(
...: 'h... | [
"Adds",
"triple",
"to",
"rdflib",
"Graph"
] | python | train | 33.481481 |
amol-/tgext.mailer | tgext/mailer/mailer.py | https://github.com/amol-/tgext.mailer/blob/4c452244969b98431e57d5ebba930f365006dfbd/tgext/mailer/mailer.py#L217-L234 | def send_immediately(self, message, fail_silently=False):
"""Send a message immediately, outside the transaction manager.
If there is a connection error to the mail server this will have to
be handled manually. However if you pass ``fail_silently`` the error
will be swallowed.
... | [
"def",
"send_immediately",
"(",
"self",
",",
"message",
",",
"fail_silently",
"=",
"False",
")",
":",
"try",
":",
"return",
"self",
".",
"smtp_mailer",
".",
"send",
"(",
"*",
"self",
".",
"_message_args",
"(",
"message",
")",
")",
"except",
"smtplib",
".... | Send a message immediately, outside the transaction manager.
If there is a connection error to the mail server this will have to
be handled manually. However if you pass ``fail_silently`` the error
will be swallowed.
:versionadded: 0.3
:param message: a 'Message' instance.
... | [
"Send",
"a",
"message",
"immediately",
"outside",
"the",
"transaction",
"manager",
"."
] | python | train | 34.611111 |
projectatomic/osbs-client | osbs/build/build_request.py | https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/build_request.py#L515-L544 | def adjust_for_registry_api_versions(self):
"""
Enable/disable plugins depending on supported registry API versions
"""
versions = self.spec.registry_api_versions.value
if 'v2' not in versions:
raise OsbsValidationException('v1-only docker registry API is not support... | [
"def",
"adjust_for_registry_api_versions",
"(",
"self",
")",
":",
"versions",
"=",
"self",
".",
"spec",
".",
"registry_api_versions",
".",
"value",
"if",
"'v2'",
"not",
"in",
"versions",
":",
"raise",
"OsbsValidationException",
"(",
"'v1-only docker registry API is no... | Enable/disable plugins depending on supported registry API versions | [
"Enable",
"/",
"disable",
"plugins",
"depending",
"on",
"supported",
"registry",
"API",
"versions"
] | python | train | 40.766667 |
F5Networks/f5-common-python | f5/bigip/tm/sys/ucs.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/ucs.py#L83-L95 | def load(self, **kwargs):
"""Method to list the UCS on the system
Since this is only fixed in 12.1.0 and up
we implemented version check here
"""
# Check if we are using 12.1.0 version or above when using this method
self._is_version_supported_method('12.1.0')
n... | [
"def",
"load",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Check if we are using 12.1.0 version or above when using this method",
"self",
".",
"_is_version_supported_method",
"(",
"'12.1.0'",
")",
"newinst",
"=",
"self",
".",
"_stamp_out_core",
"(",
")",
"newin... | Method to list the UCS on the system
Since this is only fixed in 12.1.0 and up
we implemented version check here | [
"Method",
"to",
"list",
"the",
"UCS",
"on",
"the",
"system"
] | python | train | 30.615385 |
titusjan/argos | argos/inspector/pgplugins/imageplot2d.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/imageplot2d.py#L236-L241 | def setHorCrossPlotAutoRangeOn(self, axisNumber):
""" Sets the horizontal cross-hair plot's auto-range on for the axis with number axisNumber.
:param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
"""
setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.horCrossPlotRange... | [
"def",
"setHorCrossPlotAutoRangeOn",
"(",
"self",
",",
"axisNumber",
")",
":",
"setXYAxesAutoRangeOn",
"(",
"self",
",",
"self",
".",
"xAxisRangeCti",
",",
"self",
".",
"horCrossPlotRangeCti",
",",
"axisNumber",
")"
] | Sets the horizontal cross-hair plot's auto-range on for the axis with number axisNumber.
:param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). | [
"Sets",
"the",
"horizontal",
"cross",
"-",
"hair",
"plot",
"s",
"auto",
"-",
"range",
"on",
"for",
"the",
"axis",
"with",
"number",
"axisNumber",
"."
] | python | train | 55.166667 |
avalente/appmetrics | appmetrics/statistics.py | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L442-L455 | def percentile(data, n):
"""Return the n-th percentile of the given data
Assume that the data are already sorted
"""
size = len(data)
idx = (n / 100.0) * size - 0.5
if idx < 0 or idx > size:
raise StatisticsError("Too few data points ({}) for {}th percentile".format(size, n))
re... | [
"def",
"percentile",
"(",
"data",
",",
"n",
")",
":",
"size",
"=",
"len",
"(",
"data",
")",
"idx",
"=",
"(",
"n",
"/",
"100.0",
")",
"*",
"size",
"-",
"0.5",
"if",
"idx",
"<",
"0",
"or",
"idx",
">",
"size",
":",
"raise",
"StatisticsError",
"(",... | Return the n-th percentile of the given data
Assume that the data are already sorted | [
"Return",
"the",
"n",
"-",
"th",
"percentile",
"of",
"the",
"given",
"data"
] | python | train | 23.285714 |
SkyLothar/shcmd | shcmd/tar.py | https://github.com/SkyLothar/shcmd/blob/d8cad6311a4da7ef09f3419c86b58e30388b7ee3/shcmd/tar.py#L44-L49 | def files(self):
"""files that will be add to tar file later
should be tuple, list or generator that returns strings
"""
ios_names = [info.name for info in self._ios_to_add.keys()]
return set(self.files_to_add + ios_names) | [
"def",
"files",
"(",
"self",
")",
":",
"ios_names",
"=",
"[",
"info",
".",
"name",
"for",
"info",
"in",
"self",
".",
"_ios_to_add",
".",
"keys",
"(",
")",
"]",
"return",
"set",
"(",
"self",
".",
"files_to_add",
"+",
"ios_names",
")"
] | files that will be add to tar file later
should be tuple, list or generator that returns strings | [
"files",
"that",
"will",
"be",
"add",
"to",
"tar",
"file",
"later",
"should",
"be",
"tuple",
"list",
"or",
"generator",
"that",
"returns",
"strings"
] | python | train | 42.833333 |
pymc-devs/pymc | pymc/StepMethods.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L669-L687 | def propose(self):
"""
Proposals for positive definite matrix using random walk deviations on the Cholesky
factor of the current value.
"""
# Locally store size of matrix
dims = self.stochastic.value.shape
# Add normal deviate to value and symmetrize
dev... | [
"def",
"propose",
"(",
"self",
")",
":",
"# Locally store size of matrix",
"dims",
"=",
"self",
".",
"stochastic",
".",
"value",
".",
"shape",
"# Add normal deviate to value and symmetrize",
"dev",
"=",
"rnormal",
"(",
"0",
",",
"self",
".",
"adaptive_scale_factor",... | Proposals for positive definite matrix using random walk deviations on the Cholesky
factor of the current value. | [
"Proposals",
"for",
"positive",
"definite",
"matrix",
"using",
"random",
"walk",
"deviations",
"on",
"the",
"Cholesky",
"factor",
"of",
"the",
"current",
"value",
"."
] | python | train | 27.631579 |
singnet/snet-cli | snet_cli/utils_ipfs.py | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/utils_ipfs.py#L79-L96 | def safe_extract_proto_from_ipfs(ipfs_client, ipfs_hash, protodir):
"""
Tar files might be dangerous (see https://bugs.python.org/issue21109,
and https://docs.python.org/3/library/tarfile.html, TarFile.extractall warning)
we extract only simple files
"""
spec_tar = get_from_ipfs_and_checkhash(ip... | [
"def",
"safe_extract_proto_from_ipfs",
"(",
"ipfs_client",
",",
"ipfs_hash",
",",
"protodir",
")",
":",
"spec_tar",
"=",
"get_from_ipfs_and_checkhash",
"(",
"ipfs_client",
",",
"ipfs_hash",
")",
"with",
"tarfile",
".",
"open",
"(",
"fileobj",
"=",
"io",
".",
"By... | Tar files might be dangerous (see https://bugs.python.org/issue21109,
and https://docs.python.org/3/library/tarfile.html, TarFile.extractall warning)
we extract only simple files | [
"Tar",
"files",
"might",
"be",
"dangerous",
"(",
"see",
"https",
":",
"//",
"bugs",
".",
"python",
".",
"org",
"/",
"issue21109",
"and",
"https",
":",
"//",
"docs",
".",
"python",
".",
"org",
"/",
"3",
"/",
"library",
"/",
"tarfile",
".",
"html",
"... | python | train | 49.777778 |
yymao/generic-catalog-reader | GCR/base.py | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L162-L170 | def get_input_kwargs(self, key=None, default=None):
"""
Deprecated. Use `get_catalog_info` instead.
Get information from the catalog config file.
If *key* is `None`, return the full dict.
"""
warnings.warn("`get_input_kwargs` is deprecated; use `get_catalog_info` instead... | [
"def",
"get_input_kwargs",
"(",
"self",
",",
"key",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`get_input_kwargs` is deprecated; use `get_catalog_info` instead.\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"get... | Deprecated. Use `get_catalog_info` instead.
Get information from the catalog config file.
If *key* is `None`, return the full dict. | [
"Deprecated",
".",
"Use",
"get_catalog_info",
"instead",
"."
] | python | train | 42.888889 |
invinst/ResponseBot | responsebot/responsebot_client.py | https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L97-L109 | def get_tweet(self, id):
"""
Get an existing tweet.
:param id: ID of the tweet in question
:return: Tweet object. None if not found
"""
try:
return Tweet(self._client.get_status(id=id)._json)
except TweepError as e:
if e.api_code == TWITTE... | [
"def",
"get_tweet",
"(",
"self",
",",
"id",
")",
":",
"try",
":",
"return",
"Tweet",
"(",
"self",
".",
"_client",
".",
"get_status",
"(",
"id",
"=",
"id",
")",
".",
"_json",
")",
"except",
"TweepError",
"as",
"e",
":",
"if",
"e",
".",
"api_code",
... | Get an existing tweet.
:param id: ID of the tweet in question
:return: Tweet object. None if not found | [
"Get",
"an",
"existing",
"tweet",
"."
] | python | train | 29.076923 |
COLORFULBOARD/revision | revision/config.py | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/config.py#L68-L106 | def read_config(config_path_or_dict=None):
"""
Read config from given path string or dict object.
:param config_path_or_dict:
:type config_path_or_dict: str or dict
:return: Returns config object or None if not found.
:rtype: :class:`revision.config.Config`
"""
config = None
if isi... | [
"def",
"read_config",
"(",
"config_path_or_dict",
"=",
"None",
")",
":",
"config",
"=",
"None",
"if",
"isinstance",
"(",
"config_path_or_dict",
",",
"dict",
")",
":",
"config",
"=",
"Config",
"(",
"config_path_or_dict",
")",
"if",
"isinstance",
"(",
"config_pa... | Read config from given path string or dict object.
:param config_path_or_dict:
:type config_path_or_dict: str or dict
:return: Returns config object or None if not found.
:rtype: :class:`revision.config.Config` | [
"Read",
"config",
"from",
"given",
"path",
"string",
"or",
"dict",
"object",
"."
] | python | train | 26.487179 |
serkanyersen/underscore.py | src/underscore.py | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L789-L800 | def delay(self, wait, *args):
"""
Delays a function for the given number of milliseconds, and then calls
it with the arguments supplied.
"""
def call_it():
self.obj(*args)
t = Timer((float(wait) / float(1000)), call_it)
t.start()
return self.... | [
"def",
"delay",
"(",
"self",
",",
"wait",
",",
"*",
"args",
")",
":",
"def",
"call_it",
"(",
")",
":",
"self",
".",
"obj",
"(",
"*",
"args",
")",
"t",
"=",
"Timer",
"(",
"(",
"float",
"(",
"wait",
")",
"/",
"float",
"(",
"1000",
")",
")",
"... | Delays a function for the given number of milliseconds, and then calls
it with the arguments supplied. | [
"Delays",
"a",
"function",
"for",
"the",
"given",
"number",
"of",
"milliseconds",
"and",
"then",
"calls",
"it",
"with",
"the",
"arguments",
"supplied",
"."
] | python | train | 27 |
lordmauve/lepton | examples/games/bonk/game.py | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/game.py#L263-L268 | def update(self, td):
"""Update state of ball"""
self.sprite.last_position = self.sprite.position
self.sprite.last_velocity = self.sprite.velocity
if self.particle_group != None:
self.update_particle_group(td) | [
"def",
"update",
"(",
"self",
",",
"td",
")",
":",
"self",
".",
"sprite",
".",
"last_position",
"=",
"self",
".",
"sprite",
".",
"position",
"self",
".",
"sprite",
".",
"last_velocity",
"=",
"self",
".",
"sprite",
".",
"velocity",
"if",
"self",
".",
... | Update state of ball | [
"Update",
"state",
"of",
"ball"
] | python | train | 42.166667 |
juju/python-libjuju | juju/client/_client1.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client1.py#L3071-L3086 | async def DestroyMachines(self, force, machine_names):
'''
force : bool
machine_names : typing.Sequence[str]
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Client',
request='DestroyMachines',
... | [
"async",
"def",
"DestroyMachines",
"(",
"self",
",",
"force",
",",
"machine_names",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Client'",
",",
"request",
"=",
"'DestroyMachines'",
",",
"... | force : bool
machine_names : typing.Sequence[str]
Returns -> None | [
"force",
":",
"bool",
"machine_names",
":",
"typing",
".",
"Sequence",
"[",
"str",
"]",
"Returns",
"-",
">",
"None"
] | python | train | 31.1875 |
PlaidWeb/Publ | publ/queries.py | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L145-L157 | def where_entry_date(query, datespec):
""" Where clause for entries which match a textual date spec
datespec -- The date spec to check for, in YYYY[[-]MM[[-]DD]] format
"""
date, interval, _ = utils.parse_date(datespec)
start_date, end_date = date.span(interval)
return orm.select(
e fo... | [
"def",
"where_entry_date",
"(",
"query",
",",
"datespec",
")",
":",
"date",
",",
"interval",
",",
"_",
"=",
"utils",
".",
"parse_date",
"(",
"datespec",
")",
"start_date",
",",
"end_date",
"=",
"date",
".",
"span",
"(",
"interval",
")",
"return",
"orm",
... | Where clause for entries which match a textual date spec
datespec -- The date spec to check for, in YYYY[[-]MM[[-]DD]] format | [
"Where",
"clause",
"for",
"entries",
"which",
"match",
"a",
"textual",
"date",
"spec"
] | python | train | 31.769231 |
picleslivre/plumber | plumber.py | https://github.com/picleslivre/plumber/blob/f5019ef20679b3e9a31c6c84e4f4529d72dc8db9/plumber.py#L203-L229 | def run(self, data, rewrap=False, prefetch=0):
"""
Wires the pipeline and returns a lazy object of
the transformed data.
:param data: must be an iterable, where a full document
must be returned for each loop
:param rewrap: (optional) is a bool that indicates the need to... | [
"def",
"run",
"(",
"self",
",",
"data",
",",
"rewrap",
"=",
"False",
",",
"prefetch",
"=",
"0",
")",
":",
"if",
"rewrap",
":",
"data",
"=",
"[",
"data",
"]",
"for",
"_filter",
"in",
"self",
".",
"_filters",
":",
"_filter",
".",
"feed",
"(",
"data... | Wires the pipeline and returns a lazy object of
the transformed data.
:param data: must be an iterable, where a full document
must be returned for each loop
:param rewrap: (optional) is a bool that indicates the need to rewrap
data in cases where iterating over it produces unde... | [
"Wires",
"the",
"pipeline",
"and",
"returns",
"a",
"lazy",
"object",
"of",
"the",
"transformed",
"data",
"."
] | python | train | 37.074074 |
wimglenn/advent-of-code-data | aocd/models.py | https://github.com/wimglenn/advent-of-code-data/blob/a3856459d225840f2b6919659fc65aa7a6a74533/aocd/models.py#L283-L312 | def _get_answer(self, part):
"""
Note: Answers are only revealed after a correct submission. If you've
have not already solved the puzzle, AocdError will be raised.
"""
answer_fname = getattr(self, "answer_{}_fname".format(part))
if os.path.isfile(answer_fname):
... | [
"def",
"_get_answer",
"(",
"self",
",",
"part",
")",
":",
"answer_fname",
"=",
"getattr",
"(",
"self",
",",
"\"answer_{}_fname\"",
".",
"format",
"(",
"part",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"answer_fname",
")",
":",
"with",
"ope... | Note: Answers are only revealed after a correct submission. If you've
have not already solved the puzzle, AocdError will be raised. | [
"Note",
":",
"Answers",
"are",
"only",
"revealed",
"after",
"a",
"correct",
"submission",
".",
"If",
"you",
"ve",
"have",
"not",
"already",
"solved",
"the",
"puzzle",
"AocdError",
"will",
"be",
"raised",
"."
] | python | train | 47.8 |
exa-analytics/exa | exa/core/editor.py | https://github.com/exa-analytics/exa/blob/40fb3c22b531d460dbc51e603de75b856cc28f0d/exa/core/editor.py#L183-L219 | def find(self, *strings, **kwargs):
"""
Search the entire editor for lines that match the string.
.. code-block:: Python
string = '''word one
word two
three'''
ed = Editor(string)
ed.find('word') # [(0, "word one"), (1, "word... | [
"def",
"find",
"(",
"self",
",",
"*",
"strings",
",",
"*",
"*",
"kwargs",
")",
":",
"start",
"=",
"kwargs",
".",
"pop",
"(",
"\"start\"",
",",
"0",
")",
"stop",
"=",
"kwargs",
".",
"pop",
"(",
"\"stop\"",
",",
"None",
")",
"keys_only",
"=",
"kwar... | Search the entire editor for lines that match the string.
.. code-block:: Python
string = '''word one
word two
three'''
ed = Editor(string)
ed.find('word') # [(0, "word one"), (1, "word two")]
ed.find('word', 'three') # {'word': ... | [
"Search",
"the",
"entire",
"editor",
"for",
"lines",
"that",
"match",
"the",
"string",
"."
] | python | train | 37.459459 |
xapple/plumbing | plumbing/common.py | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L417-L445 | def download_from_url(source, destination, progress=False, uncompress=False):
"""Download a file from an URL and place it somewhere. Like wget.
Uses requests and tqdm to display progress if you want.
By default it will uncompress files.
#TODO: handle case where destination is a directory"""
# Module... | [
"def",
"download_from_url",
"(",
"source",
",",
"destination",
",",
"progress",
"=",
"False",
",",
"uncompress",
"=",
"False",
")",
":",
"# Modules #",
"from",
"tqdm",
"import",
"tqdm",
"import",
"requests",
"from",
"autopaths",
".",
"file_path",
"import",
"Fi... | Download a file from an URL and place it somewhere. Like wget.
Uses requests and tqdm to display progress if you want.
By default it will uncompress files.
#TODO: handle case where destination is a directory | [
"Download",
"a",
"file",
"from",
"an",
"URL",
"and",
"place",
"it",
"somewhere",
".",
"Like",
"wget",
".",
"Uses",
"requests",
"and",
"tqdm",
"to",
"display",
"progress",
"if",
"you",
"want",
".",
"By",
"default",
"it",
"will",
"uncompress",
"files",
"."... | python | train | 41.655172 |
Capitains/MyCapytain | MyCapytain/common/reference/_capitains_cts.py | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/reference/_capitains_cts.py#L828-L872 | def fill(self, passage=None, xpath=None):
""" Fill the xpath with given informations
:param passage: CapitainsCtsPassage reference
:type passage: CtsReference or list or None. Can be list of None and not None
:param xpath: If set to True, will return the replaced self.xpath value and no... | [
"def",
"fill",
"(",
"self",
",",
"passage",
"=",
"None",
",",
"xpath",
"=",
"None",
")",
":",
"if",
"xpath",
"is",
"True",
":",
"# Then passage is a string or None",
"xpath",
"=",
"self",
".",
"xpath",
"replacement",
"=",
"r\"\\1\"",
"if",
"isinstance",
"(... | Fill the xpath with given informations
:param passage: CapitainsCtsPassage reference
:type passage: CtsReference or list or None. Can be list of None and not None
:param xpath: If set to True, will return the replaced self.xpath value and not the whole self.refsDecl
:type xpath: Boolean... | [
"Fill",
"the",
"xpath",
"with",
"given",
"informations"
] | python | train | 36.933333 |
h2oai/h2o-3 | h2o-py/h2o/model/binomial.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/binomial.py#L551-L570 | def find_idx_by_threshold(self, threshold, train=False, valid=False, xval=False):
"""
Retrieve the index in this metric's threshold list at which the given threshold is located.
If all are False (default), then return the training metric value.
If more than one options is set to True, t... | [
"def",
"find_idx_by_threshold",
"(",
"self",
",",
"threshold",
",",
"train",
"=",
"False",
",",
"valid",
"=",
"False",
",",
"xval",
"=",
"False",
")",
":",
"tm",
"=",
"ModelBase",
".",
"_get_metrics",
"(",
"self",
",",
"train",
",",
"valid",
",",
"xval... | Retrieve the index in this metric's threshold list at which the given threshold is located.
If all are False (default), then return the training metric value.
If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
"valid", and "xval".
:... | [
"Retrieve",
"the",
"index",
"in",
"this",
"metric",
"s",
"threshold",
"list",
"at",
"which",
"the",
"given",
"threshold",
"is",
"located",
"."
] | python | test | 56.3 |
nschloe/colorio | experiments/new-cs.py | https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/experiments/new-cs.py#L757-L798 | def cost_min2(self, alpha):
"""Residual formulation, Hessian is a low-rank update of the identity.
"""
n = self.V.dim()
ax = alpha[:n]
ay = alpha[n:]
# ml = pyamg.ruge_stuben_solver(self.L)
# # ml = pyamg.smoothed_aggregation_solver(self.L)
# print(ml)
... | [
"def",
"cost_min2",
"(",
"self",
",",
"alpha",
")",
":",
"n",
"=",
"self",
".",
"V",
".",
"dim",
"(",
")",
"ax",
"=",
"alpha",
"[",
":",
"n",
"]",
"ay",
"=",
"alpha",
"[",
"n",
":",
"]",
"# ml = pyamg.ruge_stuben_solver(self.L)",
"# # ml = pyamg.smooth... | Residual formulation, Hessian is a low-rank update of the identity. | [
"Residual",
"formulation",
"Hessian",
"is",
"a",
"low",
"-",
"rank",
"update",
"of",
"the",
"identity",
"."
] | python | train | 27.238095 |
JasonKessler/scattertext | scattertext/representations/EmbeddingsResolver.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/representations/EmbeddingsResolver.py#L17-L28 | def set_embeddings(self, embeddings):
'''
Specifies fixed set of embeddings
:param embeddings: array-like, sparse or dense, shape should be (embedding size, # terms)
:return: EmbeddingsResolver
'''
if self.embeddings_ is not None:
raise Exception("You have alr... | [
"def",
"set_embeddings",
"(",
"self",
",",
"embeddings",
")",
":",
"if",
"self",
".",
"embeddings_",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"\"You have already set embeddings by running set_embeddings or set_embeddings_model.\"",
")",
"assert",
"embeddings",... | Specifies fixed set of embeddings
:param embeddings: array-like, sparse or dense, shape should be (embedding size, # terms)
:return: EmbeddingsResolver | [
"Specifies",
"fixed",
"set",
"of",
"embeddings",
":",
"param",
"embeddings",
":",
"array",
"-",
"like",
"sparse",
"or",
"dense",
"shape",
"should",
"be",
"(",
"embedding",
"size",
"#",
"terms",
")",
":",
"return",
":",
"EmbeddingsResolver"
] | python | train | 46.25 |
stephenmcd/gnotty | gnotty/client.py | https://github.com/stephenmcd/gnotty/blob/bea3762dc9cbc3cb21a5ae7224091cf027273c40/gnotty/client.py#L176-L185 | def on_quit(self, connection, event):
"""
Someone left the channel - send the nicknames list to the
WebSocket.
"""
nickname = self.get_nickname(event)
nickname_color = self.nicknames[nickname]
del self.nicknames[nickname]
self.namespace.emit("message", nic... | [
"def",
"on_quit",
"(",
"self",
",",
"connection",
",",
"event",
")",
":",
"nickname",
"=",
"self",
".",
"get_nickname",
"(",
"event",
")",
"nickname_color",
"=",
"self",
".",
"nicknames",
"[",
"nickname",
"]",
"del",
"self",
".",
"nicknames",
"[",
"nickn... | Someone left the channel - send the nicknames list to the
WebSocket. | [
"Someone",
"left",
"the",
"channel",
"-",
"send",
"the",
"nicknames",
"list",
"to",
"the",
"WebSocket",
"."
] | python | train | 37.3 |
barryp/py-amqplib | amqplib/client_0_8/connection.py | https://github.com/barryp/py-amqplib/blob/2b3a47de34b4712c111d0a55d7ff109dffc2a7b2/amqplib/client_0_8/connection.py#L495-L508 | def _open_ok(self, args):
"""
signal that the connection is ready
This method signals to the client that the connection is ready
for use.
PARAMETERS:
known_hosts: shortstr
"""
self.known_hosts = args.read_shortstr()
AMQP_LOGGER.debug('Open O... | [
"def",
"_open_ok",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"known_hosts",
"=",
"args",
".",
"read_shortstr",
"(",
")",
"AMQP_LOGGER",
".",
"debug",
"(",
"'Open OK! known_hosts [%s]'",
"%",
"self",
".",
"known_hosts",
")",
"return",
"None"
] | signal that the connection is ready
This method signals to the client that the connection is ready
for use.
PARAMETERS:
known_hosts: shortstr | [
"signal",
"that",
"the",
"connection",
"is",
"ready"
] | python | train | 26.214286 |
stephen-bunn/file-config | src/file_config/handlers/ini.py | https://github.com/stephen-bunn/file-config/blob/93429360c949985202e1f2b9cd0340731819ba75/src/file_config/handlers/ini.py#L27-L60 | def on_configparser_dumps(self, configparser, config, dictionary, **kwargs):
""" The :mod:`configparser` dumps method.
:param module configparser: The ``configparser`` module
:param class config: The instance's config class
:param dict dictionary: The dictionary instance to serialize
... | [
"def",
"on_configparser_dumps",
"(",
"self",
",",
"configparser",
",",
"config",
",",
"dictionary",
",",
"*",
"*",
"kwargs",
")",
":",
"root_section",
"=",
"kwargs",
".",
"pop",
"(",
"\"root\"",
")",
"if",
"not",
"isinstance",
"(",
"root_section",
",",
"st... | The :mod:`configparser` dumps method.
:param module configparser: The ``configparser`` module
:param class config: The instance's config class
:param dict dictionary: The dictionary instance to serialize
:param str root: The top-level section of the ini file,
defaults to ``c... | [
"The",
":",
"mod",
":",
"configparser",
"dumps",
"method",
"."
] | python | train | 42.558824 |
jazzband/django-discover-jenkins | setup.py | https://github.com/jazzband/django-discover-jenkins/blob/c0c859dfdd571de6e8f63865dfc8ebac6bab1d07/setup.py#L12-L19 | def get_author_and_version(package):
"""
Return package author and version as listed in `init.py`.
"""
init_py = open(os.path.join(package, '__init__.py')).read()
author = re.search("__author__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
version = re.search("__version__ = ['\"]([^'\"]+)['\"]", ini... | [
"def",
"get_author_and_version",
"(",
"package",
")",
":",
"init_py",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"package",
",",
"'__init__.py'",
")",
")",
".",
"read",
"(",
")",
"author",
"=",
"re",
".",
"search",
"(",
"\"__author__ = ['\\\"... | Return package author and version as listed in `init.py`. | [
"Return",
"package",
"author",
"and",
"version",
"as",
"listed",
"in",
"init",
".",
"py",
"."
] | python | valid | 44.25 |
apache/incubator-heron | heron/tools/common/src/python/access/heron_api.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/access/heron_api.py#L621-L645 | def run_instance_jmap(cluster, environ, topology, instance, role=None):
'''
:param cluster:
:param environ:
:param topology:
:param instance:
:param role:
:return:
'''
params = dict(
cluster=cluster,
environ=environ,
topology=topology,
instance=instance)
if role is not None:... | [
"def",
"run_instance_jmap",
"(",
"cluster",
",",
"environ",
",",
"topology",
",",
"instance",
",",
"role",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
"cluster",
"=",
"cluster",
",",
"environ",
"=",
"environ",
",",
"topology",
"=",
"topology",
","... | :param cluster:
:param environ:
:param topology:
:param instance:
:param role:
:return: | [
":",
"param",
"cluster",
":",
":",
"param",
"environ",
":",
":",
"param",
"topology",
":",
":",
"param",
"instance",
":",
":",
"param",
"role",
":",
":",
"return",
":"
] | python | valid | 23.04 |
klen/muffin-babel | muffin_babel.py | https://github.com/klen/muffin-babel/blob/f48ebbbf7806c6c727f66d8d0df331b29f6ead08/muffin_babel.py#L263-L266 | def pgettext(self, context, string, domain=None, **variables):
"""Like :meth:`gettext` but with a context."""
t = self.get_translations(domain)
return t.upgettext(context, string) % variables | [
"def",
"pgettext",
"(",
"self",
",",
"context",
",",
"string",
",",
"domain",
"=",
"None",
",",
"*",
"*",
"variables",
")",
":",
"t",
"=",
"self",
".",
"get_translations",
"(",
"domain",
")",
"return",
"t",
".",
"upgettext",
"(",
"context",
",",
"str... | Like :meth:`gettext` but with a context. | [
"Like",
":",
"meth",
":",
"gettext",
"but",
"with",
"a",
"context",
"."
] | python | train | 53 |
junaruga/rpm-py-installer | install.py | https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1770-L1773 | def cd(cls, directory):
"""Change directory. It behaves like "cd directory"."""
Log.debug('CMD: cd {0}'.format(directory))
os.chdir(directory) | [
"def",
"cd",
"(",
"cls",
",",
"directory",
")",
":",
"Log",
".",
"debug",
"(",
"'CMD: cd {0}'",
".",
"format",
"(",
"directory",
")",
")",
"os",
".",
"chdir",
"(",
"directory",
")"
] | Change directory. It behaves like "cd directory". | [
"Change",
"directory",
".",
"It",
"behaves",
"like",
"cd",
"directory",
"."
] | python | train | 40.75 |
pandas-dev/pandas | pandas/io/pytables.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L2911-L2924 | def write(self, obj, **kwargs):
""" write it as a collection of individual sparse series """
super().write(obj, **kwargs)
for name, ss in obj.items():
key = 'sparse_series_{name}'.format(name=name)
if key not in self.group._v_children:
node = self._handle.... | [
"def",
"write",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"write",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
"for",
"name",
",",
"ss",
"in",
"obj",
".",
"items",
"(",
")",
":",
"key",
"=",
"'sparse_se... | write it as a collection of individual sparse series | [
"write",
"it",
"as",
"a",
"collection",
"of",
"individual",
"sparse",
"series"
] | python | train | 45.857143 |
bcbio/bcbio-nextgen | bcbio/variation/validateplot.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validateplot.py#L304-L315 | def _ggplot(df, out_file):
"""Plot faceted items with ggplot wrapper on top of matplotlib.
XXX Not yet functional
"""
import ggplot as gg
df["variant.type"] = [vtype_labels[x] for x in df["variant.type"]]
df["category"] = [cat_labels[x] for x in df["category"]]
df["caller"] = [caller_labels.... | [
"def",
"_ggplot",
"(",
"df",
",",
"out_file",
")",
":",
"import",
"ggplot",
"as",
"gg",
"df",
"[",
"\"variant.type\"",
"]",
"=",
"[",
"vtype_labels",
"[",
"x",
"]",
"for",
"x",
"in",
"df",
"[",
"\"variant.type\"",
"]",
"]",
"df",
"[",
"\"category\"",
... | Plot faceted items with ggplot wrapper on top of matplotlib.
XXX Not yet functional | [
"Plot",
"faceted",
"items",
"with",
"ggplot",
"wrapper",
"on",
"top",
"of",
"matplotlib",
".",
"XXX",
"Not",
"yet",
"functional"
] | python | train | 44.25 |
angr/angr | angr/state_plugins/javavm_classloader.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/javavm_classloader.py#L68-L106 | def init_class(self, class_, step_func=None):
"""
This method simulates the loading of a class by the JVM, during which
parts of the class (e.g. static fields) are initialized. For this, we
run the class initializer method <clinit> (if available) and update
the state accordingly.... | [
"def",
"init_class",
"(",
"self",
",",
"class_",
",",
"step_func",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_class_initialized",
"(",
"class_",
")",
":",
"l",
".",
"debug",
"(",
"\"Class %r already initialized.\"",
",",
"class_",
")",
"return",
"l",
".... | This method simulates the loading of a class by the JVM, during which
parts of the class (e.g. static fields) are initialized. For this, we
run the class initializer method <clinit> (if available) and update
the state accordingly.
Note: Initialization is skipped, if the class has alread... | [
"This",
"method",
"simulates",
"the",
"loading",
"of",
"a",
"class",
"by",
"the",
"JVM",
"during",
"which",
"parts",
"of",
"the",
"class",
"(",
"e",
".",
"g",
".",
"static",
"fields",
")",
"are",
"initialized",
".",
"For",
"this",
"we",
"run",
"the",
... | python | train | 52.923077 |
mjirik/imcut | imcut/image_manipulation.py | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/image_manipulation.py#L85-L121 | def seed_zoom(seeds, zoom):
"""
Smart zoom for sparse matrix. If there is resize to bigger resolution
thin line of label could be lost. This function prefers labels larger
then zero. If there is only one small voxel in larger volume with zeros
it is selected.
"""
# import scipy
# loseeds... | [
"def",
"seed_zoom",
"(",
"seeds",
",",
"zoom",
")",
":",
"# import scipy",
"# loseeds=seeds",
"labels",
"=",
"np",
".",
"unique",
"(",
"seeds",
")",
"# remove first label - 0",
"labels",
"=",
"np",
".",
"delete",
"(",
"labels",
",",
"0",
")",
"# @TODO smart ... | Smart zoom for sparse matrix. If there is resize to bigger resolution
thin line of label could be lost. This function prefers labels larger
then zero. If there is only one small voxel in larger volume with zeros
it is selected. | [
"Smart",
"zoom",
"for",
"sparse",
"matrix",
".",
"If",
"there",
"is",
"resize",
"to",
"bigger",
"resolution",
"thin",
"line",
"of",
"label",
"could",
"be",
"lost",
".",
"This",
"function",
"prefers",
"labels",
"larger",
"then",
"zero",
".",
"If",
"there",
... | python | train | 32.405405 |
mwhooker/jsonselect | jsonselect/jsonselect.py | https://github.com/mwhooker/jsonselect/blob/c64aa9ea930de0344797ff87b04c753c8fc096a6/jsonselect/jsonselect.py#L432-L442 | def _match_nodes(self, validators, obj):
"""Apply each validator in validators to each node in obj.
Return each node in obj which matches all validators.
"""
results = []
for node in object_iter(obj):
if all([validate(node) for validate in validators]):
... | [
"def",
"_match_nodes",
"(",
"self",
",",
"validators",
",",
"obj",
")",
":",
"results",
"=",
"[",
"]",
"for",
"node",
"in",
"object_iter",
"(",
"obj",
")",
":",
"if",
"all",
"(",
"[",
"validate",
"(",
"node",
")",
"for",
"validate",
"in",
"validators... | Apply each validator in validators to each node in obj.
Return each node in obj which matches all validators. | [
"Apply",
"each",
"validator",
"in",
"validators",
"to",
"each",
"node",
"in",
"obj",
"."
] | python | test | 32.454545 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L169-L172 | def match_string(self, stype):
"""Match string type."""
return not (stype - self.string_types) or bool(stype & self.wild_string_types) | [
"def",
"match_string",
"(",
"self",
",",
"stype",
")",
":",
"return",
"not",
"(",
"stype",
"-",
"self",
".",
"string_types",
")",
"or",
"bool",
"(",
"stype",
"&",
"self",
".",
"wild_string_types",
")"
] | Match string type. | [
"Match",
"string",
"type",
"."
] | python | train | 37 |
twilio/twilio-python | twilio/rest/video/v1/composition_hook.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/video/v1/composition_hook.py#L104-L139 | def page(self, enabled=values.unset, date_created_after=values.unset,
date_created_before=values.unset, friendly_name=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of CompositionHookInstance rec... | [
"def",
"page",
"(",
"self",
",",
"enabled",
"=",
"values",
".",
"unset",
",",
"date_created_after",
"=",
"values",
".",
"unset",
",",
"date_created_before",
"=",
"values",
".",
"unset",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"page_token",
... | Retrieve a single page of CompositionHookInstance records from the API.
Request is executed immediately
:param bool enabled: Only show Composition Hooks enabled or disabled.
:param datetime date_created_after: Only show Composition Hooks created on or after this ISO8601 date-time with timezone.... | [
"Retrieve",
"a",
"single",
"page",
"of",
"CompositionHookInstance",
"records",
"from",
"the",
"API",
".",
"Request",
"is",
"executed",
"immediately"
] | python | train | 47.722222 |
ff0000/scarlet | scarlet/versioning/models.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/versioning/models.py#L678-L727 | def publish(self, user=None, when=None):
"""
Publishes a item and any sub items.
A new transaction will be started if
we aren't already in a transaction.
Should only be run on draft items
"""
assert self.state == self.DRAFT
user_published = 'code'
... | [
"def",
"publish",
"(",
"self",
",",
"user",
"=",
"None",
",",
"when",
"=",
"None",
")",
":",
"assert",
"self",
".",
"state",
"==",
"self",
".",
"DRAFT",
"user_published",
"=",
"'code'",
"if",
"user",
":",
"user_published",
"=",
"user",
".",
"username",... | Publishes a item and any sub items.
A new transaction will be started if
we aren't already in a transaction.
Should only be run on draft items | [
"Publishes",
"a",
"item",
"and",
"any",
"sub",
"items",
".",
"A",
"new",
"transaction",
"will",
"be",
"started",
"if",
"we",
"aren",
"t",
"already",
"in",
"a",
"transaction",
"."
] | python | train | 32.48 |
sublee/zeronimo | zeronimo/helpers.py | https://github.com/sublee/zeronimo/blob/b216638232932718d2cbc5eabd870c8f5b5e83fb/zeronimo/helpers.py#L111-L113 | def eintr_retry_zmq(f, *args, **kwargs):
"""The specialization of :func:`eintr_retry` by :exc:`zmq.ZMQError`."""
return eintr_retry(zmq.ZMQError, f, *args, **kwargs) | [
"def",
"eintr_retry_zmq",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"eintr_retry",
"(",
"zmq",
".",
"ZMQError",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | The specialization of :func:`eintr_retry` by :exc:`zmq.ZMQError`. | [
"The",
"specialization",
"of",
":",
"func",
":",
"eintr_retry",
"by",
":",
"exc",
":",
"zmq",
".",
"ZMQError",
"."
] | python | test | 57 |
skorch-dev/skorch | skorch/cli.py | https://github.com/skorch-dev/skorch/blob/5b9b8b7b7712cb6e5aaa759d9608ea6269d5bcd3/skorch/cli.py#L102-L135 | def _resolve_dotted_name(dotted_name):
"""Returns objects from strings
Deals e.g. with 'torch.nn.Softmax(dim=-1)'.
Modified from palladium:
https://github.com/ottogroup/palladium/blob/8a066a9a7690557d9b1b6ed54b7d1a1502ba59e3/palladium/util.py
with added support for instantiated objects.
"""... | [
"def",
"_resolve_dotted_name",
"(",
"dotted_name",
")",
":",
"if",
"not",
"isinstance",
"(",
"dotted_name",
",",
"str",
")",
":",
"return",
"dotted_name",
"if",
"'.'",
"not",
"in",
"dotted_name",
":",
"return",
"dotted_name",
"args",
"=",
"None",
"params",
"... | Returns objects from strings
Deals e.g. with 'torch.nn.Softmax(dim=-1)'.
Modified from palladium:
https://github.com/ottogroup/palladium/blob/8a066a9a7690557d9b1b6ed54b7d1a1502ba59e3/palladium/util.py
with added support for instantiated objects. | [
"Returns",
"objects",
"from",
"strings"
] | python | train | 24.147059 |
prompt-toolkit/pymux | pymux/commands/commands.py | https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L595-L599 | def display_message(pymux, variables):
" Display a message. "
message = variables['<message>']
client_state = pymux.get_client_state()
client_state.message = message | [
"def",
"display_message",
"(",
"pymux",
",",
"variables",
")",
":",
"message",
"=",
"variables",
"[",
"'<message>'",
"]",
"client_state",
"=",
"pymux",
".",
"get_client_state",
"(",
")",
"client_state",
".",
"message",
"=",
"message"
] | Display a message. | [
"Display",
"a",
"message",
"."
] | python | train | 35.4 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L290-L338 | def clear_tc(self, owner, data, clear_type):
"""Delete threat intel from ThreatConnect platform.
Args:
owner (str): The ThreatConnect owner.
data (dict): The data for the threat intel to clear.
clear_type (str): The type of clear action.
"""
batch = s... | [
"def",
"clear_tc",
"(",
"self",
",",
"owner",
",",
"data",
",",
"clear_type",
")",
":",
"batch",
"=",
"self",
".",
"tcex",
".",
"batch",
"(",
"owner",
",",
"action",
"=",
"'Delete'",
")",
"tc_type",
"=",
"data",
".",
"get",
"(",
"'type'",
")",
"pat... | Delete threat intel from ThreatConnect platform.
Args:
owner (str): The ThreatConnect owner.
data (dict): The data for the threat intel to clear.
clear_type (str): The type of clear action. | [
"Delete",
"threat",
"intel",
"from",
"ThreatConnect",
"platform",
"."
] | python | train | 42.387755 |
arviz-devs/arviz | arviz/data/io_tfp.py | https://github.com/arviz-devs/arviz/blob/d04d8da07f029fd2931f48d2f7f324cf393e5277/arviz/data/io_tfp.py#L123-L150 | def sample_stats_to_xarray(self):
"""Extract sample_stats from tfp trace."""
if self.model_fn is None or self.observed is None:
return None
log_likelihood = []
sample_size = self.posterior[0].shape[0]
for i in range(sample_size):
variables = {}
... | [
"def",
"sample_stats_to_xarray",
"(",
"self",
")",
":",
"if",
"self",
".",
"model_fn",
"is",
"None",
"or",
"self",
".",
"observed",
"is",
"None",
":",
"return",
"None",
"log_likelihood",
"=",
"[",
"]",
"sample_size",
"=",
"self",
".",
"posterior",
"[",
"... | Extract sample_stats from tfp trace. | [
"Extract",
"sample_stats",
"from",
"tfp",
"trace",
"."
] | python | train | 37.785714 |
tchellomello/python-arlo | pyarlo/base_station.py | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L305-L312 | def available_modes(self):
"""Return list of available mode names."""
if not self._available_modes:
modes = self.available_modes_with_ids
if not modes:
return None
self._available_modes = list(modes.keys())
return self._available_modes | [
"def",
"available_modes",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_available_modes",
":",
"modes",
"=",
"self",
".",
"available_modes_with_ids",
"if",
"not",
"modes",
":",
"return",
"None",
"self",
".",
"_available_modes",
"=",
"list",
"(",
"modes"... | Return list of available mode names. | [
"Return",
"list",
"of",
"available",
"mode",
"names",
"."
] | python | train | 38 |
LonamiWebs/Telethon | telethon/crypto/rsa.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/crypto/rsa.py#L21-L34 | def get_byte_array(integer):
"""Return the variable length bytes corresponding to the given int"""
# Operate in big endian (unlike most of Telegram API) since:
# > "...pq is a representation of a natural number
# (in binary *big endian* format)..."
# > "...current value of dh_prime equals
# ... | [
"def",
"get_byte_array",
"(",
"integer",
")",
":",
"# Operate in big endian (unlike most of Telegram API) since:",
"# > \"...pq is a representation of a natural number",
"# (in binary *big endian* format)...\"",
"# > \"...current value of dh_prime equals",
"# (in *big-endian* byte order)..... | Return the variable length bytes corresponding to the given int | [
"Return",
"the",
"variable",
"length",
"bytes",
"corresponding",
"to",
"the",
"given",
"int"
] | python | train | 40 |
MAVENSDC/cdflib | cdflib/cdfwrite.py | https://github.com/MAVENSDC/cdflib/blob/d237c60e5db67db0f92d96054209c25c4042465c/cdflib/cdfwrite.py#L605-L818 | def write_var(self, var_spec, var_attrs=None, var_data=None):
'''
Writes a variable, along with variable attributes and data.
Parameters
----------
var_spec : dict
The specifications of the variable.
The required/optional keys for creating a variable:
... | [
"def",
"write_var",
"(",
"self",
",",
"var_spec",
",",
"var_attrs",
"=",
"None",
",",
"var_data",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"var_spec",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'Variable should be in dictionary form.'",
... | Writes a variable, along with variable attributes and data.
Parameters
----------
var_spec : dict
The specifications of the variable.
The required/optional keys for creating a variable:
Required keys:
- ['Variable']: The name of the variable
... | [
"Writes",
"a",
"variable",
"along",
"with",
"variable",
"attributes",
"and",
"data",
"."
] | python | train | 42.560748 |
secdev/scapy | scapy/contrib/diameter.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/diameter.py#L4819-L4824 | def DiamAns(cmd, **fields):
"""Craft Diameter answer commands"""
upfields, name = getCmdParams(cmd, False, **fields)
p = DiamG(**upfields)
p.name = name
return p | [
"def",
"DiamAns",
"(",
"cmd",
",",
"*",
"*",
"fields",
")",
":",
"upfields",
",",
"name",
"=",
"getCmdParams",
"(",
"cmd",
",",
"False",
",",
"*",
"*",
"fields",
")",
"p",
"=",
"DiamG",
"(",
"*",
"*",
"upfields",
")",
"p",
".",
"name",
"=",
"na... | Craft Diameter answer commands | [
"Craft",
"Diameter",
"answer",
"commands"
] | python | train | 29.333333 |
broadinstitute/fiss | firecloud/fiss.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/fiss.py#L915-L1000 | def attr_delete(args):
''' Delete key=value attributes: if entity name & type are specified then
attributes will be deleted from that entity, otherwise the attribute will
be removed from the workspace'''
if args.entity_type and args.entities:
# Since there is no attribute deletion endpoint, we ... | [
"def",
"attr_delete",
"(",
"args",
")",
":",
"if",
"args",
".",
"entity_type",
"and",
"args",
".",
"entities",
":",
"# Since there is no attribute deletion endpoint, we must perform 2 steps",
"# here: first we retrieve the entity_ids, and any foreign keys (e.g.",
"# participant_id ... | Delete key=value attributes: if entity name & type are specified then
attributes will be deleted from that entity, otherwise the attribute will
be removed from the workspace | [
"Delete",
"key",
"=",
"value",
"attributes",
":",
"if",
"entity",
"name",
"&",
"type",
"are",
"specified",
"then",
"attributes",
"will",
"be",
"deleted",
"from",
"that",
"entity",
"otherwise",
"the",
"attribute",
"will",
"be",
"removed",
"from",
"the",
"work... | python | train | 44.337209 |
ejeschke/ginga | ginga/rv/plugins/FBrowser.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/FBrowser.py#L269-L296 | def open_files(self, path):
"""Load file(s) -- image*.fits, image*.fits[ext].
Returns success code (True or False).
"""
paths = []
input_list = _patt.findall(path)
if not input_list:
input_list = [path]
for path in input_list:
# Strips tra... | [
"def",
"open_files",
"(",
"self",
",",
"path",
")",
":",
"paths",
"=",
"[",
"]",
"input_list",
"=",
"_patt",
".",
"findall",
"(",
"path",
")",
"if",
"not",
"input_list",
":",
"input_list",
"=",
"[",
"path",
"]",
"for",
"path",
"in",
"input_list",
":"... | Load file(s) -- image*.fits, image*.fits[ext].
Returns success code (True or False). | [
"Load",
"file",
"(",
"s",
")",
"--",
"image",
"*",
".",
"fits",
"image",
"*",
".",
"fits",
"[",
"ext",
"]",
".",
"Returns",
"success",
"code",
"(",
"True",
"or",
"False",
")",
"."
] | python | train | 30.535714 |
jluttine/d3py | d3py/core.py | https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L79-L95 | def create_graph_html(js_template, css_template, html_template=None):
""" Create HTML code block given the graph Javascript and CSS. """
if html_template is None:
html_template = read_lib('html', 'graph')
# Create div ID for the graph and give it to the JS and CSS templates so
# they can refere... | [
"def",
"create_graph_html",
"(",
"js_template",
",",
"css_template",
",",
"html_template",
"=",
"None",
")",
":",
"if",
"html_template",
"is",
"None",
":",
"html_template",
"=",
"read_lib",
"(",
"'html'",
",",
"'graph'",
")",
"# Create div ID for the graph and give ... | Create HTML code block given the graph Javascript and CSS. | [
"Create",
"HTML",
"code",
"block",
"given",
"the",
"graph",
"Javascript",
"and",
"CSS",
"."
] | python | train | 35.764706 |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L326-L372 | def configuration_check(config):
"""Perform a sanity check on configuration.
First it performs a sanity check against settings for daemon
and then against settings for each service check.
Arguments:
config (obj): A configparser object which holds our configuration.
Returns:
None i... | [
"def",
"configuration_check",
"(",
"config",
")",
":",
"log_level",
"=",
"config",
".",
"get",
"(",
"'daemon'",
",",
"'loglevel'",
")",
"num_level",
"=",
"getattr",
"(",
"logging",
",",
"log_level",
".",
"upper",
"(",
")",
",",
"None",
")",
"pidfile",
"=... | Perform a sanity check on configuration.
First it performs a sanity check against settings for daemon
and then against settings for each service check.
Arguments:
config (obj): A configparser object which holds our configuration.
Returns:
None if all checks are successfully passed oth... | [
"Perform",
"a",
"sanity",
"check",
"on",
"configuration",
"."
] | python | train | 35.638298 |
pdkit/pdkit | pdkit/tremor_time_series.py | https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/tremor_time_series.py#L31-L55 | def load(self, filename, format_file='cloudupdrs'):
"""
This is a general load data method where the format of data to load can be passed as a parameter,
:param str filename: The path to load data from
:param str format_file: format of the file. Default is CloudUPDRS. Set to... | [
"def",
"load",
"(",
"self",
",",
"filename",
",",
"format_file",
"=",
"'cloudupdrs'",
")",
":",
"try",
":",
"ts",
"=",
"load_data",
"(",
"filename",
",",
"format_file",
")",
"validator",
"=",
"CloudUPDRSDataFrameValidator",
"(",
")",
"if",
"validator",
".",
... | This is a general load data method where the format of data to load can be passed as a parameter,
:param str filename: The path to load data from
:param str format_file: format of the file. Default is CloudUPDRS. Set to mpower for mpower data.
:return dataframe: data_frame.x, data_f... | [
"This",
"is",
"a",
"general",
"load",
"data",
"method",
"where",
"the",
"format",
"of",
"data",
"to",
"load",
"can",
"be",
"passed",
"as",
"a",
"parameter"
] | python | train | 46.8 |
shexSpec/grammar | parsers/python/pyshexc/parser_impl/shex_doc_parser.py | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/shex_doc_parser.py#L55-L60 | def visitPrefixDecl(self, ctx: ShExDocParser.PrefixDeclContext):
""" prefixDecl: KW_PREFIX PNAME_NS IRIREF """
iri = self.context.iriref_to_shexj_iriref(ctx.IRIREF())
prefix = ctx.PNAME_NS().getText()
if iri not in self.context.ld_prefixes:
self.context.prefixes.setdefault(pr... | [
"def",
"visitPrefixDecl",
"(",
"self",
",",
"ctx",
":",
"ShExDocParser",
".",
"PrefixDeclContext",
")",
":",
"iri",
"=",
"self",
".",
"context",
".",
"iriref_to_shexj_iriref",
"(",
"ctx",
".",
"IRIREF",
"(",
")",
")",
"prefix",
"=",
"ctx",
".",
"PNAME_NS",... | prefixDecl: KW_PREFIX PNAME_NS IRIREF | [
"prefixDecl",
":",
"KW_PREFIX",
"PNAME_NS",
"IRIREF"
] | python | train | 54.833333 |
HiPERCAM/hcam_widgets | hcam_widgets/widgets.py | https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L757-L762 | def add(self, num):
"""
Adds num to the current value
"""
self.index = max(0, min(len(self.allowed)-1, self.index+num))
self.set(self.allowed[self.index]) | [
"def",
"add",
"(",
"self",
",",
"num",
")",
":",
"self",
".",
"index",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"len",
"(",
"self",
".",
"allowed",
")",
"-",
"1",
",",
"self",
".",
"index",
"+",
"num",
")",
")",
"self",
".",
"set",
"(",
"self... | Adds num to the current value | [
"Adds",
"num",
"to",
"the",
"current",
"value"
] | python | train | 31.5 |
saltstack/salt | salt/modules/consul.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L50-L113 | def _query(function,
consul_url,
token=None,
method='GET',
api_version='v1',
data=None,
query_params=None):
'''
Consul object method function to construct and execute on the API URL.
:param api_url: The Consul api url.
:param api_ver... | [
"def",
"_query",
"(",
"function",
",",
"consul_url",
",",
"token",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"api_version",
"=",
"'v1'",
",",
"data",
"=",
"None",
",",
"query_params",
"=",
"None",
")",
":",
"if",
"not",
"query_params",
":",
"query... | Consul object method function to construct and execute on the API URL.
:param api_url: The Consul api url.
:param api_version The Consul api version
:param function: The Consul api function to perform.
:param method: The HTTP method, e.g. GET or POST.
:param data: The data to be... | [
"Consul",
"object",
"method",
"function",
"to",
"construct",
"and",
"execute",
"on",
"the",
"API",
"URL",
"."
] | python | train | 28.234375 |
arviz-devs/arviz | arviz/plots/hpdplot.py | https://github.com/arviz-devs/arviz/blob/d04d8da07f029fd2931f48d2f7f324cf393e5277/arviz/plots/hpdplot.py#L10-L86 | def plot_hpd(
x,
y,
credible_interval=0.94,
color="C1",
circular=False,
smooth=True,
smooth_kwargs=None,
fill_kwargs=None,
plot_kwargs=None,
ax=None,
):
"""
Plot hpd intervals for regression data.
Parameters
----------
x : array-like
Values to plot
... | [
"def",
"plot_hpd",
"(",
"x",
",",
"y",
",",
"credible_interval",
"=",
"0.94",
",",
"color",
"=",
"\"C1\"",
",",
"circular",
"=",
"False",
",",
"smooth",
"=",
"True",
",",
"smooth_kwargs",
"=",
"None",
",",
"fill_kwargs",
"=",
"None",
",",
"plot_kwargs",
... | Plot hpd intervals for regression data.
Parameters
----------
x : array-like
Values to plot
y : array-like
values from which to compute the hpd
credible_interval : float, optional
Credible interval to plot. Defaults to 0.94.
color : str
Color used for the limit... | [
"Plot",
"hpd",
"intervals",
"for",
"regression",
"data",
"."
] | python | train | 30.194805 |
metachris/RPIO | source/RPIO/__init__.py | https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/__init__.py#L203-L220 | def add_interrupt_callback(gpio_id, callback, edge='both', \
pull_up_down=PUD_OFF, threaded_callback=False, \
debounce_timeout_ms=None):
"""
Add a callback to be executed when the value on 'gpio_id' changes to
the edge specified via the 'edge' parameter (default='both').
`pull_up_down` ... | [
"def",
"add_interrupt_callback",
"(",
"gpio_id",
",",
"callback",
",",
"edge",
"=",
"'both'",
",",
"pull_up_down",
"=",
"PUD_OFF",
",",
"threaded_callback",
"=",
"False",
",",
"debounce_timeout_ms",
"=",
"None",
")",
":",
"_rpio",
".",
"add_interrupt_callback",
... | Add a callback to be executed when the value on 'gpio_id' changes to
the edge specified via the 'edge' parameter (default='both').
`pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and
`RPIO.PUD_OFF`.
If `threaded_callback` is True, the callback will be started
inside a Thread.
If ... | [
"Add",
"a",
"callback",
"to",
"be",
"executed",
"when",
"the",
"value",
"on",
"gpio_id",
"changes",
"to",
"the",
"edge",
"specified",
"via",
"the",
"edge",
"parameter",
"(",
"default",
"=",
"both",
")",
"."
] | python | train | 40 |
spdx/tools-python | spdx/parsers/tagvalue.py | https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvalue.py#L1341-L1350 | def p_created_1(self, p):
"""created : CREATED DATE"""
try:
if six.PY2:
value = p[2].decode(encoding='utf-8')
else:
value = p[2]
self.builder.set_created_date(self.document, value)
except CardinalityError:
self.more_... | [
"def",
"p_created_1",
"(",
"self",
",",
"p",
")",
":",
"try",
":",
"if",
"six",
".",
"PY2",
":",
"value",
"=",
"p",
"[",
"2",
"]",
".",
"decode",
"(",
"encoding",
"=",
"'utf-8'",
")",
"else",
":",
"value",
"=",
"p",
"[",
"2",
"]",
"self",
"."... | created : CREATED DATE | [
"created",
":",
"CREATED",
"DATE"
] | python | valid | 34.9 |
gabrielfalcao/dominic | dominic/xpath/expr.py | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L17-L33 | def string_value(node):
"""Compute the string-value of a node."""
if (node.nodeType == node.DOCUMENT_NODE or
node.nodeType == node.ELEMENT_NODE):
s = u''
for n in axes['descendant'](node):
if n.nodeType == n.TEXT_NODE:
s += n.data
return s
elif no... | [
"def",
"string_value",
"(",
"node",
")",
":",
"if",
"(",
"node",
".",
"nodeType",
"==",
"node",
".",
"DOCUMENT_NODE",
"or",
"node",
".",
"nodeType",
"==",
"node",
".",
"ELEMENT_NODE",
")",
":",
"s",
"=",
"u''",
"for",
"n",
"in",
"axes",
"[",
"'descen... | Compute the string-value of a node. | [
"Compute",
"the",
"string",
"-",
"value",
"of",
"a",
"node",
"."
] | python | train | 32.117647 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/extensions_v1beta1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/extensions_v1beta1_api.py#L3759-L3787 | def list_replica_set_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_replica_set_for_all_namespaces # noqa: E501
list or watch objects of kind ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass a... | [
"def",
"list_replica_set_for_all_namespaces",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"list_re... | list_replica_set_for_all_namespaces # noqa: E501
list or watch objects of kind ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_replica_set_for_all_namespaces(async_r... | [
"list_replica_set_for_all_namespaces",
"#",
"noqa",
":",
"E501"
] | python | train | 165.034483 |
ECRL/ecabc | ecabc/abc.py | https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L452-L478 | def _merge_bee(self, bee):
'''Shifts a random value for a supplied bee with in accordance with
another random bee's value
Args:
bee (EmployerBee): supplied bee to merge
Returns:
tuple: (score of new position, values of new position, fitness
funct... | [
"def",
"_merge_bee",
"(",
"self",
",",
"bee",
")",
":",
"random_dimension",
"=",
"randint",
"(",
"0",
",",
"len",
"(",
"self",
".",
"_value_ranges",
")",
"-",
"1",
")",
"second_bee",
"=",
"randint",
"(",
"0",
",",
"self",
".",
"_num_employers",
"-",
... | Shifts a random value for a supplied bee with in accordance with
another random bee's value
Args:
bee (EmployerBee): supplied bee to merge
Returns:
tuple: (score of new position, values of new position, fitness
function return value of new position) | [
"Shifts",
"a",
"random",
"value",
"for",
"a",
"supplied",
"bee",
"with",
"in",
"accordance",
"with",
"another",
"random",
"bee",
"s",
"value"
] | python | train | 39 |
IdentityPython/oidcendpoint | src/oidcendpoint/sso_db.py | https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/sso_db.py#L62-L70 | def map_sid2sub(self, sid, sub):
"""
Store the connection between a Session ID and a subject ID.
:param sid: Session ID
:param sub: subject ID
"""
self.set('sid2sub', sid, sub)
self.set('sub2sid', sub, sid) | [
"def",
"map_sid2sub",
"(",
"self",
",",
"sid",
",",
"sub",
")",
":",
"self",
".",
"set",
"(",
"'sid2sub'",
",",
"sid",
",",
"sub",
")",
"self",
".",
"set",
"(",
"'sub2sid'",
",",
"sub",
",",
"sid",
")"
] | Store the connection between a Session ID and a subject ID.
:param sid: Session ID
:param sub: subject ID | [
"Store",
"the",
"connection",
"between",
"a",
"Session",
"ID",
"and",
"a",
"subject",
"ID",
"."
] | python | train | 28.333333 |
manns/pyspread | pyspread/src/lib/_grid_cairo_renderer.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/_grid_cairo_renderer.py#L865-L911 | def draw(self):
"""Draws cell content to context"""
# Content is only rendered within rect
self.context.save()
self.context.rectangle(*self.rect)
self.context.clip()
content = self.get_cell_content()
pos_x, pos_y = self.rect[:2]
self.context.translate(p... | [
"def",
"draw",
"(",
"self",
")",
":",
"# Content is only rendered within rect",
"self",
".",
"context",
".",
"save",
"(",
")",
"self",
".",
"context",
".",
"rectangle",
"(",
"*",
"self",
".",
"rect",
")",
"self",
".",
"context",
".",
"clip",
"(",
")",
... | Draws cell content to context | [
"Draws",
"cell",
"content",
"to",
"context"
] | python | train | 34.553191 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/mavproxy.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/mavproxy.py#L108-L112 | def write(self):
'''write status to status.txt'''
f = open('status.txt', mode='w')
self.show(f)
f.close() | [
"def",
"write",
"(",
"self",
")",
":",
"f",
"=",
"open",
"(",
"'status.txt'",
",",
"mode",
"=",
"'w'",
")",
"self",
".",
"show",
"(",
"f",
")",
"f",
".",
"close",
"(",
")"
] | write status to status.txt | [
"write",
"status",
"to",
"status",
".",
"txt"
] | python | train | 26.6 |
sdss/sdss_access | python/sdss_access/misc/docupaths.py | https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/misc/docupaths.py#L34-L64 | def _format_templates(name, command, templates):
''' Creates a list-table directive
for a set of defined environment variables
Parameters:
name (str):
The name of the config section
command (object):
The sdss_access path instance
templates (dict):
... | [
"def",
"_format_templates",
"(",
"name",
",",
"command",
",",
"templates",
")",
":",
"yield",
"'.. list-table:: {0}'",
".",
"format",
"(",
"name",
")",
"yield",
"_indent",
"(",
"':widths: 20 50 70'",
")",
"yield",
"_indent",
"(",
"':header-rows: 1'",
")",
"yield... | Creates a list-table directive
for a set of defined environment variables
Parameters:
name (str):
The name of the config section
command (object):
The sdss_access path instance
templates (dict):
A dictionary of the path templates
Yields:
... | [
"Creates",
"a",
"list",
"-",
"table",
"directive"
] | python | train | 28.16129 |
aldur/cryptonator | cryptonator.py | https://github.com/aldur/cryptonator/blob/4e98bc7ddb19f9da2388e241ea90c89798718dd6/cryptonator.py#L43-L67 | def get_exchange_rate(self, base, target, raise_errors=True):
"""Return the ::base:: to ::target:: exchange rate."""
assert base and target
base, target = base.lower(), target.lower()
r = self.session.get(API_SIMPLE_TICKER.format(base, target))
if r.status_code != requests.code... | [
"def",
"get_exchange_rate",
"(",
"self",
",",
"base",
",",
"target",
",",
"raise_errors",
"=",
"True",
")",
":",
"assert",
"base",
"and",
"target",
"base",
",",
"target",
"=",
"base",
".",
"lower",
"(",
")",
",",
"target",
".",
"lower",
"(",
")",
"r"... | Return the ::base:: to ::target:: exchange rate. | [
"Return",
"the",
"::",
"base",
"::",
"to",
"::",
"target",
"::",
"exchange",
"rate",
"."
] | python | train | 37.04 |
DataBiosphere/toil | src/toil/leader.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/leader.py#L689-L696 | def killJobs(self, jobsToKill):
"""
Kills the given set of jobs and then sends them for processing
"""
if len(jobsToKill) > 0:
self.batchSystem.killBatchJobs(jobsToKill)
for jobBatchSystemID in jobsToKill:
self.processFinishedJob(jobBatchSystemID, ... | [
"def",
"killJobs",
"(",
"self",
",",
"jobsToKill",
")",
":",
"if",
"len",
"(",
"jobsToKill",
")",
">",
"0",
":",
"self",
".",
"batchSystem",
".",
"killBatchJobs",
"(",
"jobsToKill",
")",
"for",
"jobBatchSystemID",
"in",
"jobsToKill",
":",
"self",
".",
"p... | Kills the given set of jobs and then sends them for processing | [
"Kills",
"the",
"given",
"set",
"of",
"jobs",
"and",
"then",
"sends",
"them",
"for",
"processing"
] | python | train | 39.375 |
welbornprod/colr | colr/colr.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr.py#L1065-L1108 | def _iter_text_wave(
self, text, numbers, step=1,
fore=None, back=None, style=None, rgb_mode=False):
""" Yield colorized characters from `text`, using a wave of `numbers`.
Arguments:
text : String to be colorized.
numbers : A list/tuple ... | [
"def",
"_iter_text_wave",
"(",
"self",
",",
"text",
",",
"numbers",
",",
"step",
"=",
"1",
",",
"fore",
"=",
"None",
",",
"back",
"=",
"None",
",",
"style",
"=",
"None",
",",
"rgb_mode",
"=",
"False",
")",
":",
"if",
"fore",
"and",
"back",
":",
"... | Yield colorized characters from `text`, using a wave of `numbers`.
Arguments:
text : String to be colorized.
numbers : A list/tuple of numbers (256 colors).
step : Number of characters to colorize per color.
fore : Fore color t... | [
"Yield",
"colorized",
"characters",
"from",
"text",
"using",
"a",
"wave",
"of",
"numbers",
".",
"Arguments",
":",
"text",
":",
"String",
"to",
"be",
"colorized",
".",
"numbers",
":",
"A",
"list",
"/",
"tuple",
"of",
"numbers",
"(",
"256",
"colors",
")",
... | python | train | 37.886364 |
twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/event.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/event.py#L137-L189 | def page(self, end_date=values.unset, event_type=values.unset,
minutes=values.unset, reservation_sid=values.unset,
start_date=values.unset, task_queue_sid=values.unset,
task_sid=values.unset, worker_sid=values.unset,
workflow_sid=values.unset, task_channel=values.unse... | [
"def",
"page",
"(",
"self",
",",
"end_date",
"=",
"values",
".",
"unset",
",",
"event_type",
"=",
"values",
".",
"unset",
",",
"minutes",
"=",
"values",
".",
"unset",
",",
"reservation_sid",
"=",
"values",
".",
"unset",
",",
"start_date",
"=",
"values",
... | Retrieve a single page of EventInstance records from the API.
Request is executed immediately
:param datetime end_date: Filter events by an end date.
:param unicode event_type: Filter events by those of a certain event type
:param unicode minutes: Filter events by up to 'x' minutes in t... | [
"Retrieve",
"a",
"single",
"page",
"of",
"EventInstance",
"records",
"from",
"the",
"API",
".",
"Request",
"is",
"executed",
"immediately"
] | python | train | 48.962264 |
inspirehep/refextract | refextract/references/engine.py | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L639-L716 | def parse_reference_line(ref_line, kbs, bad_titles_count={}, linker_callback=None):
"""Parse one reference line
@input a string representing a single reference bullet
@output parsed references (a list of elements objects)
"""
# Strip the 'marker' (e.g. [1]) from this reference line:
line_marker... | [
"def",
"parse_reference_line",
"(",
"ref_line",
",",
"kbs",
",",
"bad_titles_count",
"=",
"{",
"}",
",",
"linker_callback",
"=",
"None",
")",
":",
"# Strip the 'marker' (e.g. [1]) from this reference line:",
"line_marker",
",",
"ref_line",
"=",
"remove_reference_line_mark... | Parse one reference line
@input a string representing a single reference bullet
@output parsed references (a list of elements objects) | [
"Parse",
"one",
"reference",
"line"
] | python | train | 39.615385 |
saltstack/salt | salt/modules/azurearm_network.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L447-L480 | def security_rule_get(security_rule, security_group, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get a security rule within a specified network security group.
:param name: The name of the security rule to query.
:param security_group: The network security group containing the
... | [
"def",
"security_rule_get",
"(",
"security_rule",
",",
"security_group",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"se... | .. versionadded:: 2019.2.0
Get a security rule within a specified network security group.
:param name: The name of the security rule to query.
:param security_group: The network security group containing the
security rule.
:param resource_group: The resource group name assigned to the
... | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | python | train | 29.970588 |
hagenw/sphinxcontrib-katex | sphinxcontrib/katex.py | https://github.com/hagenw/sphinxcontrib-katex/blob/52e235b93a2471df9a7477e04b697e4274399623/sphinxcontrib/katex.py#L159-L177 | def katex_rendering_delimiters(app):
"""Delimiters for rendering KaTeX math.
If no delimiters are specified in katex_options, add the
katex_inline and katex_display delimiters. See also
https://khan.github.io/KaTeX/docs/autorender.html
"""
# Return if we have user defined rendering delimiters
... | [
"def",
"katex_rendering_delimiters",
"(",
"app",
")",
":",
"# Return if we have user defined rendering delimiters",
"if",
"'delimiters'",
"in",
"app",
".",
"config",
".",
"katex_options",
":",
"return",
"''",
"katex_inline",
"=",
"[",
"d",
".",
"replace",
"(",
"'\\\... | Delimiters for rendering KaTeX math.
If no delimiters are specified in katex_options, add the
katex_inline and katex_display delimiters. See also
https://khan.github.io/KaTeX/docs/autorender.html | [
"Delimiters",
"for",
"rendering",
"KaTeX",
"math",
"."
] | python | train | 47.894737 |
log2timeline/plaso | plaso/storage/sqlite/sqlite_file.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/sqlite/sqlite_file.py#L1074-L1090 | def ReadPreprocessingInformation(self, knowledge_base):
"""Reads preprocessing information.
The preprocessing information contains the system configuration which
contains information about various system specific configuration data,
for example the user accounts.
Args:
knowledge_base (Knowle... | [
"def",
"ReadPreprocessingInformation",
"(",
"self",
",",
"knowledge_base",
")",
":",
"generator",
"=",
"self",
".",
"_GetAttributeContainers",
"(",
"self",
".",
"_CONTAINER_TYPE_SYSTEM_CONFIGURATION",
")",
"for",
"stream_number",
",",
"system_configuration",
"in",
"enum... | Reads preprocessing information.
The preprocessing information contains the system configuration which
contains information about various system specific configuration data,
for example the user accounts.
Args:
knowledge_base (KnowledgeBase): is used to store the preprocessing
informat... | [
"Reads",
"preprocessing",
"information",
"."
] | python | train | 42.588235 |
joshspeagle/dynesty | dynesty/bounding.py | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L431-L484 | def sample(self, rstate=None, return_q=False):
"""
Sample a point uniformly distributed within the *union* of ellipsoids.
Returns
-------
x : `~numpy.ndarray` with shape (ndim,)
A coordinate within the set of ellipsoids.
idx : int
The index of th... | [
"def",
"sample",
"(",
"self",
",",
"rstate",
"=",
"None",
",",
"return_q",
"=",
"False",
")",
":",
"if",
"rstate",
"is",
"None",
":",
"rstate",
"=",
"np",
".",
"random",
"# If there is only one ellipsoid, sample from it.",
"if",
"self",
".",
"nells",
"==",
... | Sample a point uniformly distributed within the *union* of ellipsoids.
Returns
-------
x : `~numpy.ndarray` with shape (ndim,)
A coordinate within the set of ellipsoids.
idx : int
The index of the ellipsoid `x` was sampled from.
q : int, optional
... | [
"Sample",
"a",
"point",
"uniformly",
"distributed",
"within",
"the",
"*",
"union",
"*",
"of",
"ellipsoids",
"."
] | python | train | 32.388889 |
agile4you/bottle-neck | bottle_neck/routing.py | https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/routing.py#L130-L142 | def mount(self, app=None):
"""Mounts all registered routes to a bottle.py application instance.
Args:
app (instance): A `bottle.Bottle()` application instance.
Returns:
The Router instance (for chaining purposes).
"""
for endpoint in self._routes:
... | [
"def",
"mount",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"for",
"endpoint",
"in",
"self",
".",
"_routes",
":",
"endpoint",
".",
"register_app",
"(",
"app",
")",
"return",
"self"
] | Mounts all registered routes to a bottle.py application instance.
Args:
app (instance): A `bottle.Bottle()` application instance.
Returns:
The Router instance (for chaining purposes). | [
"Mounts",
"all",
"registered",
"routes",
"to",
"a",
"bottle",
".",
"py",
"application",
"instance",
"."
] | python | train | 27.769231 |
hactar-is/frink | frink/orm.py | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L33-L90 | def save(self):
"""
Save the current instance to the DB
"""
with rconnect() as conn:
try:
self.validate()
except ValidationError as e:
log.warn(e.messages)
raise
except ModelValidationError as e:
... | [
"def",
"save",
"(",
"self",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"try",
":",
"self",
".",
"validate",
"(",
")",
"except",
"ValidationError",
"as",
"e",
":",
"log",
".",
"warn",
"(",
"e",
".",
"messages",
")",
"raise",
"except"... | Save the current instance to the DB | [
"Save",
"the",
"current",
"instance",
"to",
"the",
"DB"
] | python | train | 34.568966 |
rmed/pyemtmad | pyemtmad/api/geo.py | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L39-L65 | def get_arrive_stop(self, **kwargs):
"""Obtain bus arrival info in target stop.
Args:
stop_number (int): Stop number to query.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Arrival]), or message string
... | [
"def",
"get_arrive_stop",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"params",
"=",
"{",
"'idStop'",
":",
"kwargs",
".",
"get",
"(",
"'stop_number'",
")",
",",
"'cultureInfo'",
":",
"util",
".",
"language_code",
"(",
"kwargs",
... | Obtain bus arrival info in target stop.
Args:
stop_number (int): Stop number to query.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Arrival]), or message string
in case of error. | [
"Obtain",
"bus",
"arrival",
"info",
"in",
"target",
"stop",
"."
] | python | train | 31.740741 |
Kronuz/pyScss | scss/compiler.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/compiler.py#L913-L952 | def _at_for(self, calculator, rule, scope, block):
"""
Implements @for
"""
var, _, name = block.argument.partition(' from ')
frm, _, through = name.partition(' through ')
if through:
inclusive = True
else:
inclusive = False
frm,... | [
"def",
"_at_for",
"(",
"self",
",",
"calculator",
",",
"rule",
",",
"scope",
",",
"block",
")",
":",
"var",
",",
"_",
",",
"name",
"=",
"block",
".",
"argument",
".",
"partition",
"(",
"' from '",
")",
"frm",
",",
"_",
",",
"through",
"=",
"name",
... | Implements @for | [
"Implements"
] | python | train | 33.75 |
bids-standard/pybids | bids/analysis/hrf.py | https://github.com/bids-standard/pybids/blob/30d924ce770622bda0e390d613a8da42a2a20c32/bids/analysis/hrf.py#L144-L166 | def glover_time_derivative(tr, oversampling=50, time_length=32., onset=0.):
"""Implementation of the Glover time derivative hrf (dhrf) model
Parameters
----------
tr: float
scan repeat time, in seconds
oversampling: int,
temporal oversampling factor, optional
time_length: float,... | [
"def",
"glover_time_derivative",
"(",
"tr",
",",
"oversampling",
"=",
"50",
",",
"time_length",
"=",
"32.",
",",
"onset",
"=",
"0.",
")",
":",
"do",
"=",
".1",
"dhrf",
"=",
"1.",
"/",
"do",
"*",
"(",
"glover_hrf",
"(",
"tr",
",",
"oversampling",
",",... | Implementation of the Glover time derivative hrf (dhrf) model
Parameters
----------
tr: float
scan repeat time, in seconds
oversampling: int,
temporal oversampling factor, optional
time_length: float,
hrf kernel length, in seconds
onset: float,
onset of the respo... | [
"Implementation",
"of",
"the",
"Glover",
"time",
"derivative",
"hrf",
"(",
"dhrf",
")",
"model"
] | python | train | 30.043478 |
pyscaffold/configupdater | src/configupdater/configupdater.py | https://github.com/pyscaffold/configupdater/blob/6ebac0b1fa7b8222baacdd4991d18cfc61659f84/src/configupdater/configupdater.py#L176-L190 | def space(self, newlines=1):
"""Creates a vertical space of newlines
Args:
newlines (int): number of empty lines
Returns:
self for chaining
"""
space = Space()
for line in range(newlines):
space.add_line('\n')
self._container.... | [
"def",
"space",
"(",
"self",
",",
"newlines",
"=",
"1",
")",
":",
"space",
"=",
"Space",
"(",
")",
"for",
"line",
"in",
"range",
"(",
"newlines",
")",
":",
"space",
".",
"add_line",
"(",
"'\\n'",
")",
"self",
".",
"_container",
".",
"structure",
".... | Creates a vertical space of newlines
Args:
newlines (int): number of empty lines
Returns:
self for chaining | [
"Creates",
"a",
"vertical",
"space",
"of",
"newlines"
] | python | train | 25.533333 |
jwhitlock/drf-cached-instances | drf_cached_instances/cache.py | https://github.com/jwhitlock/drf-cached-instances/blob/ec4e8a6e1e83eeea6ec0b924b2eaa40a38d5963a/drf_cached_instances/cache.py#L86-L157 | def get_instances(self, object_specs, version=None):
"""Get the cached native representation for one or more objects.
Keyword arguments:
object_specs - A sequence of triples (model name, pk, obj):
- model name - the name of the model
- pk - the primary key of the instance
... | [
"def",
"get_instances",
"(",
"self",
",",
"object_specs",
",",
"version",
"=",
"None",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"spec_keys",
"=",
"set",
"(",
")",
"cache_keys",
"=",
"[",
"]",
"version",
"=",
"version",
"or",
"self",
".",
"default_versio... | Get the cached native representation for one or more objects.
Keyword arguments:
object_specs - A sequence of triples (model name, pk, obj):
- model name - the name of the model
- pk - the primary key of the instance
- obj - the instance, or None to load it
version - The... | [
"Get",
"the",
"cached",
"native",
"representation",
"for",
"one",
"or",
"more",
"objects",
"."
] | python | train | 35.791667 |
angr/angr | angr/analyses/cfg/cfg_base.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_base.py#L1185-L1320 | def make_functions(self):
"""
Revisit the entire control flow graph, create Function instances accordingly, and correctly put blocks into
each function.
Although Function objects are crated during the CFG recovery, they are neither sound nor accurate. With a
pre-constructed CFG,... | [
"def",
"make_functions",
"(",
"self",
")",
":",
"# TODO: Is it required that PLT stubs are always aligned by 16? If so, on what architectures and platforms is it",
"# TODO: enforced?",
"tmp_functions",
"=",
"self",
".",
"kb",
".",
"functions",
".",
"copy",
"(",
")",
"for",
"... | Revisit the entire control flow graph, create Function instances accordingly, and correctly put blocks into
each function.
Although Function objects are crated during the CFG recovery, they are neither sound nor accurate. With a
pre-constructed CFG, this method rebuilds all functions bearing th... | [
"Revisit",
"the",
"entire",
"control",
"flow",
"graph",
"create",
"Function",
"instances",
"accordingly",
"and",
"correctly",
"put",
"blocks",
"into",
"each",
"function",
"."
] | python | train | 45.294118 |
Opentrons/opentrons | api/src/opentrons/config/__init__.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/__init__.py#L176-L190 | def load_and_migrate() -> Dict[str, Path]:
""" Ensure the settings directory tree is properly configured.
This function does most of its work on the actual robot. It will move
all settings files from wherever they happen to be to the proper
place. On non-robots, this mostly just loads. In addition, it ... | [
"def",
"load_and_migrate",
"(",
")",
"->",
"Dict",
"[",
"str",
",",
"Path",
"]",
":",
"if",
"IS_ROBOT",
":",
"_migrate_robot",
"(",
")",
"base",
"=",
"infer_config_base_dir",
"(",
")",
"base",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
... | Ensure the settings directory tree is properly configured.
This function does most of its work on the actual robot. It will move
all settings files from wherever they happen to be to the proper
place. On non-robots, this mostly just loads. In addition, it writes
a default config and makes sure all dire... | [
"Ensure",
"the",
"settings",
"directory",
"tree",
"is",
"properly",
"configured",
"."
] | python | train | 41.933333 |
jobovy/galpy | galpy/orbit/Orbit.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/Orbit.py#L2287-L2319 | def ra(self,*args,**kwargs):
"""
NAME:
ra
PURPOSE:
return the right ascension
INPUT:
t - (optional) time at which to get ra (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity)
(def... | [
"def",
"ra",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"self",
".",
"_orb",
".",
"ra",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"out",
")",
"==",
"1",
":",
"return",
"out",
"[",
... | NAME:
ra
PURPOSE:
return the right ascension
INPUT:
t - (optional) time at which to get ra (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity)
(default=[8.0,0.,0.]) OR Orbit object that correspond... | [
"NAME",
":"
] | python | train | 24.151515 |
peri-source/peri | peri/opt/optimize.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1469-L1472 | def update_function(self, param_vals):
"""Updates the opt_obj, returns new error."""
self.opt_obj.update_function(param_vals)
return self.opt_obj.get_error() | [
"def",
"update_function",
"(",
"self",
",",
"param_vals",
")",
":",
"self",
".",
"opt_obj",
".",
"update_function",
"(",
"param_vals",
")",
"return",
"self",
".",
"opt_obj",
".",
"get_error",
"(",
")"
] | Updates the opt_obj, returns new error. | [
"Updates",
"the",
"opt_obj",
"returns",
"new",
"error",
"."
] | python | valid | 44.5 |
angr/angr | angr/analyses/cfg/cfg_emulated.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_emulated.py#L975-L1016 | def _get_one_pending_job(self):
"""
Retrieve a pending job.
:return: A CFGJob instance or None
"""
pending_job_key, pending_job = self._pending_jobs.popitem()
pending_job_state = pending_job.state
pending_job_call_stack = pending_job.call_stack
pending_j... | [
"def",
"_get_one_pending_job",
"(",
"self",
")",
":",
"pending_job_key",
",",
"pending_job",
"=",
"self",
".",
"_pending_jobs",
".",
"popitem",
"(",
")",
"pending_job_state",
"=",
"pending_job",
".",
"state",
"pending_job_call_stack",
"=",
"pending_job",
".",
"cal... | Retrieve a pending job.
:return: A CFGJob instance or None | [
"Retrieve",
"a",
"pending",
"job",
"."
] | python | train | 43.119048 |
Workiva/furious | furious/async.py | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L497-L512 | def _increment_recursion_level(self):
"""Increment current_depth based on either defaults or the enclosing
Async.
"""
# Update the recursion info. This is done so that if an async created
# outside an executing context, or one previously created is later
# loaded from st... | [
"def",
"_increment_recursion_level",
"(",
"self",
")",
":",
"# Update the recursion info. This is done so that if an async created",
"# outside an executing context, or one previously created is later",
"# loaded from storage, that the \"current\" setting is correctly set.",
"self",
".",
"_in... | Increment current_depth based on either defaults or the enclosing
Async. | [
"Increment",
"current_depth",
"based",
"on",
"either",
"defaults",
"or",
"the",
"enclosing",
"Async",
"."
] | python | train | 46.5 |
pneff/wsgiservice | wsgiservice/status.py | https://github.com/pneff/wsgiservice/blob/03c064ac2e8c53a1aac9c7b99970f23cf79e20f4/wsgiservice/status.py#L49-L60 | def raise_204(instance):
"""Abort the current request with a 204 (No Content) response code. Clears
out the body of the response.
:param instance: Resource instance (used to access the response)
:type instance: :class:`webob.resource.Resource`
:raises: :class:`webob.exceptions.ResponseException` of... | [
"def",
"raise_204",
"(",
"instance",
")",
":",
"instance",
".",
"response",
".",
"status",
"=",
"204",
"instance",
".",
"response",
".",
"body",
"=",
"''",
"instance",
".",
"response",
".",
"body_raw",
"=",
"None",
"raise",
"ResponseException",
"(",
"insta... | Abort the current request with a 204 (No Content) response code. Clears
out the body of the response.
:param instance: Resource instance (used to access the response)
:type instance: :class:`webob.resource.Resource`
:raises: :class:`webob.exceptions.ResponseException` of status 204 | [
"Abort",
"the",
"current",
"request",
"with",
"a",
"204",
"(",
"No",
"Content",
")",
"response",
"code",
".",
"Clears",
"out",
"the",
"body",
"of",
"the",
"response",
"."
] | python | train | 40 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.