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 |
|---|---|---|---|---|---|---|---|---|---|
trombastic/PyScada | pyscada/systemstat/device.py | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/systemstat/device.py#L25-L191 | def request_data(self):
"""
(0,'cpu_percent'),
(1,'virtual_memory_total'),
(2,'virtual_memory_available'),
(3,'virtual_memory_percent'),
(4,'virtual_memory_used'),
(5,'virtual_memory_free'),
(6,'virtual_memory_active'),
(7,'virtual_memory_inactive'... | [
"def",
"request_data",
"(",
"self",
")",
":",
"if",
"not",
"driver_ok",
":",
"return",
"None",
"output",
"=",
"[",
"]",
"apcupsd_status_is_queried",
"=",
"False",
"for",
"item",
"in",
"self",
".",
"variables",
":",
"timestamp",
"=",
"time",
"(",
")",
"va... | (0,'cpu_percent'),
(1,'virtual_memory_total'),
(2,'virtual_memory_available'),
(3,'virtual_memory_percent'),
(4,'virtual_memory_used'),
(5,'virtual_memory_free'),
(6,'virtual_memory_active'),
(7,'virtual_memory_inactive'),
(8,'virtual_memory_buffers'),
... | [
"(",
"0",
"cpu_percent",
")",
"(",
"1",
"virtual_memory_total",
")",
"(",
"2",
"virtual_memory_available",
")",
"(",
"3",
"virtual_memory_percent",
")",
"(",
"4",
"virtual_memory_used",
")",
"(",
"5",
"virtual_memory_free",
")",
"(",
"6",
"virtual_memory_active",
... | python | train | 45.131737 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py#L145-L200 | def set_option(self, name, value):
"""
Sets an option from an SConscript file.
"""
if not name in self.settable:
raise SCons.Errors.UserError("This option is not settable from a SConscript file: %s"%name)
if name == 'num_jobs':
try:
value ... | [
"def",
"set_option",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"name",
"in",
"self",
".",
"settable",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"\"This option is not settable from a SConscript file: %s\"",
"%",
"name",
"... | Sets an option from an SConscript file. | [
"Sets",
"an",
"option",
"from",
"an",
"SConscript",
"file",
"."
] | python | train | 43.178571 |
NLeSC/noodles | noodles/run/runners.py | https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/runners.py#L58-L79 | def run_parallel_with_display(wf, n_threads, display):
"""Adds a display to the parallel runner. Because messages come in
asynchronously now, we start an extra thread just for the display
routine."""
LogQ = Queue()
S = Scheduler(error_handler=display.error_handler)
threading.Thread(
ta... | [
"def",
"run_parallel_with_display",
"(",
"wf",
",",
"n_threads",
",",
"display",
")",
":",
"LogQ",
"=",
"Queue",
"(",
")",
"S",
"=",
"Scheduler",
"(",
"error_handler",
"=",
"display",
".",
"error_handler",
")",
"threading",
".",
"Thread",
"(",
"target",
"=... | Adds a display to the parallel runner. Because messages come in
asynchronously now, we start an extra thread just for the display
routine. | [
"Adds",
"a",
"display",
"to",
"the",
"parallel",
"runner",
".",
"Because",
"messages",
"come",
"in",
"asynchronously",
"now",
"we",
"start",
"an",
"extra",
"thread",
"just",
"for",
"the",
"display",
"routine",
"."
] | python | train | 27.772727 |
tensorflow/tensor2tensor | tensor2tensor/models/video/basic_stochastic.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_stochastic.py#L255-L282 | def next_frame_basic_stochastic_discrete():
"""Basic 2-frame conv model with stochastic discrete latent."""
hparams = basic_deterministic_params.next_frame_sampling()
hparams.batch_size = 4
hparams.video_num_target_frames = 6
hparams.scheduled_sampling_mode = "prob_inverse_lin"
hparams.scheduled_sampling_de... | [
"def",
"next_frame_basic_stochastic_discrete",
"(",
")",
":",
"hparams",
"=",
"basic_deterministic_params",
".",
"next_frame_sampling",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"4",
"hparams",
".",
"video_num_target_frames",
"=",
"6",
"hparams",
".",
"scheduled_sa... | Basic 2-frame conv model with stochastic discrete latent. | [
"Basic",
"2",
"-",
"frame",
"conv",
"model",
"with",
"stochastic",
"discrete",
"latent",
"."
] | python | train | 44.785714 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/classbuilder.py | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L96-L117 | def from_json(cls, jsonmsg):
""" Create an object directly from a JSON string.
Applies general validation after creating the
object to check whether all required fields are
present.
Args:
jsonmsg (str): An object encoded as a JSON string
Returns:
... | [
"def",
"from_json",
"(",
"cls",
",",
"jsonmsg",
")",
":",
"import",
"json",
"msg",
"=",
"json",
".",
"loads",
"(",
"jsonmsg",
")",
"obj",
"=",
"cls",
"(",
"*",
"*",
"msg",
")",
"obj",
".",
"validate",
"(",
")",
"return",
"obj"
] | Create an object directly from a JSON string.
Applies general validation after creating the
object to check whether all required fields are
present.
Args:
jsonmsg (str): An object encoded as a JSON string
Returns:
An object of the generated type
... | [
"Create",
"an",
"object",
"directly",
"from",
"a",
"JSON",
"string",
"."
] | python | train | 26.863636 |
LonamiWebs/Telethon | telethon_generator/docswriter.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/docswriter.py#L107-L116 | def write_title(self, title, level=1, id=None):
"""Writes a title header in the document body,
with an optional depth level
"""
if id:
self.write('<h{lv} id="{id}">{title}</h{lv}>',
title=title, lv=level, id=id)
else:
self.write('... | [
"def",
"write_title",
"(",
"self",
",",
"title",
",",
"level",
"=",
"1",
",",
"id",
"=",
"None",
")",
":",
"if",
"id",
":",
"self",
".",
"write",
"(",
"'<h{lv} id=\"{id}\">{title}</h{lv}>'",
",",
"title",
"=",
"title",
",",
"lv",
"=",
"level",
",",
"... | Writes a title header in the document body,
with an optional depth level | [
"Writes",
"a",
"title",
"header",
"in",
"the",
"document",
"body",
"with",
"an",
"optional",
"depth",
"level"
] | python | train | 38.1 |
joke2k/django-environ | environ/environ.py | https://github.com/joke2k/django-environ/blob/c2620021614557abe197578f99deeef42af3e082/environ/environ.py#L151-L155 | def bool(self, var, default=NOTSET):
"""
:rtype: bool
"""
return self.get_value(var, cast=bool, default=default) | [
"def",
"bool",
"(",
"self",
",",
"var",
",",
"default",
"=",
"NOTSET",
")",
":",
"return",
"self",
".",
"get_value",
"(",
"var",
",",
"cast",
"=",
"bool",
",",
"default",
"=",
"default",
")"
] | :rtype: bool | [
":",
"rtype",
":",
"bool"
] | python | train | 28 |
SiLab-Bonn/pyBAR | pybar/analysis/analysis_utils.py | https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/analysis/analysis_utils.py#L361-L404 | def get_parameter_value_from_file_names(files, parameters=None, unique=False, sort=True):
"""
Takes a list of files, searches for the parameter name in the file name and returns a ordered dict with the file name
in the first dimension and the corresponding parameter value in the second.
The file names c... | [
"def",
"get_parameter_value_from_file_names",
"(",
"files",
",",
"parameters",
"=",
"None",
",",
"unique",
"=",
"False",
",",
"sort",
"=",
"True",
")",
":",
"# unique=False",
"logging",
".",
"debug",
"(",
"'Get the parameter: '",
"+",
"str",
"(",
"parameters... | Takes a list of files, searches for the parameter name in the file name and returns a ordered dict with the file name
in the first dimension and the corresponding parameter value in the second.
The file names can be sorted by the parameter value, otherwise the order is kept. If unique is true every parameter is... | [
"Takes",
"a",
"list",
"of",
"files",
"searches",
"for",
"the",
"parameter",
"name",
"in",
"the",
"file",
"name",
"and",
"returns",
"a",
"ordered",
"dict",
"with",
"the",
"file",
"name",
"in",
"the",
"first",
"dimension",
"and",
"the",
"corresponding",
"par... | python | train | 45.136364 |
mjirik/io3d | io3d/datasets.py | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L241-L260 | def get_dataset_meta(label):
"""Gives you metadata for dataset chosen via 'label' param
:param label: label = key in data_url dict (that big dict containing all possible datasets)
:return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir)
relative_download_dir says where will be do... | [
"def",
"get_dataset_meta",
"(",
"label",
")",
":",
"data_url",
"=",
"data_urls",
"[",
"label",
"]",
"if",
"type",
"(",
"data_url",
")",
"==",
"str",
":",
"# back compatibility",
"data_url",
"=",
"[",
"data_url",
"]",
"if",
"type",
"(",
"data_url",
")",
"... | Gives you metadata for dataset chosen via 'label' param
:param label: label = key in data_url dict (that big dict containing all possible datasets)
:return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir)
relative_download_dir says where will be downloaded the file from url and event... | [
"Gives",
"you",
"metadata",
"for",
"dataset",
"chosen",
"via",
"label",
"param"
] | python | train | 41.75 |
goshuirc/irc | girc/formatting.py | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/formatting.py#L117-L141 | def escape(msg):
"""Takes a raw IRC message and returns a girc-escaped message."""
msg = msg.replace(escape_character, 'girc-escaped-character')
for escape_key, irc_char in format_dict.items():
msg = msg.replace(irc_char, escape_character + escape_key)
# convert colour codes
new_msg = ''
... | [
"def",
"escape",
"(",
"msg",
")",
":",
"msg",
"=",
"msg",
".",
"replace",
"(",
"escape_character",
",",
"'girc-escaped-character'",
")",
"for",
"escape_key",
",",
"irc_char",
"in",
"format_dict",
".",
"items",
"(",
")",
":",
"msg",
"=",
"msg",
".",
"repl... | Takes a raw IRC message and returns a girc-escaped message. | [
"Takes",
"a",
"raw",
"IRC",
"message",
"and",
"returns",
"a",
"girc",
"-",
"escaped",
"message",
"."
] | python | train | 31 |
qubole/qds-sdk-py | qds_sdk/clusterv2.py | https://github.com/qubole/qds-sdk-py/blob/77210fb64e5a7d567aedeea3b742a1d872fd0e5e/qds_sdk/clusterv2.py#L730-L736 | def clone(cls, cluster_id_label, cluster_info):
"""
Update the cluster with id/label `cluster_id_label` using information provided in
`cluster_info`.
"""
conn = Qubole.agent(version="v2")
return conn.post(cls.element_path(cluster_id_label) + '/clone', data=cluster_info) | [
"def",
"clone",
"(",
"cls",
",",
"cluster_id_label",
",",
"cluster_info",
")",
":",
"conn",
"=",
"Qubole",
".",
"agent",
"(",
"version",
"=",
"\"v2\"",
")",
"return",
"conn",
".",
"post",
"(",
"cls",
".",
"element_path",
"(",
"cluster_id_label",
")",
"+"... | Update the cluster with id/label `cluster_id_label` using information provided in
`cluster_info`. | [
"Update",
"the",
"cluster",
"with",
"id",
"/",
"label",
"cluster_id_label",
"using",
"information",
"provided",
"in",
"cluster_info",
"."
] | python | train | 44.571429 |
benjamin-hodgson/Contexts | src/contexts/__init__.py | https://github.com/benjamin-hodgson/Contexts/blob/f5ee6a08aed19ab157158c1fc7752cff18cceb91/src/contexts/__init__.py#L42-L60 | def run_with_plugins(plugin_list):
"""
Carry out a test run with the supplied list of plugin instances.
The plugins are expected to identify the object to run.
Parameters:
plugin_list: a list of plugin instances (objects which implement some subset of PluginInterface)
Returns: exit code as ... | [
"def",
"run_with_plugins",
"(",
"plugin_list",
")",
":",
"composite",
"=",
"core",
".",
"PluginComposite",
"(",
"plugin_list",
")",
"to_run",
"=",
"composite",
".",
"get_object_to_run",
"(",
")",
"test_run",
"=",
"core",
".",
"TestRun",
"(",
"to_run",
",",
"... | Carry out a test run with the supplied list of plugin instances.
The plugins are expected to identify the object to run.
Parameters:
plugin_list: a list of plugin instances (objects which implement some subset of PluginInterface)
Returns: exit code as an integer.
The default behaviour (whic... | [
"Carry",
"out",
"a",
"test",
"run",
"with",
"the",
"supplied",
"list",
"of",
"plugin",
"instances",
".",
"The",
"plugins",
"are",
"expected",
"to",
"identify",
"the",
"object",
"to",
"run",
"."
] | python | train | 35.210526 |
saltstack/salt | salt/returners/smtp_return.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/smtp_return.py#L270-L279 | def event_return(events):
'''
Return event data via SMTP
'''
for event in events:
ret = event.get('data', False)
if ret:
returner(ret) | [
"def",
"event_return",
"(",
"events",
")",
":",
"for",
"event",
"in",
"events",
":",
"ret",
"=",
"event",
".",
"get",
"(",
"'data'",
",",
"False",
")",
"if",
"ret",
":",
"returner",
"(",
"ret",
")"
] | Return event data via SMTP | [
"Return",
"event",
"data",
"via",
"SMTP"
] | python | train | 17.1 |
daler/metaseq | metaseq/plotutils.py | https://github.com/daler/metaseq/blob/fa875d1f72317aa7ef95cb128b739956b16eef9f/metaseq/plotutils.py#L485-L512 | def prepare_logged(x, y):
"""
Transform `x` and `y` to a log scale while dealing with zeros.
This function scales `x` and `y` such that the points that are zero in one
array are set to the min of the other array.
When plotting expression data, frequently one sample will have reads in
a particu... | [
"def",
"prepare_logged",
"(",
"x",
",",
"y",
")",
":",
"xi",
"=",
"np",
".",
"log2",
"(",
"x",
")",
"yi",
"=",
"np",
".",
"log2",
"(",
"y",
")",
"xv",
"=",
"np",
".",
"isfinite",
"(",
"xi",
")",
"yv",
"=",
"np",
".",
"isfinite",
"(",
"yi",
... | Transform `x` and `y` to a log scale while dealing with zeros.
This function scales `x` and `y` such that the points that are zero in one
array are set to the min of the other array.
When plotting expression data, frequently one sample will have reads in
a particular feature but the other sample will ... | [
"Transform",
"x",
"and",
"y",
"to",
"a",
"log",
"scale",
"while",
"dealing",
"with",
"zeros",
"."
] | python | train | 30.5 |
GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/networking/network_daemon.py | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/networking/network_daemon.py#L101-L126 | def _ExtractInterfaceMetadata(self, metadata):
"""Extracts network interface metadata.
Args:
metadata: dict, the metadata response with the new network interfaces.
Returns:
list, a list of NetworkInterface objects.
"""
interfaces = []
for network_interface in metadata:
mac_ad... | [
"def",
"_ExtractInterfaceMetadata",
"(",
"self",
",",
"metadata",
")",
":",
"interfaces",
"=",
"[",
"]",
"for",
"network_interface",
"in",
"metadata",
":",
"mac_address",
"=",
"network_interface",
".",
"get",
"(",
"'mac'",
")",
"interface",
"=",
"self",
".",
... | Extracts network interface metadata.
Args:
metadata: dict, the metadata response with the new network interfaces.
Returns:
list, a list of NetworkInterface objects. | [
"Extracts",
"network",
"interface",
"metadata",
"."
] | python | train | 38.884615 |
ChristianTremblay/BAC0 | BAC0/scripts/Complete.py | https://github.com/ChristianTremblay/BAC0/blob/8d95b065ea068524a08f5b0c34322ebeeba95d06/BAC0/scripts/Complete.py#L101-L135 | def network_stats(self):
"""
Used by Flask to show informations on the network
"""
statistics = {}
mstp_networks = []
mstp_map = {}
ip_devices = []
bacoids = []
mstp_devices = []
for address, bacoid in self.whois_answer[0].keys():
... | [
"def",
"network_stats",
"(",
"self",
")",
":",
"statistics",
"=",
"{",
"}",
"mstp_networks",
"=",
"[",
"]",
"mstp_map",
"=",
"{",
"}",
"ip_devices",
"=",
"[",
"]",
"bacoids",
"=",
"[",
"]",
"mstp_devices",
"=",
"[",
"]",
"for",
"address",
",",
"bacoi... | Used by Flask to show informations on the network | [
"Used",
"by",
"Flask",
"to",
"show",
"informations",
"on",
"the",
"network"
] | python | train | 38 |
hazelcast/hazelcast-python-client | hazelcast/protocol/codec/set_add_all_codec.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/protocol/codec/set_add_all_codec.py#L20-L30 | def encode_request(name, value_list):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name, value_list))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client_message.appen... | [
"def",
"encode_request",
"(",
"name",
",",
"value_list",
")",
":",
"client_message",
"=",
"ClientMessage",
"(",
"payload_size",
"=",
"calculate_size",
"(",
"name",
",",
"value_list",
")",
")",
"client_message",
".",
"set_message_type",
"(",
"REQUEST_TYPE",
")",
... | Encode request into client_message | [
"Encode",
"request",
"into",
"client_message"
] | python | train | 44.545455 |
sbg/sevenbridges-python | sevenbridges/models/automation.py | https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/models/automation.py#L264-L275 | def get_packages(self, offset=None, limit=None, api=None):
"""
Return list of packages that belong to this automation
:param offset: Pagination offset.
:param limit: Pagination limit.
:param api: sevenbridges Api instance.
:return: AutomationPackage collection
"""... | [
"def",
"get_packages",
"(",
"self",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"api",
"=",
"None",
")",
":",
"api",
"=",
"api",
"or",
"self",
".",
"_API",
"return",
"AutomationPackage",
".",
"query",
"(",
"automation",
"=",
"self",
"... | Return list of packages that belong to this automation
:param offset: Pagination offset.
:param limit: Pagination limit.
:param api: sevenbridges Api instance.
:return: AutomationPackage collection | [
"Return",
"list",
"of",
"packages",
"that",
"belong",
"to",
"this",
"automation",
":",
"param",
"offset",
":",
"Pagination",
"offset",
".",
":",
"param",
"limit",
":",
"Pagination",
"limit",
".",
":",
"param",
"api",
":",
"sevenbridges",
"Api",
"instance",
... | python | train | 38.166667 |
HDI-Project/RDT | rdt/transformers/datetime.py | https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/datetime.py#L89-L102 | def to_timestamp(self, data):
"""Transform a datetime series into linux epoch.
Args:
data(pandas.DataFrame): DataFrame containins a column named as `self.col_name`.
Returns:
pandas.Series
"""
result = pd.Series(index=data.index)
_slice = ~data[se... | [
"def",
"to_timestamp",
"(",
"self",
",",
"data",
")",
":",
"result",
"=",
"pd",
".",
"Series",
"(",
"index",
"=",
"data",
".",
"index",
")",
"_slice",
"=",
"~",
"data",
"[",
"self",
".",
"col_name",
"]",
".",
"isnull",
"(",
")",
"result",
"[",
"_... | Transform a datetime series into linux epoch.
Args:
data(pandas.DataFrame): DataFrame containins a column named as `self.col_name`.
Returns:
pandas.Series | [
"Transform",
"a",
"datetime",
"series",
"into",
"linux",
"epoch",
"."
] | python | train | 30 |
stephantul/somber | somber/components/utilities.py | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/components/utilities.py#L56-L60 | def transform(self, X):
"""Transform your data to zero mean unit variance."""
if not self.is_fit:
raise ValueError("The scaler has not been fit yet.")
return (X-self.mean) / (self.std + 10e-7) | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"if",
"not",
"self",
".",
"is_fit",
":",
"raise",
"ValueError",
"(",
"\"The scaler has not been fit yet.\"",
")",
"return",
"(",
"X",
"-",
"self",
".",
"mean",
")",
"/",
"(",
"self",
".",
"std",
"+",... | Transform your data to zero mean unit variance. | [
"Transform",
"your",
"data",
"to",
"zero",
"mean",
"unit",
"variance",
"."
] | python | train | 44.8 |
devopshq/artifactory | artifactory.py | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L1202-L1225 | def deploy_deb(self,
file_name,
distribution,
component,
architecture,
parameters={}):
"""
Convenience method to deploy .deb packages
Keyword arguments:
file_name -- full path to local file th... | [
"def",
"deploy_deb",
"(",
"self",
",",
"file_name",
",",
"distribution",
",",
"component",
",",
"architecture",
",",
"parameters",
"=",
"{",
"}",
")",
":",
"params",
"=",
"{",
"'deb.distribution'",
":",
"distribution",
",",
"'deb.component'",
":",
"component",... | Convenience method to deploy .deb packages
Keyword arguments:
file_name -- full path to local file that will be deployed
distribution -- debian distribution (e.g. 'wheezy')
component -- repository component (e.g. 'main')
architecture -- package architecture (e.g. 'i386')
... | [
"Convenience",
"method",
"to",
"deploy",
".",
"deb",
"packages"
] | python | train | 33.583333 |
saltstack/salt | salt/modules/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1135-L1179 | def sed_contains(path,
text,
limit='',
flags='g'):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the file at ``path`` contains ``text``. Utilizes sed to
perform the search (line-wise search).
Note: the ``p`` flag wil... | [
"def",
"sed_contains",
"(",
"path",
",",
"text",
",",
"limit",
"=",
"''",
",",
"flags",
"=",
"'g'",
")",
":",
"# Largely inspired by Fabric's contrib.files.contains()",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"not",
"os",
... | .. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the file at ``path`` contains ``text``. Utilizes sed to
perform the search (line-wise search).
Note: the ``p`` flag will be added to any flags you pass in.
CLI Example:
.. code-block:: bash
salt '*' file.contains /... | [
"..",
"deprecated",
"::",
"0",
".",
"17",
".",
"0",
"Use",
":",
"func",
":",
"search",
"instead",
"."
] | python | train | 25.888889 |
yvesalexandre/bandicoot | bandicoot/individual.py | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L47-L63 | def number_of_contacts(records, direction=None, more=0):
"""
The number of contacts the user interacted with.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing.
more... | [
"def",
"number_of_contacts",
"(",
"records",
",",
"direction",
"=",
"None",
",",
"more",
"=",
"0",
")",
":",
"if",
"direction",
"is",
"None",
":",
"counter",
"=",
"Counter",
"(",
"r",
".",
"correspondent_id",
"for",
"r",
"in",
"records",
")",
"else",
"... | The number of contacts the user interacted with.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing.
more : int, default is 0
Counts only contacts with more than this... | [
"The",
"number",
"of",
"contacts",
"the",
"user",
"interacted",
"with",
"."
] | python | train | 38.294118 |
edx/edx-search | search/result_processor.py | https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/result_processor.py#L46-L51 | def strings_in_dictionary(dictionary):
""" Used by default implementation for finding excerpt """
strings = [value for value in six.itervalues(dictionary) if not isinstance(value, dict)]
for child_dict in [dv for dv in six.itervalues(dictionary) if isinstance(dv, dict)]:
strings.exte... | [
"def",
"strings_in_dictionary",
"(",
"dictionary",
")",
":",
"strings",
"=",
"[",
"value",
"for",
"value",
"in",
"six",
".",
"itervalues",
"(",
"dictionary",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
"]",
"for",
"child_dict",
"in",
... | Used by default implementation for finding excerpt | [
"Used",
"by",
"default",
"implementation",
"for",
"finding",
"excerpt"
] | python | valid | 66.166667 |
Trax-air/swagger-parser | swagger_parser/swagger_parser.py | https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L453-L500 | def validate_additional_properties(self, valid_response, response):
"""Validates additional properties. In additional properties, we only
need to compare the values of the dict, not the keys
Args:
valid_response: An example response (for example generated in
... | [
"def",
"validate_additional_properties",
"(",
"self",
",",
"valid_response",
",",
"response",
")",
":",
"assert",
"isinstance",
"(",
"valid_response",
",",
"dict",
")",
"assert",
"isinstance",
"(",
"response",
",",
"dict",
")",
"# the type of the value of the first ke... | Validates additional properties. In additional properties, we only
need to compare the values of the dict, not the keys
Args:
valid_response: An example response (for example generated in
_get_example_from_properties(self, spec))
Ty... | [
"Validates",
"additional",
"properties",
".",
"In",
"additional",
"properties",
"we",
"only",
"need",
"to",
"compare",
"the",
"values",
"of",
"the",
"dict",
"not",
"the",
"keys"
] | python | train | 42.3125 |
seleniumbase/SeleniumBase | seleniumbase/plugins/db_reporting_plugin.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/plugins/db_reporting_plugin.py#L92-L96 | def addError(self, test, err, capt=None):
"""
After a test error, we want to record testcase run information.
"""
self.__insert_test_result(constants.State.ERROR, test, err) | [
"def",
"addError",
"(",
"self",
",",
"test",
",",
"err",
",",
"capt",
"=",
"None",
")",
":",
"self",
".",
"__insert_test_result",
"(",
"constants",
".",
"State",
".",
"ERROR",
",",
"test",
",",
"err",
")"
] | After a test error, we want to record testcase run information. | [
"After",
"a",
"test",
"error",
"we",
"want",
"to",
"record",
"testcase",
"run",
"information",
"."
] | python | train | 40.2 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/frame.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/frame.py#L25-L52 | def extract_vars(*names,**kw):
"""Extract a set of variables by name from another frame.
:Parameters:
- `*names`: strings
One or more variable names which will be extracted from the caller's
frame.
:Keywords:
- `depth`: integer (0)
How many frames in the stack to walk when ... | [
"def",
"extract_vars",
"(",
"*",
"names",
",",
"*",
"*",
"kw",
")",
":",
"depth",
"=",
"kw",
".",
"get",
"(",
"'depth'",
",",
"0",
")",
"callerNS",
"=",
"sys",
".",
"_getframe",
"(",
"depth",
"+",
"1",
")",
".",
"f_locals",
"return",
"dict",
"(",... | Extract a set of variables by name from another frame.
:Parameters:
- `*names`: strings
One or more variable names which will be extracted from the caller's
frame.
:Keywords:
- `depth`: integer (0)
How many frames in the stack to walk when looking for your variables.
Exam... | [
"Extract",
"a",
"set",
"of",
"variables",
"by",
"name",
"from",
"another",
"frame",
"."
] | python | test | 24.178571 |
b3j0f/utils | b3j0f/utils/property.py | https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L255-L275 | def get_first_property(elt, key, default=None, ctx=None):
"""Get first property related to one input key.
:param elt: first property elt. Not None methods.
:param str key: property key to get.
:param default: default value to return if key does not exist in elt.
properties
:param ctx: elt c... | [
"def",
"get_first_property",
"(",
"elt",
",",
"key",
",",
"default",
"=",
"None",
",",
"ctx",
"=",
"None",
")",
":",
"result",
"=",
"default",
"properties",
"=",
"_get_properties",
"(",
"elt",
",",
"keys",
"=",
"(",
"key",
",",
")",
",",
"ctx",
"=",
... | Get first property related to one input key.
:param elt: first property elt. Not None methods.
:param str key: property key to get.
:param default: default value to return if key does not exist in elt.
properties
:param ctx: elt ctx from where get properties. Equals elt if None. It
allo... | [
"Get",
"first",
"property",
"related",
"to",
"one",
"input",
"key",
"."
] | python | train | 33.571429 |
Grokzen/pykwalify | pykwalify/cli.py | https://github.com/Grokzen/pykwalify/blob/02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7/pykwalify/cli.py#L14-L65 | def parse_cli():
"""
The outline of this function needs to be like this:
1. parse arguments
2. validate arguments only, dont go into other logic/code
3. run application logic
"""
#
# 1. parse cli arguments
#
__docopt__ = """
usage: pykwalify -d FILE -s FILE ... [-e FILE ...]
... | [
"def",
"parse_cli",
"(",
")",
":",
"#",
"# 1. parse cli arguments",
"#",
"__docopt__",
"=",
"\"\"\"\nusage: pykwalify -d FILE -s FILE ... [-e FILE ...]\n [--strict-rule-validation] [--fix-ruby-style-regex] [--allow-assertions] [--encoding ENCODING]\n [-v ...] [-q]\n\noptional argumen... | The outline of this function needs to be like this:
1. parse arguments
2. validate arguments only, dont go into other logic/code
3. run application logic | [
"The",
"outline",
"of",
"this",
"function",
"needs",
"to",
"be",
"like",
"this",
":"
] | python | train | 40.019231 |
saltstack/salt | salt/states/keystone.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L484-L512 | def role_present(name, profile=None, **connection_args):
''''
Ensures that the keystone role exists
name
The name of the role that should be present
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Role "{0}" already exists'.format(name)}
... | [
"def",
"role_present",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"'Role \"{0}\" al... | Ensures that the keystone role exists
name
The name of the role that should be present | [
"Ensures",
"that",
"the",
"keystone",
"role",
"exists"
] | python | train | 32.62069 |
codelv/enaml-native | src/enamlnative/ios/uikit_slider.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/uikit_slider.py#L59-L81 | def init_widget(self):
""" Bind the on property to the checked state """
super(UiKitSlider, self).init_widget()
d = self.declaration
if d.min:
self.set_min(d.min)
if d.max:
self.set_max(d.max)
if d.progress:
self.set_progress(d.progres... | [
"def",
"init_widget",
"(",
"self",
")",
":",
"super",
"(",
"UiKitSlider",
",",
"self",
")",
".",
"init_widget",
"(",
")",
"d",
"=",
"self",
".",
"declaration",
"if",
"d",
".",
"min",
":",
"self",
".",
"set_min",
"(",
"d",
".",
"min",
")",
"if",
"... | Bind the on property to the checked state | [
"Bind",
"the",
"on",
"property",
"to",
"the",
"checked",
"state"
] | python | train | 33.26087 |
tommikaikkonen/prettyprinter | prettyprinter/prettyprinter.py | https://github.com/tommikaikkonen/prettyprinter/blob/6b405884b8085eaf867e81c02b7b662b463ac5a0/prettyprinter/prettyprinter.py#L297-L304 | def assoc(self, key, value):
"""
Return a modified PrettyContext with ``key`` set to ``value``
"""
return self._replace(user_ctx={
**self.user_ctx,
key: value,
}) | [
"def",
"assoc",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"self",
".",
"_replace",
"(",
"user_ctx",
"=",
"{",
"*",
"*",
"self",
".",
"user_ctx",
",",
"key",
":",
"value",
",",
"}",
")"
] | Return a modified PrettyContext with ``key`` set to ``value`` | [
"Return",
"a",
"modified",
"PrettyContext",
"with",
"key",
"set",
"to",
"value"
] | python | train | 27.375 |
ultrabug/py3status | py3status/modules/i3pystatus.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/i3pystatus.py#L167-L194 | def event(self, button):
"""
button has been clicked
"""
# cancel any pending timer
if self.timer:
self.timer.cancel()
if self.last_button != button:
if self.last_button:
# new button clicked process the one before.
... | [
"def",
"event",
"(",
"self",
",",
"button",
")",
":",
"# cancel any pending timer",
"if",
"self",
".",
"timer",
":",
"self",
".",
"timer",
".",
"cancel",
"(",
")",
"if",
"self",
".",
"last_button",
"!=",
"button",
":",
"if",
"self",
".",
"last_button",
... | button has been clicked | [
"button",
"has",
"been",
"clicked"
] | python | train | 35.535714 |
zeaphoo/budoc | budoc/pydoc.py | https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L26-L59 | def import_module(module_name):
"""
Imports a module. A single point of truth for importing modules to
be documented by `pydoc`. In particular, it makes sure that the top
module in `module_name` can be imported by using only the paths in
`pydoc.import_path`.
If a module has already been importe... | [
"def",
"import_module",
"(",
"module_name",
")",
":",
"if",
"import_path",
"!=",
"sys",
".",
"path",
":",
"# Such a kludge. Only restrict imports if the `import_path` has",
"# been changed. We don't want to always restrict imports, since",
"# providing a path to `imp.find_module` stops... | Imports a module. A single point of truth for importing modules to
be documented by `pydoc`. In particular, it makes sure that the top
module in `module_name` can be imported by using only the paths in
`pydoc.import_path`.
If a module has already been imported, then its corresponding entry
in `sys.... | [
"Imports",
"a",
"module",
".",
"A",
"single",
"point",
"of",
"truth",
"for",
"importing",
"modules",
"to",
"be",
"documented",
"by",
"pydoc",
".",
"In",
"particular",
"it",
"makes",
"sure",
"that",
"the",
"top",
"module",
"in",
"module_name",
"can",
"be",
... | python | train | 43.588235 |
ninuxorg/nodeshot | nodeshot/core/base/models.py | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/models.py#L161-L168 | def save(self, *args, **kwargs):
""" if order left blank """
if self.order == '' or self.order is None:
try:
self.order = self.get_auto_order_queryset().order_by("-order")[0].order + 1
except IndexError:
self.order = 0
super(BaseOrdered, se... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"order",
"==",
"''",
"or",
"self",
".",
"order",
"is",
"None",
":",
"try",
":",
"self",
".",
"order",
"=",
"self",
".",
"get_auto_order_queryset",
... | if order left blank | [
"if",
"order",
"left",
"blank"
] | python | train | 40.375 |
ShopRunner/apparate | apparate/update_databricks_library.py | https://github.com/ShopRunner/apparate/blob/3ae74798c1c52cf3f69ee67d617c7c875c949577/apparate/update_databricks_library.py#L405-L452 | def delete_old_versions(
logger,
new_library_match,
id_nums,
token,
prod_folder,
host
):
"""
delete any other versions of the same library where:
it has the same major version
it has a smaller minor version
it lives in prod_folder
Parameters
----------
... | [
"def",
"delete_old_versions",
"(",
"logger",
",",
"new_library_match",
",",
"id_nums",
",",
"token",
",",
"prod_folder",
",",
"host",
")",
":",
"old_versions",
"=",
"[",
"]",
"for",
"name",
",",
"lib",
"in",
"id_nums",
".",
"items",
"(",
")",
":",
"if",
... | delete any other versions of the same library where:
it has the same major version
it has a smaller minor version
it lives in prod_folder
Parameters
----------
logger: logging object
configured in cli_commands.py
match: FilenameMatch object
match object with libr... | [
"delete",
"any",
"other",
"versions",
"of",
"the",
"same",
"library",
"where",
":",
"it",
"has",
"the",
"same",
"major",
"version",
"it",
"has",
"a",
"smaller",
"minor",
"version",
"it",
"lives",
"in",
"prod_folder"
] | python | train | 29.416667 |
inveniosoftware/invenio-assets | invenio_assets/filters.py | https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/filters.py#L121-L133 | def input(self, _in, out, **kwargs):
"""Process individual translation file."""
language_code = _re_language_code.search(_in.read()).group(
'language_code'
)
_in.seek(0) # move at the begining after matching the language
catalog = read_po(_in)
out.write('gett... | [
"def",
"input",
"(",
"self",
",",
"_in",
",",
"out",
",",
"*",
"*",
"kwargs",
")",
":",
"language_code",
"=",
"_re_language_code",
".",
"search",
"(",
"_in",
".",
"read",
"(",
")",
")",
".",
"group",
"(",
"'language_code'",
")",
"_in",
".",
"seek",
... | Process individual translation file. | [
"Process",
"individual",
"translation",
"file",
"."
] | python | train | 41.384615 |
cga-harvard/Hypermap-Registry | hypermap/search_api/utils.py | https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L247-L257 | def parse_solr_geo_range_as_pair(geo_box_str):
"""
:param geo_box_str: [-90,-180 TO 90,180]
:return: ("-90,-180", "90,180")
"""
pattern = "\\[(.*) TO (.*)\\]"
matcher = re.search(pattern, geo_box_str)
if matcher:
return matcher.group(1), matcher.group(2)
else:
raise Excep... | [
"def",
"parse_solr_geo_range_as_pair",
"(",
"geo_box_str",
")",
":",
"pattern",
"=",
"\"\\\\[(.*) TO (.*)\\\\]\"",
"matcher",
"=",
"re",
".",
"search",
"(",
"pattern",
",",
"geo_box_str",
")",
"if",
"matcher",
":",
"return",
"matcher",
".",
"group",
"(",
"1",
... | :param geo_box_str: [-90,-180 TO 90,180]
:return: ("-90,-180", "90,180") | [
":",
"param",
"geo_box_str",
":",
"[",
"-",
"90",
"-",
"180",
"TO",
"90",
"180",
"]",
":",
"return",
":",
"(",
"-",
"90",
"-",
"180",
"90",
"180",
")"
] | python | train | 34.181818 |
sio2project/filetracker | filetracker/client/client.py | https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L294-L307 | def delete_file(self, name):
"""Deletes the file identified by ``name`` along with its metadata.
The file is removed from both the local store and the remote store.
"""
if self.local_store:
lock = self.lock_manager.lock_for(name)
lock.lock_exclusive()
... | [
"def",
"delete_file",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"local_store",
":",
"lock",
"=",
"self",
".",
"lock_manager",
".",
"lock_for",
"(",
"name",
")",
"lock",
".",
"lock_exclusive",
"(",
")",
"try",
":",
"self",
".",
"local_store... | Deletes the file identified by ``name`` along with its metadata.
The file is removed from both the local store and the remote store. | [
"Deletes",
"the",
"file",
"identified",
"by",
"name",
"along",
"with",
"its",
"metadata",
"."
] | python | train | 35.285714 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_chassis.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_chassis.py#L24-L34 | def hide_virtual_ip_holder_chassis_virtual_ipv6(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_virtual_ip_holder = ET.SubElement(config, "hide-virtual-ip-holder", xmlns="urn:brocade.com:mgmt:brocade-chassis")
chassis = ET.SubElement(hide_virtual_ip... | [
"def",
"hide_virtual_ip_holder_chassis_virtual_ipv6",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_virtual_ip_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hide-virtual-ip-holder... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 48.818182 |
newville/wxmplot | wxmplot/imagepanel.py | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/imagepanel.py#L196-L231 | def set_viewlimits(self, axes=None):
""" update xy limits of a plot"""
if axes is None:
axes = self.axes
xmin, xmax, ymin, ymax = self.data_range
if len(self.conf.zoom_lims) >1:
zlims = self.conf.zoom_lims[-1]
if axes in zlims:
xmin, x... | [
"def",
"set_viewlimits",
"(",
"self",
",",
"axes",
"=",
"None",
")",
":",
"if",
"axes",
"is",
"None",
":",
"axes",
"=",
"self",
".",
"axes",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
"=",
"self",
".",
"data_range",
"if",
"len",
"(",
"self",
... | update xy limits of a plot | [
"update",
"xy",
"limits",
"of",
"a",
"plot"
] | python | train | 32.472222 |
hydpy-dev/hydpy | hydpy/core/parametertools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/parametertools.py#L143-L188 | def update(self) -> None:
"""Call method |Parameter.update| of all "secondary" parameters.
Directly after initialisation, neither the primary (`control`)
parameters nor the secondary (`derived`) parameters of
application model |hstream_v1| are ready for usage:
>>> from hydpy.m... | [
"def",
"update",
"(",
"self",
")",
"->",
"None",
":",
"for",
"subpars",
"in",
"self",
".",
"secondary_subpars",
":",
"for",
"par",
"in",
"subpars",
":",
"try",
":",
"par",
".",
"update",
"(",
")",
"except",
"BaseException",
":",
"objecttools",
".",
"au... | Call method |Parameter.update| of all "secondary" parameters.
Directly after initialisation, neither the primary (`control`)
parameters nor the secondary (`derived`) parameters of
application model |hstream_v1| are ready for usage:
>>> from hydpy.models.hstream_v1 import *
>>>... | [
"Call",
"method",
"|Parameter",
".",
"update|",
"of",
"all",
"secondary",
"parameters",
"."
] | python | train | 33.76087 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/core_v1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L9887-L9914 | def delete_namespaced_pod(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_pod # noqa: E501
delete a Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.... | [
"def",
"delete_namespaced_pod",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
... | delete_namespaced_pod # noqa: E501
delete a Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_pod(name, namespace, async_req=True)
>>> result = thread.ge... | [
"delete_namespaced_pod",
"#",
"noqa",
":",
"E501"
] | python | train | 93.107143 |
hammerlab/cohorts | cohorts/variant_stats.py | https://github.com/hammerlab/cohorts/blob/278b05e609e6c4d4a77c57d49446460be53ea33e/cohorts/variant_stats.py#L163-L178 | def _vcf_is_strelka(variant_file, variant_metadata):
"""Return True if variant_file given is in strelka format
"""
if "strelka" in variant_file.lower():
return True
elif "NORMAL" in variant_metadata["sample_info"].keys():
return True
else:
vcf_reader = vcf.Reader(open(variant... | [
"def",
"_vcf_is_strelka",
"(",
"variant_file",
",",
"variant_metadata",
")",
":",
"if",
"\"strelka\"",
"in",
"variant_file",
".",
"lower",
"(",
")",
":",
"return",
"True",
"elif",
"\"NORMAL\"",
"in",
"variant_metadata",
"[",
"\"sample_info\"",
"]",
".",
"keys",
... | Return True if variant_file given is in strelka format | [
"Return",
"True",
"if",
"variant_file",
"given",
"is",
"in",
"strelka",
"format"
] | python | train | 32.375 |
saltstack/salt | salt/modules/git.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L439-L453 | def _which_git_config(global_, cwd, user, password, output_encoding=None):
'''
Based on whether global or local config is desired, return a list of CLI
args to include in the git config command.
'''
if global_:
return ['--global']
version_ = _LooseVersion(version(versioninfo=False))
... | [
"def",
"_which_git_config",
"(",
"global_",
",",
"cwd",
",",
"user",
",",
"password",
",",
"output_encoding",
"=",
"None",
")",
":",
"if",
"global_",
":",
"return",
"[",
"'--global'",
"]",
"version_",
"=",
"_LooseVersion",
"(",
"version",
"(",
"versioninfo",... | Based on whether global or local config is desired, return a list of CLI
args to include in the git config command. | [
"Based",
"on",
"whether",
"global",
"or",
"local",
"config",
"is",
"desired",
"return",
"a",
"list",
"of",
"CLI",
"args",
"to",
"include",
"in",
"the",
"git",
"config",
"command",
"."
] | python | train | 42.066667 |
cbclab/MOT | mot/mcmc_diagnostics.py | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/mcmc_diagnostics.py#L444-L462 | def monte_carlo_standard_error(chain, batch_size_generator=None, compute_method=None):
"""Compute Monte Carlo standard errors for the expectations
This is a convenience function that calls the compute method for each batch size and returns the lowest ESS
over the used batch sizes.
Args:
chain ... | [
"def",
"monte_carlo_standard_error",
"(",
"chain",
",",
"batch_size_generator",
"=",
"None",
",",
"compute_method",
"=",
"None",
")",
":",
"batch_size_generator",
"=",
"batch_size_generator",
"or",
"SquareRootSingleBatch",
"(",
")",
"compute_method",
"=",
"compute_metho... | Compute Monte Carlo standard errors for the expectations
This is a convenience function that calls the compute method for each batch size and returns the lowest ESS
over the used batch sizes.
Args:
chain (ndarray): the Markov chain
batch_size_generator (UniVariateESSBatchSizeGenerator): th... | [
"Compute",
"Monte",
"Carlo",
"standard",
"errors",
"for",
"the",
"expectations"
] | python | train | 53.421053 |
aiven/pghoard | pghoard/pgutil.py | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/pgutil.py#L67-L100 | def parse_connection_string_libpq(connection_string):
"""parse a postgresql connection string as defined in
http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING"""
fields = {}
while True:
connection_string = connection_string.strip()
if not connection_string:... | [
"def",
"parse_connection_string_libpq",
"(",
"connection_string",
")",
":",
"fields",
"=",
"{",
"}",
"while",
"True",
":",
"connection_string",
"=",
"connection_string",
".",
"strip",
"(",
")",
"if",
"not",
"connection_string",
":",
"break",
"if",
"\"=\"",
"not"... | parse a postgresql connection string as defined in
http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING | [
"parse",
"a",
"postgresql",
"connection",
"string",
"as",
"defined",
"in",
"http",
":",
"//",
"www",
".",
"postgresql",
".",
"org",
"/",
"docs",
"/",
"current",
"/",
"static",
"/",
"libpq",
"-",
"connect",
".",
"html#LIBPQ",
"-",
"CONNSTRING"
] | python | train | 40 |
GearPlug/payu-python | payu/payments.py | https://github.com/GearPlug/payu-python/blob/47ec5c9fc89f1f89a53ec0a68c84f358bbe3394e/payu/payments.py#L36-L233 | def make_payment(self, *, reference_code, description, tx_value, tx_tax, tx_tax_return_base, currency, buyer,
payer, credit_card, payment_method, payment_country, device_session_id, ip_address, cookie,
user_agent, language=None, shipping_address=None, extra_parameters=None, not... | [
"def",
"make_payment",
"(",
"self",
",",
"*",
",",
"reference_code",
",",
"description",
",",
"tx_value",
",",
"tx_tax",
",",
"tx_tax_return_base",
",",
"currency",
",",
"buyer",
",",
"payer",
",",
"credit_card",
",",
"payment_method",
",",
"payment_country",
... | Authorization: used to verify if a credit card is active, if it has funds, etc.
The transaction is not complete until a transaction capture is sent (only available for accounts in Argentina,
Brazil, Peru).
Capture: terminates a previously authorized transaction.
This is when the account... | [
"Authorization",
":",
"used",
"to",
"verify",
"if",
"a",
"credit",
"card",
"is",
"active",
"if",
"it",
"has",
"funds",
"etc",
".",
"The",
"transaction",
"is",
"not",
"complete",
"until",
"a",
"transaction",
"capture",
"is",
"sent",
"(",
"only",
"available"... | python | train | 40.984848 |
mfussenegger/cr8 | cr8/misc.py | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L87-L96 | def get_lines(filename: str) -> Iterator[str]:
"""Create an iterator that returns the lines of a utf-8 encoded file."""
if filename.endswith('.gz'):
with gzip.open(filename, 'r') as f:
for line in f:
yield line.decode('utf-8')
else:
with open(filename, 'r', encodi... | [
"def",
"get_lines",
"(",
"filename",
":",
"str",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
... | Create an iterator that returns the lines of a utf-8 encoded file. | [
"Create",
"an",
"iterator",
"that",
"returns",
"the",
"lines",
"of",
"a",
"utf",
"-",
"8",
"encoded",
"file",
"."
] | python | train | 38.2 |
alpha-xone/xbbg | xbbg/io/storage.py | https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/storage.py#L137-L183 | def save_intraday(data: pd.DataFrame, ticker: str, dt, typ='TRADE'):
"""
Check whether data is done for the day and save
Args:
data: data
ticker: ticker
dt: date
typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]
Examples:
>>> os.environ['BBG_ROOT'] ... | [
"def",
"save_intraday",
"(",
"data",
":",
"pd",
".",
"DataFrame",
",",
"ticker",
":",
"str",
",",
"dt",
",",
"typ",
"=",
"'TRADE'",
")",
":",
"cur_dt",
"=",
"pd",
".",
"Timestamp",
"(",
"dt",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"logger",
... | Check whether data is done for the day and save
Args:
data: data
ticker: ticker
dt: date
typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]
Examples:
>>> os.environ['BBG_ROOT'] = 'xbbg/tests/data'
>>> sample = pd.read_parquet('xbbg/tests/data/aapl.pa... | [
"Check",
"whether",
"data",
"is",
"done",
"for",
"the",
"day",
"and",
"save"
] | python | valid | 34.553191 |
neuropsychology/NeuroKit.py | neurokit/bio/bio_ecg_preprocessing.py | https://github.com/neuropsychology/NeuroKit.py/blob/c9589348fbbde0fa7e986048c48f38e6b488adfe/neurokit/bio/bio_ecg_preprocessing.py#L256-L403 | def ecg_wave_detector(ecg, rpeaks):
"""
Returns the localization of the P, Q, T waves. This function needs massive help!
Parameters
----------
ecg : list or ndarray
ECG signal (preferably filtered).
rpeaks : list or ndarray
R peaks localization.
Returns
----------
e... | [
"def",
"ecg_wave_detector",
"(",
"ecg",
",",
"rpeaks",
")",
":",
"q_waves",
"=",
"[",
"]",
"p_waves",
"=",
"[",
"]",
"q_waves_starts",
"=",
"[",
"]",
"s_waves",
"=",
"[",
"]",
"t_waves",
"=",
"[",
"]",
"t_waves_starts",
"=",
"[",
"]",
"t_waves_ends",
... | Returns the localization of the P, Q, T waves. This function needs massive help!
Parameters
----------
ecg : list or ndarray
ECG signal (preferably filtered).
rpeaks : list or ndarray
R peaks localization.
Returns
----------
ecg_waves : dict
Contains wave peaks loca... | [
"Returns",
"the",
"localization",
"of",
"the",
"P",
"Q",
"T",
"waves",
".",
"This",
"function",
"needs",
"massive",
"help!"
] | python | train | 36.695946 |
BernardFW/bernard | src/bernard/reporter/_raven.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/reporter/_raven.py#L68-L74 | def report(self, request: 'Request'=None, state: Text=None):
"""
Report current exception to Sentry.
"""
self._make_context(request, state)
self.client.captureException()
self._clear_context() | [
"def",
"report",
"(",
"self",
",",
"request",
":",
"'Request'",
"=",
"None",
",",
"state",
":",
"Text",
"=",
"None",
")",
":",
"self",
".",
"_make_context",
"(",
"request",
",",
"state",
")",
"self",
".",
"client",
".",
"captureException",
"(",
")",
... | Report current exception to Sentry. | [
"Report",
"current",
"exception",
"to",
"Sentry",
"."
] | python | train | 33.428571 |
mixcloud/django-experiments | experiments/admin.py | https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/admin.py#L46-L61 | def get_form(self, request, obj=None, **kwargs):
"""
Add the default alternative dropdown with appropriate choices
"""
if obj:
if obj.alternatives:
choices = [(alternative, alternative) for alternative in obj.alternatives.keys()]
else:
... | [
"def",
"get_form",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"obj",
":",
"if",
"obj",
".",
"alternatives",
":",
"choices",
"=",
"[",
"(",
"alternative",
",",
"alternative",
")",
"for",
"alternative... | Add the default alternative dropdown with appropriate choices | [
"Add",
"the",
"default",
"alternative",
"dropdown",
"with",
"appropriate",
"choices"
] | python | train | 48.875 |
materialsproject/pymatgen | pymatgen/io/vasp/outputs.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/outputs.py#L2796-L2806 | def get_axis_grid(self, ind):
"""
Returns the grid for a particular axis.
Args:
ind (int): Axis index.
"""
ng = self.dim
num_pts = ng[ind]
lengths = self.structure.lattice.abc
return [i / num_pts * lengths[ind] for i in range(num_pts)] | [
"def",
"get_axis_grid",
"(",
"self",
",",
"ind",
")",
":",
"ng",
"=",
"self",
".",
"dim",
"num_pts",
"=",
"ng",
"[",
"ind",
"]",
"lengths",
"=",
"self",
".",
"structure",
".",
"lattice",
".",
"abc",
"return",
"[",
"i",
"/",
"num_pts",
"*",
"lengths... | Returns the grid for a particular axis.
Args:
ind (int): Axis index. | [
"Returns",
"the",
"grid",
"for",
"a",
"particular",
"axis",
"."
] | python | train | 27.454545 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1392-L1395 | def p_try_statement_3(self, p):
"""try_statement : TRY block catch finally"""
p[0] = self.asttypes.Try(statements=p[2], catch=p[3], fin=p[4])
p[0].setpos(p) | [
"def",
"p_try_statement_3",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Try",
"(",
"statements",
"=",
"p",
"[",
"2",
"]",
",",
"catch",
"=",
"p",
"[",
"3",
"]",
",",
"fin",
"=",
"p",
"[",
"4",
"]... | try_statement : TRY block catch finally | [
"try_statement",
":",
"TRY",
"block",
"catch",
"finally"
] | python | train | 44.25 |
SpikeInterface/spikeextractors | spikeextractors/SortingExtractor.py | https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/SortingExtractor.py#L359-L383 | def copy_unit_spike_features(self, sorting, unit_ids=None):
'''Copy unit spike features from another sorting extractor to the current
sorting extractor.
Parameters
----------
sorting: SortingExtractor
The sorting extractor from which the spike features will be copied... | [
"def",
"copy_unit_spike_features",
"(",
"self",
",",
"sorting",
",",
"unit_ids",
"=",
"None",
")",
":",
"if",
"unit_ids",
"is",
"None",
":",
"unit_ids",
"=",
"sorting",
".",
"get_unit_ids",
"(",
")",
"if",
"isinstance",
"(",
"unit_ids",
",",
"int",
")",
... | Copy unit spike features from another sorting extractor to the current
sorting extractor.
Parameters
----------
sorting: SortingExtractor
The sorting extractor from which the spike features will be copied
unit_ids: (array_like, int)
The list (or single va... | [
"Copy",
"unit",
"spike",
"features",
"from",
"another",
"sorting",
"extractor",
"to",
"the",
"current",
"sorting",
"extractor",
"."
] | python | train | 57.4 |
psss/did | did/base.py | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/base.py#L269-L275 | def this_year():
""" Return start and end date of this fiscal year """
since = TODAY
while since.month != 3 or since.day != 1:
since -= delta(days=1)
until = since + delta(years=1)
return Date(since), Date(until) | [
"def",
"this_year",
"(",
")",
":",
"since",
"=",
"TODAY",
"while",
"since",
".",
"month",
"!=",
"3",
"or",
"since",
".",
"day",
"!=",
"1",
":",
"since",
"-=",
"delta",
"(",
"days",
"=",
"1",
")",
"until",
"=",
"since",
"+",
"delta",
"(",
"years",... | Return start and end date of this fiscal year | [
"Return",
"start",
"and",
"end",
"date",
"of",
"this",
"fiscal",
"year"
] | python | train | 36.857143 |
explosion/spaCy | spacy/tokens/_serialize.py | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L79-L94 | def from_bytes(self, string):
"""Deserialize the binder's annotations from a byte string."""
msg = srsly.msgpack_loads(gzip.decompress(string))
self.attrs = msg["attrs"]
self.strings = set(msg["strings"])
lengths = numpy.fromstring(msg["lengths"], dtype="int32")
flat_spac... | [
"def",
"from_bytes",
"(",
"self",
",",
"string",
")",
":",
"msg",
"=",
"srsly",
".",
"msgpack_loads",
"(",
"gzip",
".",
"decompress",
"(",
"string",
")",
")",
"self",
".",
"attrs",
"=",
"msg",
"[",
"\"attrs\"",
"]",
"self",
".",
"strings",
"=",
"set"... | Deserialize the binder's annotations from a byte string. | [
"Deserialize",
"the",
"binder",
"s",
"annotations",
"from",
"a",
"byte",
"string",
"."
] | python | train | 53.0625 |
constverum/ProxyBroker | proxybroker/proxy.py | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/proxy.py#L236-L260 | def as_json(self):
"""Return the proxy's properties in JSON format.
:rtype: dict
"""
info = {
'host': self.host,
'port': self.port,
'geo': {
'country': {'code': self._geo.code, 'name': self._geo.name},
'region': {
... | [
"def",
"as_json",
"(",
"self",
")",
":",
"info",
"=",
"{",
"'host'",
":",
"self",
".",
"host",
",",
"'port'",
":",
"self",
".",
"port",
",",
"'geo'",
":",
"{",
"'country'",
":",
"{",
"'code'",
":",
"self",
".",
"_geo",
".",
"code",
",",
"'name'",... | Return the proxy's properties in JSON format.
:rtype: dict | [
"Return",
"the",
"proxy",
"s",
"properties",
"in",
"JSON",
"format",
"."
] | python | train | 32.96 |
apache/incubator-mxnet | python/mxnet/contrib/onnx/onnx2mx/_op_translations.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L296-L299 | def _selu(attrs, inputs, proto_obj):
"""Selu function"""
new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type': 'selu'})
return 'LeakyReLU', new_attrs, inputs | [
"def",
"_selu",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"new_attrs",
"=",
"translation_utils",
".",
"_add_extra_attributes",
"(",
"attrs",
",",
"{",
"'act_type'",
":",
"'selu'",
"}",
")",
"return",
"'LeakyReLU'",
",",
"new_attrs",
",",
"inpu... | Selu function | [
"Selu",
"function"
] | python | train | 46 |
gmr/rejected | rejected/smart_consumer.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/smart_consumer.py#L356-L376 | def _dump_csv(self, rows):
"""Take a list of dicts and return it as a CSV value. The
.. versionchanged:: 4.0.0
:param list rows: A list of lists to return as a CSV
:rtype: str
"""
self.logger.debug('Writing %r', rows)
csv = self._maybe_import('csv')
buf... | [
"def",
"_dump_csv",
"(",
"self",
",",
"rows",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Writing %r'",
",",
"rows",
")",
"csv",
"=",
"self",
".",
"_maybe_import",
"(",
"'csv'",
")",
"buff",
"=",
"io",
".",
"StringIO",
"(",
")",
"if",
"_P... | Take a list of dicts and return it as a CSV value. The
.. versionchanged:: 4.0.0
:param list rows: A list of lists to return as a CSV
:rtype: str | [
"Take",
"a",
"list",
"of",
"dicts",
"and",
"return",
"it",
"as",
"a",
"CSV",
"value",
".",
"The"
] | python | train | 29.666667 |
StackStorm/pybind | pybind/slxos/v17r_1_01a/interface/port_channel/logical_interface/port_channel/pc_cmd_container_dummy/service_instance_vlan_cmds_dummy_container/get_untagged_vlan_dummy/untagged/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/interface/port_channel/logical_interface/port_channel/pc_cmd_container_dummy/service_instance_vlan_cmds_dummy_container/get_untagged_vlan_dummy/untagged/__init__.py#L92-L113 | def _set_untagged_vlan(self, v, load=False):
"""
Setter method for untagged_vlan, mapped from YANG variable /interface/port_channel/logical_interface/port_channel/pc_cmd_container_dummy/service_instance_vlan_cmds_dummy_container/get_untagged_vlan_dummy/untagged/untagged_vlan (container)
If this variable is ... | [
"def",
"_set_untagged_vlan",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | Setter method for untagged_vlan, mapped from YANG variable /interface/port_channel/logical_interface/port_channel/pc_cmd_container_dummy/service_instance_vlan_cmds_dummy_container/get_untagged_vlan_dummy/untagged/untagged_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, th... | [
"Setter",
"method",
"for",
"untagged_vlan",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"port_channel",
"/",
"logical_interface",
"/",
"port_channel",
"/",
"pc_cmd_container_dummy",
"/",
"service_instance_vlan_cmds_dummy_container",
"/",
"get_untagged_vlan_... | python | train | 86.909091 |
keon/algorithms | algorithms/arrays/longest_non_repeat.py | https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/longest_non_repeat.py#L50-L69 | def get_longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
Return max_len and the substring as a tuple
"""
if string is None:
return 0, ''
sub_string = ''
dict = {}
max_length = 0
j = 0
for i in range(len(string))... | [
"def",
"get_longest_non_repeat_v1",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"0",
",",
"''",
"sub_string",
"=",
"''",
"dict",
"=",
"{",
"}",
"max_length",
"=",
"0",
"j",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
... | Find the length of the longest substring
without repeating characters.
Return max_len and the substring as a tuple | [
"Find",
"the",
"length",
"of",
"the",
"longest",
"substring",
"without",
"repeating",
"characters",
".",
"Return",
"max_len",
"and",
"the",
"substring",
"as",
"a",
"tuple"
] | python | train | 27.5 |
bcbio/bcbio-nextgen | bcbio/install.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/install.py#L164-L181 | def _symlink_bcbio(args, script="bcbio_nextgen.py", env_name=None, prefix=None):
"""Ensure a bcbio-nextgen script symlink in final tool directory.
"""
if env_name:
bcbio_anaconda = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(sys.executable))),
... | [
"def",
"_symlink_bcbio",
"(",
"args",
",",
"script",
"=",
"\"bcbio_nextgen.py\"",
",",
"env_name",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"env_name",
":",
"bcbio_anaconda",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
... | Ensure a bcbio-nextgen script symlink in final tool directory. | [
"Ensure",
"a",
"bcbio",
"-",
"nextgen",
"script",
"symlink",
"in",
"final",
"tool",
"directory",
"."
] | python | train | 48.5 |
churchill-lab/emase | emase/Sparse3DMatrix.py | https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/Sparse3DMatrix.py#L238-L257 | def add(self, addend_mat, axis=1):
"""
In-place addition
:param addend_mat: A matrix to be added on the Sparse3DMatrix object
:param axis: The dimension along the addend_mat is added
:return: Nothing (as it performs in-place operations)
"""
if self.finalized:
... | [
"def",
"add",
"(",
"self",
",",
"addend_mat",
",",
"axis",
"=",
"1",
")",
":",
"if",
"self",
".",
"finalized",
":",
"if",
"axis",
"==",
"0",
":",
"raise",
"NotImplementedError",
"(",
"'The method is not yet implemented for the axis.'",
")",
"elif",
"axis",
"... | In-place addition
:param addend_mat: A matrix to be added on the Sparse3DMatrix object
:param axis: The dimension along the addend_mat is added
:return: Nothing (as it performs in-place operations) | [
"In",
"-",
"place",
"addition"
] | python | valid | 42.7 |
saltstack/salt | salt/modules/boto_rds.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L603-L622 | def describe_db_subnet_groups(name=None, filters=None, jmespath='DBSubnetGroups',
region=None, key=None, keyid=None, profile=None):
'''
Return a detailed listing of some, or all, DB Subnet Groups visible in the
current scope. Arbitrary subelements or subsections of the returne... | [
"def",
"describe_db_subnet_groups",
"(",
"name",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"jmespath",
"=",
"'DBSubnetGroups'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
... | Return a detailed listing of some, or all, DB Subnet Groups visible in the
current scope. Arbitrary subelements or subsections of the returned dataset
can be selected by passing in a valid JMSEPath filter as well.
CLI example::
salt myminion boto_rds.describe_db_subnet_groups | [
"Return",
"a",
"detailed",
"listing",
"of",
"some",
"or",
"all",
"DB",
"Subnet",
"Groups",
"visible",
"in",
"the",
"current",
"scope",
".",
"Arbitrary",
"subelements",
"or",
"subsections",
"of",
"the",
"returned",
"dataset",
"can",
"be",
"selected",
"by",
"p... | python | train | 42.15 |
spyder-ide/spyder-kernels | spyder_kernels/utils/nsview.py | https://github.com/spyder-ide/spyder-kernels/blob/2c5b36cdb797b8aba77bc406ca96f5e079c4aaca/spyder_kernels/utils/nsview.py#L513-L524 | def get_type_string(item):
"""Return type string of an object."""
if isinstance(item, DataFrame):
return "DataFrame"
if isinstance(item, Index):
return type(item).__name__
if isinstance(item, Series):
return "Series"
found = re.findall(r"<(?:type|class) '(\S*)'>",
... | [
"def",
"get_type_string",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"DataFrame",
")",
":",
"return",
"\"DataFrame\"",
"if",
"isinstance",
"(",
"item",
",",
"Index",
")",
":",
"return",
"type",
"(",
"item",
")",
".",
"__name__",
"if",
... | Return type string of an object. | [
"Return",
"type",
"string",
"of",
"an",
"object",
"."
] | python | train | 32.166667 |
pyviz/holoviews | holoviews/plotting/bokeh/renderer.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/renderer.py#L320-L345 | def plot_options(cls, obj, percent_size):
"""
Given a holoviews object and a percentage size, apply heuristics
to compute a suitable figure size. For instance, scaling layouts
and grids linearly can result in unwieldy figure sizes when there
are a large number of elements. As ad ... | [
"def",
"plot_options",
"(",
"cls",
",",
"obj",
",",
"percent_size",
")",
":",
"obj",
"=",
"obj",
".",
"last",
"if",
"isinstance",
"(",
"obj",
",",
"HoloMap",
")",
"else",
"obj",
"plot",
"=",
"Store",
".",
"registry",
"[",
"cls",
".",
"backend",
"]",
... | Given a holoviews object and a percentage size, apply heuristics
to compute a suitable figure size. For instance, scaling layouts
and grids linearly can result in unwieldy figure sizes when there
are a large number of elements. As ad hoc heuristics are used,
this functionality is kept se... | [
"Given",
"a",
"holoviews",
"object",
"and",
"a",
"percentage",
"size",
"apply",
"heuristics",
"to",
"compute",
"a",
"suitable",
"figure",
"size",
".",
"For",
"instance",
"scaling",
"layouts",
"and",
"grids",
"linearly",
"can",
"result",
"in",
"unwieldy",
"figu... | python | train | 47.038462 |
AlecAivazis/graphql-over-kafka | nautilus/api/util/walk_query.py | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/api/util/walk_query.py#L1-L102 | async def walk_query(obj, object_resolver, connection_resolver, errors, current_user=None, __naut_name=None, obey_auth=True, **filters):
"""
This function traverses a query and collects the corresponding
information in a dictionary.
"""
# if the object has no selection set
if not hasattr... | [
"async",
"def",
"walk_query",
"(",
"obj",
",",
"object_resolver",
",",
"connection_resolver",
",",
"errors",
",",
"current_user",
"=",
"None",
",",
"__naut_name",
"=",
"None",
",",
"obey_auth",
"=",
"True",
",",
"*",
"*",
"filters",
")",
":",
"# if the objec... | This function traverses a query and collects the corresponding
information in a dictionary. | [
"This",
"function",
"traverses",
"a",
"query",
"and",
"collects",
"the",
"corresponding",
"information",
"in",
"a",
"dictionary",
"."
] | python | train | 36.627451 |
minimind/dispatch-on-value-for-python | dispatchonvalue/dispatchonvalue.py | https://github.com/minimind/dispatch-on-value-for-python/blob/87e510ee00948854752dfca65264a3eefda365ca/dispatchonvalue/dispatchonvalue.py#L75-L87 | def add_method(self, pattern):
"""Decorator to add new dispatch functions."""
def wrap(f):
def frozen_function(class_instance, f):
def _(pattern, *args, **kwargs):
return f(class_instance, pattern, *args, **kwargs)
return _
se... | [
"def",
"add_method",
"(",
"self",
",",
"pattern",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"def",
"frozen_function",
"(",
"class_instance",
",",
"f",
")",
":",
"def",
"_",
"(",
"pattern",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"... | Decorator to add new dispatch functions. | [
"Decorator",
"to",
"add",
"new",
"dispatch",
"functions",
"."
] | python | train | 31.230769 |
ponty/pyscreenshot | pyscreenshot/plugins/gdk3pixbuf.py | https://github.com/ponty/pyscreenshot/blob/51010195cbb5361dcd4b414ff132b87244c9e1cb/pyscreenshot/plugins/gdk3pixbuf.py#L33-L63 | def grab(self, bbox=None):
"""Grabs an image directly to a buffer.
:param bbox: Optional tuple or list containing (x1, y1, x2, y2) coordinates
of sub-region to capture.
:return: PIL RGB image
:raises: ValueError, if image data does not have 3 channels (RGB), each with 8
... | [
"def",
"grab",
"(",
"self",
",",
"bbox",
"=",
"None",
")",
":",
"w",
"=",
"Gdk",
".",
"get_default_root_window",
"(",
")",
"if",
"bbox",
"is",
"not",
"None",
":",
"g",
"=",
"[",
"bbox",
"[",
"0",
"]",
",",
"bbox",
"[",
"1",
"]",
",",
"bbox",
... | Grabs an image directly to a buffer.
:param bbox: Optional tuple or list containing (x1, y1, x2, y2) coordinates
of sub-region to capture.
:return: PIL RGB image
:raises: ValueError, if image data does not have 3 channels (RGB), each with 8
bits.
:rtype: Image | [
"Grabs",
"an",
"image",
"directly",
"to",
"a",
"buffer",
"."
] | python | valid | 42.225806 |
PythonCharmers/python-future | src/future/backports/datetime.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/datetime.py#L1470-L1493 | def replace(self, year=None, month=None, day=None, hour=None,
minute=None, second=None, microsecond=None, tzinfo=True):
"""Return a new datetime with new values for the specified fields."""
if year is None:
year = self.year
if month is None:
month = self.m... | [
"def",
"replace",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
",",
"hour",
"=",
"None",
",",
"minute",
"=",
"None",
",",
"second",
"=",
"None",
",",
"microsecond",
"=",
"None",
",",
"tzinfo",
"=",
"T... | Return a new datetime with new values for the specified fields. | [
"Return",
"a",
"new",
"datetime",
"with",
"new",
"values",
"for",
"the",
"specified",
"fields",
"."
] | python | train | 38.041667 |
Becksteinlab/GromacsWrapper | gromacs/cbook.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L644-L697 | def add_mdp_includes(topology=None, kwargs=None):
"""Set the mdp *include* key in the *kwargs* dict.
1. Add the directory containing *topology*.
2. Add all directories appearing under the key *includes*
3. Generate a string of the form "-Idir1 -Idir2 ..." that
is stored under the key *include* (... | [
"def",
"add_mdp_includes",
"(",
"topology",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"include_dirs",
"=",
"[",
"'.'",
",",
"'..'",
"]",
"# should . & .. always be added?",
"if",
"topolog... | Set the mdp *include* key in the *kwargs* dict.
1. Add the directory containing *topology*.
2. Add all directories appearing under the key *includes*
3. Generate a string of the form "-Idir1 -Idir2 ..." that
is stored under the key *include* (the corresponding
mdp parameter)
By default, ... | [
"Set",
"the",
"mdp",
"*",
"include",
"*",
"key",
"in",
"the",
"*",
"kwargs",
"*",
"dict",
"."
] | python | valid | 40.777778 |
tjvr/kurt | kurt/__init__.py | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2170-L2181 | def format(self):
"""The format of the image file.
An uppercase string corresponding to the
:attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values include
``"JPEG"`` and ``"PNG"``.
"""
if self._format:
return self._format
elif self.pil_image... | [
"def",
"format",
"(",
"self",
")",
":",
"if",
"self",
".",
"_format",
":",
"return",
"self",
".",
"_format",
"elif",
"self",
".",
"pil_image",
":",
"return",
"self",
".",
"pil_image",
".",
"format"
] | The format of the image file.
An uppercase string corresponding to the
:attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values include
``"JPEG"`` and ``"PNG"``. | [
"The",
"format",
"of",
"the",
"image",
"file",
"."
] | python | train | 29.25 |
foremast/foremast | src/foremast/consts.py | https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/consts.py#L94-L108 | def load_dynamic_config(config_file=DEFAULT_DYNAMIC_CONFIG_FILE):
"""Load and parse dynamic config"""
dynamic_configurations = {}
# Insert config path so we can import it
sys.path.insert(0, path.dirname(path.abspath(config_file)))
try:
config_module = __import__('config')
dynamic_c... | [
"def",
"load_dynamic_config",
"(",
"config_file",
"=",
"DEFAULT_DYNAMIC_CONFIG_FILE",
")",
":",
"dynamic_configurations",
"=",
"{",
"}",
"# Insert config path so we can import it",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"path",
".",
"dirname",
"(",
"path"... | Load and parse dynamic config | [
"Load",
"and",
"parse",
"dynamic",
"config"
] | python | train | 36.266667 |
allenai/allennlp | allennlp/semparse/worlds/world.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L287-L349 | def _construct_node_from_actions(self,
current_node: Tree,
remaining_actions: List[List[str]],
add_var_function: bool) -> List[List[str]]:
"""
Given a current node in the logical form tree, and... | [
"def",
"_construct_node_from_actions",
"(",
"self",
",",
"current_node",
":",
"Tree",
",",
"remaining_actions",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"add_var_function",
":",
"bool",
")",
"->",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
":... | Given a current node in the logical form tree, and a list of actions in an action sequence,
this method fills in the children of the current node from the action sequence, then
returns whatever actions are left.
For example, we could get a node with type ``c``, and an action sequence that begin... | [
"Given",
"a",
"current",
"node",
"in",
"the",
"logical",
"form",
"tree",
"and",
"a",
"list",
"of",
"actions",
"in",
"an",
"action",
"sequence",
"this",
"method",
"fills",
"in",
"the",
"children",
"of",
"the",
"current",
"node",
"from",
"the",
"action",
"... | python | train | 67.873016 |
CEA-COSMIC/ModOpt | modopt/base/np_adjust.py | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/np_adjust.py#L184-L243 | def fancy_transpose(data, roll=1):
"""Fancy transpose
This method transposes a multidimensional matrix.
Parameters
----------
data : np.ndarray
Input data array
roll : int
Roll direction and amount. Default (roll=1)
Returns
-------
np.ndarray transposed data
N... | [
"def",
"fancy_transpose",
"(",
"data",
",",
"roll",
"=",
"1",
")",
":",
"axis_roll",
"=",
"np",
".",
"roll",
"(",
"np",
".",
"arange",
"(",
"data",
".",
"ndim",
")",
",",
"roll",
")",
"return",
"np",
".",
"transpose",
"(",
"data",
",",
"axes",
"=... | Fancy transpose
This method transposes a multidimensional matrix.
Parameters
----------
data : np.ndarray
Input data array
roll : int
Roll direction and amount. Default (roll=1)
Returns
-------
np.ndarray transposed data
Notes
-----
Adjustment to numpy.tra... | [
"Fancy",
"transpose"
] | python | train | 22.216667 |
codelv/enaml-native | src/enamlnative/core/bridge.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/bridge.py#L119-L129 | def get_handler(ptr, method):
""" Dereference the pointer and return the handler method. """
obj = CACHE.get(ptr, None)
if obj is None:
raise BridgeReferenceError(
"Reference id={} never existed or has already been destroyed"
.format(ptr))
elif not hasattr(obj, method):
... | [
"def",
"get_handler",
"(",
"ptr",
",",
"method",
")",
":",
"obj",
"=",
"CACHE",
".",
"get",
"(",
"ptr",
",",
"None",
")",
"if",
"obj",
"is",
"None",
":",
"raise",
"BridgeReferenceError",
"(",
"\"Reference id={} never existed or has already been destroyed\"",
"."... | Dereference the pointer and return the handler method. | [
"Dereference",
"the",
"pointer",
"and",
"return",
"the",
"handler",
"method",
"."
] | python | train | 45.181818 |
a2liu/mr-clean | mr_clean/core/stats/transform.py | https://github.com/a2liu/mr-clean/blob/0ee4ee5639f834dec4b59b94442fa84373f3c176/mr_clean/core/stats/transform.py#L4-L21 | def normalize(df, style = 'mean'):
""" Returns a normalized version of a DataFrame or Series
Parameters:
df - DataFrame or Series
The data to normalize
style - function or string, default 'mean'
The style to use when computing the norms. Takes 'mean' or 'minmax' to
do mean or min... | [
"def",
"normalize",
"(",
"df",
",",
"style",
"=",
"'mean'",
")",
":",
"if",
"style",
"==",
"'mean'",
":",
"df_mean",
",",
"df_std",
"=",
"df",
".",
"mean",
"(",
")",
",",
"df",
".",
"std",
"(",
")",
"return",
"(",
"df",
"-",
"df_mean",
")",
"/"... | Returns a normalized version of a DataFrame or Series
Parameters:
df - DataFrame or Series
The data to normalize
style - function or string, default 'mean'
The style to use when computing the norms. Takes 'mean' or 'minmax' to
do mean or min-max normalization respectively. User-defin... | [
"Returns",
"a",
"normalized",
"version",
"of",
"a",
"DataFrame",
"or",
"Series",
"Parameters",
":",
"df",
"-",
"DataFrame",
"or",
"Series",
"The",
"data",
"to",
"normalize",
"style",
"-",
"function",
"or",
"string",
"default",
"mean",
"The",
"style",
"to",
... | python | train | 40.055556 |
cjdrake/pyeda | pyeda/boolalg/expr.py | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L956-L986 | def to_dot(self, name='EXPR'): # pragma: no cover
"""Convert to DOT language representation."""
parts = ['graph', name, '{', 'rankdir=BT;']
for ex in self.iter_dfs():
exid = ex.node.id()
if ex is Zero:
parts += ["n{} [label=0,shape=box];".format(exid)]
... | [
"def",
"to_dot",
"(",
"self",
",",
"name",
"=",
"'EXPR'",
")",
":",
"# pragma: no cover",
"parts",
"=",
"[",
"'graph'",
",",
"name",
",",
"'{'",
",",
"'rankdir=BT;'",
"]",
"for",
"ex",
"in",
"self",
".",
"iter_dfs",
"(",
")",
":",
"exid",
"=",
"ex",
... | Convert to DOT language representation. | [
"Convert",
"to",
"DOT",
"language",
"representation",
"."
] | python | train | 48.935484 |
perrygeo/python-rasterstats | src/rasterstats/main.py | https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/main.py#L34-L278 | def gen_zonal_stats(
vectors, raster,
layer=0,
band=1,
nodata=None,
affine=None,
stats=None,
all_touched=False,
categorical=False,
category_map=None,
add_stats=None,
zone_func=None,
raster_out=False,
prefix=None,
... | [
"def",
"gen_zonal_stats",
"(",
"vectors",
",",
"raster",
",",
"layer",
"=",
"0",
",",
"band",
"=",
"1",
",",
"nodata",
"=",
"None",
",",
"affine",
"=",
"None",
",",
"stats",
"=",
"None",
",",
"all_touched",
"=",
"False",
",",
"categorical",
"=",
"Fal... | Zonal statistics of raster values aggregated to vector geometries.
Parameters
----------
vectors: path to an vector source or geo-like python objects
raster: ndarray or path to a GDAL raster source
If ndarray is passed, the ``affine`` kwarg is required.
layer: int or string, optional
... | [
"Zonal",
"statistics",
"of",
"raster",
"values",
"aggregated",
"to",
"vector",
"geometries",
"."
] | python | train | 38.563265 |
googleads/googleads-python-lib | googleads/common.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/googleads/common.py#L1012-L1019 | def SetHeaders(self, soap_headers, http_headers):
"""Set the headers for the underlying client.
Args:
soap_headers: A SOAP element for the SOAP headers.
http_headers: A dictionary for the http headers.
"""
self.suds_client.set_options(soapheaders=soap_headers, headers=http_headers) | [
"def",
"SetHeaders",
"(",
"self",
",",
"soap_headers",
",",
"http_headers",
")",
":",
"self",
".",
"suds_client",
".",
"set_options",
"(",
"soapheaders",
"=",
"soap_headers",
",",
"headers",
"=",
"http_headers",
")"
] | Set the headers for the underlying client.
Args:
soap_headers: A SOAP element for the SOAP headers.
http_headers: A dictionary for the http headers. | [
"Set",
"the",
"headers",
"for",
"the",
"underlying",
"client",
"."
] | python | train | 38 |
Telefonica/toolium | toolium/config_driver.py | https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/config_driver.py#L383-L391 | def _setup_explorer(self, capabilities):
"""Setup Internet Explorer webdriver
:param capabilities: capabilities object
:returns: a new local Internet Explorer driver
"""
explorer_driver = self.config.get('Driver', 'explorer_driver_path')
self.logger.debug("Explorer drive... | [
"def",
"_setup_explorer",
"(",
"self",
",",
"capabilities",
")",
":",
"explorer_driver",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'Driver'",
",",
"'explorer_driver_path'",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Explorer driver path given in propert... | Setup Internet Explorer webdriver
:param capabilities: capabilities object
:returns: a new local Internet Explorer driver | [
"Setup",
"Internet",
"Explorer",
"webdriver"
] | python | train | 48.111111 |
swift-nav/libsbp | generator/sbpg/specs/yaml2.py | https://github.com/swift-nav/libsbp/blob/5a950608506b23e31b73ef7065da905b646055c1/generator/sbpg/specs/yaml2.py#L102-L122 | def get_files(input_file):
"""
Initializes an index of files to generate, returns the base
directory and index.
"""
file_index = {}
base_dir = None
if os.path.isfile(input_file):
file_index[input_file] = None
base_dir = os.path.dirname(input_file)
elif os.path.isdir(input_file):
base_dir = ... | [
"def",
"get_files",
"(",
"input_file",
")",
":",
"file_index",
"=",
"{",
"}",
"base_dir",
"=",
"None",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"input_file",
")",
":",
"file_index",
"[",
"input_file",
"]",
"=",
"None",
"base_dir",
"=",
"os",
".",
... | Initializes an index of files to generate, returns the base
directory and index. | [
"Initializes",
"an",
"index",
"of",
"files",
"to",
"generate",
"returns",
"the",
"base",
"directory",
"and",
"index",
"."
] | python | train | 29.142857 |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2442-L2467 | def github_gfonts_ttFont(ttFont, license):
"""Get a TTFont object of a font downloaded
from Google Fonts git repository.
"""
if not license:
return
from fontbakery.utils import download_file
from fontTools.ttLib import TTFont
from urllib.request import HTTPError
LICENSE_DIRECTORY = {
"OFL.tx... | [
"def",
"github_gfonts_ttFont",
"(",
"ttFont",
",",
"license",
")",
":",
"if",
"not",
"license",
":",
"return",
"from",
"fontbakery",
".",
"utils",
"import",
"download_file",
"from",
"fontTools",
".",
"ttLib",
"import",
"TTFont",
"from",
"urllib",
".",
"request... | Get a TTFont object of a font downloaded
from Google Fonts git repository. | [
"Get",
"a",
"TTFont",
"object",
"of",
"a",
"font",
"downloaded",
"from",
"Google",
"Fonts",
"git",
"repository",
"."
] | python | train | 28.923077 |
ethereum/py-evm | eth/vm/base.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L470-L510 | def execute_bytecode(self,
origin: Address,
gas_price: int,
gas: int,
to: Address,
sender: Address,
value: int,
data: bytes,
... | [
"def",
"execute_bytecode",
"(",
"self",
",",
"origin",
":",
"Address",
",",
"gas_price",
":",
"int",
",",
"gas",
":",
"int",
",",
"to",
":",
"Address",
",",
"sender",
":",
"Address",
",",
"value",
":",
"int",
",",
"data",
":",
"bytes",
",",
"code",
... | Execute raw bytecode in the context of the current state of
the virtual machine. | [
"Execute",
"raw",
"bytecode",
"in",
"the",
"context",
"of",
"the",
"current",
"state",
"of",
"the",
"virtual",
"machine",
"."
] | python | train | 29.512195 |
benley/butcher | butcher/targets/base.py | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/base.py#L153-L159 | def get_from_cache(self):
"""See if this rule has already been built and cached."""
for item in self.rule.output_files:
dstpath = os.path.join(self.buildroot, item)
self.linkorcopy(
self.cachemgr.path_in_cache(item, self._metahash()),
dstpath) | [
"def",
"get_from_cache",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"rule",
".",
"output_files",
":",
"dstpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"buildroot",
",",
"item",
")",
"self",
".",
"linkorcopy",
"(",
"self... | See if this rule has already been built and cached. | [
"See",
"if",
"this",
"rule",
"has",
"already",
"been",
"built",
"and",
"cached",
"."
] | python | train | 44.142857 |
Robpol86/terminaltables | terminaltables/base_table.py | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/base_table.py#L214-L217 | def table(self):
"""Return a large string of the entire table ready to be printed to the terminal."""
dimensions = max_dimensions(self.table_data, self.padding_left, self.padding_right)[:3]
return flatten(self.gen_table(*dimensions)) | [
"def",
"table",
"(",
"self",
")",
":",
"dimensions",
"=",
"max_dimensions",
"(",
"self",
".",
"table_data",
",",
"self",
".",
"padding_left",
",",
"self",
".",
"padding_right",
")",
"[",
":",
"3",
"]",
"return",
"flatten",
"(",
"self",
".",
"gen_table",
... | Return a large string of the entire table ready to be printed to the terminal. | [
"Return",
"a",
"large",
"string",
"of",
"the",
"entire",
"table",
"ready",
"to",
"be",
"printed",
"to",
"the",
"terminal",
"."
] | python | train | 63.5 |
klahnakoski/mo-logs | mo_logs/strings.py | https://github.com/klahnakoski/mo-logs/blob/0971277ac9caf28a755b766b70621916957d4fea/mo_logs/strings.py#L732-L851 | def apply_diff(text, diff, reverse=False, verify=True):
"""
SOME EXAMPLES OF diff
#@@ -1 +1 @@
#-before china goes live, the content team will have to manually update the settings for the china-ready apps currently in marketplace.
#+before china goes live (end January developer release, June general... | [
"def",
"apply_diff",
"(",
"text",
",",
"diff",
",",
"reverse",
"=",
"False",
",",
"verify",
"=",
"True",
")",
":",
"if",
"not",
"diff",
":",
"return",
"text",
"output",
"=",
"text",
"hunks",
"=",
"[",
"(",
"new_diff",
"[",
"start_hunk",
"]",
",",
"... | SOME EXAMPLES OF diff
#@@ -1 +1 @@
#-before china goes live, the content team will have to manually update the settings for the china-ready apps currently in marketplace.
#+before china goes live (end January developer release, June general audience release) , the content team will have to manually update t... | [
"SOME",
"EXAMPLES",
"OF",
"diff",
"#"
] | python | train | 44.683333 |
PmagPy/PmagPy | pmagpy/validate_upload2.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/validate_upload2.py#L27-L75 | def get_data_model():
"""
try to grab the up to date data model document from the EarthRef site.
if that fails, try to get the data model document from the PmagPy directory on the user's computer.
if that fails, return False.
data_model is a set of nested dictionaries that looks like this:
{'mag... | [
"def",
"get_data_model",
"(",
")",
":",
"#print(\"-I- getting data model, please be patient!!!!\")",
"url",
"=",
"'http://earthref.org/services/MagIC-data-model.txt'",
"offline",
"=",
"True",
"# always get cached data model, as 2.5 is now static",
"#try:",
"# data = urllib2.urlopen(ur... | try to grab the up to date data model document from the EarthRef site.
if that fails, try to get the data model document from the PmagPy directory on the user's computer.
if that fails, return False.
data_model is a set of nested dictionaries that looks like this:
{'magic_contributions':
{'group... | [
"try",
"to",
"grab",
"the",
"up",
"to",
"date",
"data",
"model",
"document",
"from",
"the",
"EarthRef",
"site",
".",
"if",
"that",
"fails",
"try",
"to",
"get",
"the",
"data",
"model",
"document",
"from",
"the",
"PmagPy",
"directory",
"on",
"the",
"user",... | python | train | 47.102041 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2733-L2772 | def upload_sticker_file(self, user_id, png_sticker):
"""
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
https://core.telegram.org/bots/api#uploadstickerfile... | [
"def",
"upload_sticker_file",
"(",
"self",
",",
"user_id",
",",
"png_sticker",
")",
":",
"from",
"pytgbot",
".",
"api_types",
".",
"sendable",
".",
"files",
"import",
"InputFile",
"assert_type_or_raise",
"(",
"user_id",
",",
"int",
",",
"parameter_name",
"=",
... | Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
https://core.telegram.org/bots/api#uploadstickerfile
Parameters:
:param user_id: User iden... | [
"Use",
"this",
"method",
"to",
"upload",
"a",
".",
"png",
"file",
"with",
"a",
"sticker",
"for",
"later",
"use",
"in",
"createNewStickerSet",
"and",
"addStickerToSet",
"methods",
"(",
"can",
"be",
"used",
"multiple",
"times",
")",
".",
"Returns",
"the",
"u... | python | train | 44.1 |
ruipgil/TrackToTrip | tracktotrip/compression.py | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/compression.py#L100-L134 | def td_sp(points, speed_threshold):
""" Top-Down Speed-Based Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
speed_threshold (float): max speed error, in ... | [
"def",
"td_sp",
"(",
"points",
",",
"speed_threshold",
")",
":",
"if",
"len",
"(",
"points",
")",
"<=",
"2",
":",
"return",
"points",
"else",
":",
"max_speed_threshold",
"=",
"0",
"found_index",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"le... | Top-Down Speed-Based Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
speed_threshold (float): max speed error, in km/h
Returns:
:obj:`list` of :ob... | [
"Top",
"-",
"Down",
"Speed",
"-",
"Based",
"Trajectory",
"Compression",
"Algorithm"
] | python | train | 36.657143 |
LucidtechAI/las-sdk-python | las/client.py | https://github.com/LucidtechAI/las-sdk-python/blob/5f39dee7983baff28a1deb93c12d36414d835d12/las/client.py#L213-L240 | def delete_consent_id(self, consent_id: str) -> dict:
"""Delete documents with this consent_id, calls the DELETE /consent/{consentId} endpoint.
>>> from las import Client
>>> client = Client(endpoint='<api endpoint>')
>>> client.delete_consent_id('<consent id>')
:param consent_... | [
"def",
"delete_consent_id",
"(",
"self",
",",
"consent_id",
":",
"str",
")",
"->",
"dict",
":",
"body",
"=",
"json",
".",
"dumps",
"(",
"{",
"}",
")",
".",
"encode",
"(",
")",
"uri",
",",
"headers",
"=",
"self",
".",
"_create_signing_headers",
"(",
"... | Delete documents with this consent_id, calls the DELETE /consent/{consentId} endpoint.
>>> from las import Client
>>> client = Client(endpoint='<api endpoint>')
>>> client.delete_consent_id('<consent id>')
:param consent_id: Delete documents with this consent_id
:type consent_i... | [
"Delete",
"documents",
"with",
"this",
"consent_id",
"calls",
"the",
"DELETE",
"/",
"consent",
"/",
"{",
"consentId",
"}",
"endpoint",
"."
] | python | train | 41.178571 |
django-leonardo/django-leonardo | leonardo/module/media/admin/folder/admin.py | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/admin/folder/admin.py#L684-L726 | def files_set_public_or_private(self, request, set_public, files_queryset, folders_queryset):
"""
Action which enables or disables permissions for selected files and files in selected folders to clipboard (set them private or public).
"""
if not self.has_change_permission(request):
... | [
"def",
"files_set_public_or_private",
"(",
"self",
",",
"request",
",",
"set_public",
",",
"files_queryset",
",",
"folders_queryset",
")",
":",
"if",
"not",
"self",
".",
"has_change_permission",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"if",
"request... | Action which enables or disables permissions for selected files and files in selected folders to clipboard (set them private or public). | [
"Action",
"which",
"enables",
"or",
"disables",
"permissions",
"for",
"selected",
"files",
"and",
"files",
"in",
"selected",
"folders",
"to",
"clipboard",
"(",
"set",
"them",
"private",
"or",
"public",
")",
"."
] | python | train | 33.418605 |
selectel/pyte | pyte/screens.py | https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L834-L847 | def ensure_vbounds(self, use_margins=None):
"""Ensure the cursor is within vertical screen bounds.
:param bool use_margins: when ``True`` or when
:data:`~pyte.modes.DECOM` is set,
cursor is bounded by top and and bottom
... | [
"def",
"ensure_vbounds",
"(",
"self",
",",
"use_margins",
"=",
"None",
")",
":",
"if",
"(",
"use_margins",
"or",
"mo",
".",
"DECOM",
"in",
"self",
".",
"mode",
")",
"and",
"self",
".",
"margins",
"is",
"not",
"None",
":",
"top",
",",
"bottom",
"=",
... | Ensure the cursor is within vertical screen bounds.
:param bool use_margins: when ``True`` or when
:data:`~pyte.modes.DECOM` is set,
cursor is bounded by top and and bottom
margins, instead of ``[0; lines - 1]``. | [
"Ensure",
"the",
"cursor",
"is",
"within",
"vertical",
"screen",
"bounds",
"."
] | python | train | 43.785714 |
helixyte/everest | everest/repositories/uow.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/repositories/uow.py#L63-L69 | def unregister(self, entity_class, entity):
"""
Unregisters the given entity for the given class and discards its
state information.
"""
EntityState.release(entity, self)
self.__entity_set_map[entity_class].remove(entity) | [
"def",
"unregister",
"(",
"self",
",",
"entity_class",
",",
"entity",
")",
":",
"EntityState",
".",
"release",
"(",
"entity",
",",
"self",
")",
"self",
".",
"__entity_set_map",
"[",
"entity_class",
"]",
".",
"remove",
"(",
"entity",
")"
] | Unregisters the given entity for the given class and discards its
state information. | [
"Unregisters",
"the",
"given",
"entity",
"for",
"the",
"given",
"class",
"and",
"discards",
"its",
"state",
"information",
"."
] | python | train | 37.571429 |
jazzband/django-axes | axes/helpers.py | https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L168-L194 | def get_client_parameters(username: str, ip_address: str, user_agent: str) -> dict:
"""
Get query parameters for filtering AccessAttempt queryset.
This method returns a dict that guarantees iteration order for keys and values,
and can so be used in e.g. the generation of hash keys or other deterministi... | [
"def",
"get_client_parameters",
"(",
"username",
":",
"str",
",",
"ip_address",
":",
"str",
",",
"user_agent",
":",
"str",
")",
"->",
"dict",
":",
"filter_kwargs",
"=",
"dict",
"(",
")",
"if",
"settings",
".",
"AXES_ONLY_USER_FAILURES",
":",
"# 1. Only individ... | Get query parameters for filtering AccessAttempt queryset.
This method returns a dict that guarantees iteration order for keys and values,
and can so be used in e.g. the generation of hash keys or other deterministic functions. | [
"Get",
"query",
"parameters",
"for",
"filtering",
"AccessAttempt",
"queryset",
"."
] | python | train | 41.259259 |
maybelinot/df2gspread | df2gspread/gfiles.py | https://github.com/maybelinot/df2gspread/blob/f4cef3800704aceff2ed08a623a594b558d44898/df2gspread/gfiles.py#L69-L86 | def get_worksheet(gc, gfile_id, wks_name, write_access=False, new_sheet_dimensions=(1000, 100)):
"""DOCS..."""
spsh = gc.open_by_key(gfile_id)
# if worksheet name is not provided , take first worksheet
if wks_name is None:
wks = spsh.sheet1
# if worksheet name provided and exist in given s... | [
"def",
"get_worksheet",
"(",
"gc",
",",
"gfile_id",
",",
"wks_name",
",",
"write_access",
"=",
"False",
",",
"new_sheet_dimensions",
"=",
"(",
"1000",
",",
"100",
")",
")",
":",
"spsh",
"=",
"gc",
".",
"open_by_key",
"(",
"gfile_id",
")",
"# if worksheet n... | DOCS... | [
"DOCS",
"..."
] | python | train | 32.166667 |
androguard/androguard | androguard/core/bytecodes/dvm.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/dvm.py#L6570-L6585 | def get_instruction(self, idx, off=None):
"""
Get a particular instruction by using (default) the index of the address if specified
:param idx: index of the instruction (the position in the list of the instruction)
:type idx: int
:param off: address of the instruction
:t... | [
"def",
"get_instruction",
"(",
"self",
",",
"idx",
",",
"off",
"=",
"None",
")",
":",
"if",
"off",
"is",
"not",
"None",
":",
"idx",
"=",
"self",
".",
"off_to_pos",
"(",
"off",
")",
"if",
"self",
".",
"cached_instructions",
"is",
"None",
":",
"self",
... | Get a particular instruction by using (default) the index of the address if specified
:param idx: index of the instruction (the position in the list of the instruction)
:type idx: int
:param off: address of the instruction
:type off: int
:rtype: an :class:`Instruction` object | [
"Get",
"a",
"particular",
"instruction",
"by",
"using",
"(",
"default",
")",
"the",
"index",
"of",
"the",
"address",
"if",
"specified"
] | python | train | 35.625 |
brunobord/meuhdb | meuhdb/core.py | https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L269-L274 | def filter(self, **kwargs):
"""
Filter data according to the given arguments.
"""
keys = self.filter_keys(**kwargs)
return self.keys_to_values(keys) | [
"def",
"filter",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"keys",
"=",
"self",
".",
"filter_keys",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"keys_to_values",
"(",
"keys",
")"
] | Filter data according to the given arguments. | [
"Filter",
"data",
"according",
"to",
"the",
"given",
"arguments",
"."
] | python | train | 30.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.