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 |
|---|---|---|---|---|---|---|---|---|---|
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_wp.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_wp.py#L230-L246 | def wp_loop(self):
'''close the loop on a mission'''
loader = self.wploader
if loader.count() < 2:
print("Not enough waypoints (%u)" % loader.count())
return
wp = loader.wp(loader.count()-2)
if wp.command == mavutil.mavlink.MAV_CMD_DO_JUMP:
pri... | [
"def",
"wp_loop",
"(",
"self",
")",
":",
"loader",
"=",
"self",
".",
"wploader",
"if",
"loader",
".",
"count",
"(",
")",
"<",
"2",
":",
"print",
"(",
"\"Not enough waypoints (%u)\"",
"%",
"loader",
".",
"count",
"(",
")",
")",
"return",
"wp",
"=",
"l... | close the loop on a mission | [
"close",
"the",
"loop",
"on",
"a",
"mission"
] | python | train | 44.705882 |
chamrc/to | to/net/resnet.py | https://github.com/chamrc/to/blob/ea1122bef08615b6c19904dadf2608e10c20c960/to/net/resnet.py#L45-L47 | def conv3x3(in_planes, out_planes, fn, stride=1):
"""3x3 convolution with padding"""
return fn(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) | [
"def",
"conv3x3",
"(",
"in_planes",
",",
"out_planes",
",",
"fn",
",",
"stride",
"=",
"1",
")",
":",
"return",
"fn",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
",",
"bias... | 3x3 convolution with padding | [
"3x3",
"convolution",
"with",
"padding"
] | python | train | 58.666667 |
novopl/peltak | src/peltak/extra/docker/client.py | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/client.py#L53-L61 | def list_images(self):
# type: () -> List[str]
""" List images stored in the registry.
Returns:
list[str]: List of image names.
"""
r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth)
return r.json()['repositories'] | [
"def",
"list_images",
"(",
"self",
")",
":",
"# type: () -> List[str]",
"r",
"=",
"self",
".",
"get",
"(",
"self",
".",
"registry_url",
"+",
"'/v2/_catalog'",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"return",
"r",
".",
"json",
"(",
")",
"[",
"'repo... | List images stored in the registry.
Returns:
list[str]: List of image names. | [
"List",
"images",
"stored",
"in",
"the",
"registry",
"."
] | python | train | 31.222222 |
okeuday/erlang_py | erlang.py | https://github.com/okeuday/erlang_py/blob/81b7c2ace66b6bdee23602a6802efff541223fa3/erlang.py#L461-L480 | def term_to_binary(term, compressed=False):
"""
Encode Python types into Erlang terms in binary data
"""
data_uncompressed = _term_to_binary(term)
if compressed is False:
return b_chr(_TAG_VERSION) + data_uncompressed
else:
if compressed is True:
compressed = 6
... | [
"def",
"term_to_binary",
"(",
"term",
",",
"compressed",
"=",
"False",
")",
":",
"data_uncompressed",
"=",
"_term_to_binary",
"(",
"term",
")",
"if",
"compressed",
"is",
"False",
":",
"return",
"b_chr",
"(",
"_TAG_VERSION",
")",
"+",
"data_uncompressed",
"else... | Encode Python types into Erlang terms in binary data | [
"Encode",
"Python",
"types",
"into",
"Erlang",
"terms",
"in",
"binary",
"data"
] | python | train | 38.65 |
apache/spark | python/pyspark/ml/param/__init__.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L350-L366 | def extractParamMap(self, extra=None):
"""
Extracts the embedded default param values and user-supplied
values, and then merges them with extra values from input into
a flat param map, where the latter value is used if there exist
conflicts, i.e., with ordering: default param val... | [
"def",
"extractParamMap",
"(",
"self",
",",
"extra",
"=",
"None",
")",
":",
"if",
"extra",
"is",
"None",
":",
"extra",
"=",
"dict",
"(",
")",
"paramMap",
"=",
"self",
".",
"_defaultParamMap",
".",
"copy",
"(",
")",
"paramMap",
".",
"update",
"(",
"se... | Extracts the embedded default param values and user-supplied
values, and then merges them with extra values from input into
a flat param map, where the latter value is used if there exist
conflicts, i.e., with ordering: default param values <
user-supplied values < extra.
:param... | [
"Extracts",
"the",
"embedded",
"default",
"param",
"values",
"and",
"user",
"-",
"supplied",
"values",
"and",
"then",
"merges",
"them",
"with",
"extra",
"values",
"from",
"input",
"into",
"a",
"flat",
"param",
"map",
"where",
"the",
"latter",
"value",
"is",
... | python | train | 37.117647 |
RPi-Distro/python-gpiozero | gpiozero/spi_devices.py | https://github.com/RPi-Distro/python-gpiozero/blob/7b67374fd0c8c4fde5586d9bad9531f076db9c0c/gpiozero/spi_devices.py#L77-L91 | def _int_to_words(self, pattern):
"""
Given a bit-pattern expressed an integer number, return a sequence of
the individual words that make up the pattern. The number of bits per
word will be obtained from the internal SPI interface.
"""
try:
bits_required = in... | [
"def",
"_int_to_words",
"(",
"self",
",",
"pattern",
")",
":",
"try",
":",
"bits_required",
"=",
"int",
"(",
"ceil",
"(",
"log",
"(",
"pattern",
",",
"2",
")",
")",
")",
"+",
"1",
"except",
"ValueError",
":",
"# pattern == 0 (technically speaking, no bits ar... | Given a bit-pattern expressed an integer number, return a sequence of
the individual words that make up the pattern. The number of bits per
word will be obtained from the internal SPI interface. | [
"Given",
"a",
"bit",
"-",
"pattern",
"expressed",
"an",
"integer",
"number",
"return",
"a",
"sequence",
"of",
"the",
"individual",
"words",
"that",
"make",
"up",
"the",
"pattern",
".",
"The",
"number",
"of",
"bits",
"per",
"word",
"will",
"be",
"obtained",... | python | train | 45.933333 |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2068-L2106 | def com_google_fonts_check_metadata_normal_style(ttFont, font_metadata):
"""METADATA.pb font.style "normal" matches font internals?"""
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import MacStyle
if font_metadata.style != "normal":
yield SKIP, "This check only applies to no... | [
"def",
"com_google_fonts_check_metadata_normal_style",
"(",
"ttFont",
",",
"font_metadata",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"from",
"fontbakery",
".",
"constants",
"import",
"MacStyle",
"if",
"font_metadata",
".",
"style... | METADATA.pb font.style "normal" matches font internals? | [
"METADATA",
".",
"pb",
"font",
".",
"style",
"normal",
"matches",
"font",
"internals?"
] | python | train | 54.25641 |
freevoid/django-datafilters | datafilters/views.py | https://github.com/freevoid/django-datafilters/blob/99051b3b3e97946981c0e9697576b0100093287c/datafilters/views.py#L33-L43 | def get_context_data(self, **kwargs):
"""
Add filter form to the context.
TODO: Currently we construct the filter form object twice - in
get_queryset and here, in get_context_data. Will need to figure out a
good way to eliminate extra initialization.
"""
context ... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"FilterFormMixin",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
"[",
"self",
".",
"context_filterform_name",
"]"... | Add filter form to the context.
TODO: Currently we construct the filter form object twice - in
get_queryset and here, in get_context_data. Will need to figure out a
good way to eliminate extra initialization. | [
"Add",
"filter",
"form",
"to",
"the",
"context",
"."
] | python | train | 41.454545 |
horazont/aioxmpp | aioxmpp/xml.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L738-L759 | def send(self, xso):
"""
Send a single XML stream object.
:param xso: Object to serialise and send.
:type xso: :class:`aioxmpp.xso.XSO`
:raises Exception: from any serialisation errors, usually
:class:`ValueError`.
Serialise the `xso` and send... | [
"def",
"send",
"(",
"self",
",",
"xso",
")",
":",
"with",
"self",
".",
"_writer",
".",
"buffer",
"(",
")",
":",
"xso",
".",
"unparse_to_sax",
"(",
"self",
".",
"_writer",
")"
] | Send a single XML stream object.
:param xso: Object to serialise and send.
:type xso: :class:`aioxmpp.xso.XSO`
:raises Exception: from any serialisation errors, usually
:class:`ValueError`.
Serialise the `xso` and send it over the stream. If any serialisation... | [
"Send",
"a",
"single",
"XML",
"stream",
"object",
"."
] | python | train | 34.090909 |
ray-project/ray | python/ray/services.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L921-L987 | def start_dashboard(redis_address,
temp_dir,
stdout_file=None,
stderr_file=None,
redis_password=None):
"""Start a dashboard process.
Args:
redis_address (str): The address of the Redis instance.
temp_dir (str): The ... | [
"def",
"start_dashboard",
"(",
"redis_address",
",",
"temp_dir",
",",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"redis_password",
"=",
"None",
")",
":",
"port",
"=",
"8080",
"while",
"True",
":",
"try",
":",
"port_test_socket",
"=",
... | Start a dashboard process.
Args:
redis_address (str): The address of the Redis instance.
temp_dir (str): The temporary directory used for log files and
information for this Ray session.
stdout_file: A file handle opened for writing to redirect stdout to. If
no redire... | [
"Start",
"a",
"dashboard",
"process",
"."
] | python | train | 34.462687 |
gwastro/pycbc | pycbc/waveform/utils.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/utils.py#L105-L127 | def phase_from_frequencyseries(htilde, remove_start_phase=True):
"""Returns the phase from the given frequency-domain waveform. This assumes
that the waveform has been sampled finely enough that the phase cannot
change by more than pi radians between each step.
Parameters
----------
htilde : Fr... | [
"def",
"phase_from_frequencyseries",
"(",
"htilde",
",",
"remove_start_phase",
"=",
"True",
")",
":",
"p",
"=",
"numpy",
".",
"unwrap",
"(",
"numpy",
".",
"angle",
"(",
"htilde",
".",
"data",
")",
")",
".",
"astype",
"(",
"real_same_precision_as",
"(",
"ht... | Returns the phase from the given frequency-domain waveform. This assumes
that the waveform has been sampled finely enough that the phase cannot
change by more than pi radians between each step.
Parameters
----------
htilde : FrequencySeries
The waveform to get the phase for; must be a compl... | [
"Returns",
"the",
"phase",
"from",
"the",
"given",
"frequency",
"-",
"domain",
"waveform",
".",
"This",
"assumes",
"that",
"the",
"waveform",
"has",
"been",
"sampled",
"finely",
"enough",
"that",
"the",
"phase",
"cannot",
"change",
"by",
"more",
"than",
"pi"... | python | train | 36.304348 |
saltstack/salt | salt/utils/context.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/context.py#L28-L61 | def func_globals_inject(func, **overrides):
'''
Override specific variables within a function's global context.
'''
# recognize methods
if hasattr(func, 'im_func'):
func = func.__func__
# Get a reference to the function globals dictionary
func_globals = func.__globals__
# Save t... | [
"def",
"func_globals_inject",
"(",
"func",
",",
"*",
"*",
"overrides",
")",
":",
"# recognize methods",
"if",
"hasattr",
"(",
"func",
",",
"'im_func'",
")",
":",
"func",
"=",
"func",
".",
"__func__",
"# Get a reference to the function globals dictionary",
"func_glob... | Override specific variables within a function's global context. | [
"Override",
"specific",
"variables",
"within",
"a",
"function",
"s",
"global",
"context",
"."
] | python | train | 31.676471 |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/datasource.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L313-L331 | def n_frames_total(self, stride=1, skip=0):
r"""Returns total number of frames.
Parameters
----------
stride : int
return value is the number of frames in trajectories when
running through them with a step size of `stride`.
skip : int, default=0
... | [
"def",
"n_frames_total",
"(",
"self",
",",
"stride",
"=",
"1",
",",
"skip",
"=",
"0",
")",
":",
"if",
"not",
"IteratorState",
".",
"is_uniform_stride",
"(",
"stride",
")",
":",
"return",
"len",
"(",
"stride",
")",
"return",
"sum",
"(",
"self",
".",
"... | r"""Returns total number of frames.
Parameters
----------
stride : int
return value is the number of frames in trajectories when
running through them with a step size of `stride`.
skip : int, default=0
skip the first initial n frames per trajectory.
... | [
"r",
"Returns",
"total",
"number",
"of",
"frames",
"."
] | python | train | 32.578947 |
PolyJIT/benchbuild | benchbuild/project.py | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/project.py#L342-L385 | def populate(projects_to_filter=None, group=None):
"""
Populate the list of projects that belong to this experiment.
Args:
projects_to_filter (list(Project)):
List of projects we want to assign to this experiment.
We intersect the list of projects with the list of supported
... | [
"def",
"populate",
"(",
"projects_to_filter",
"=",
"None",
",",
"group",
"=",
"None",
")",
":",
"if",
"projects_to_filter",
"is",
"None",
":",
"projects_to_filter",
"=",
"[",
"]",
"import",
"benchbuild",
".",
"projects",
"as",
"all_projects",
"all_projects",
"... | Populate the list of projects that belong to this experiment.
Args:
projects_to_filter (list(Project)):
List of projects we want to assign to this experiment.
We intersect the list of projects with the list of supported
projects to get the list of projects that belong to... | [
"Populate",
"the",
"list",
"of",
"projects",
"that",
"belong",
"to",
"this",
"experiment",
"."
] | python | train | 29.909091 |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L119-L133 | def copy_submission_locally(self, cloud_path):
"""Copies submission from Google Cloud Storage to local directory.
Args:
cloud_path: path of the submission in Google Cloud Storage
Returns:
name of the local file where submission is copied to
"""
local_path = os.path.join(self.download_d... | [
"def",
"copy_submission_locally",
"(",
"self",
",",
"cloud_path",
")",
":",
"local_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"download_dir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"cloud_path",
")",
")",
"cmd",
"=",
"[",
"'gs... | Copies submission from Google Cloud Storage to local directory.
Args:
cloud_path: path of the submission in Google Cloud Storage
Returns:
name of the local file where submission is copied to | [
"Copies",
"submission",
"from",
"Google",
"Cloud",
"Storage",
"to",
"local",
"directory",
"."
] | python | train | 34.533333 |
quantopian/zipline | zipline/finance/commission.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/commission.py#L364-L369 | def calculate(self, order, transaction):
"""
Pay commission based on dollar value of shares.
"""
cost_per_share = transaction.price * self.cost_per_dollar
return abs(transaction.amount) * cost_per_share | [
"def",
"calculate",
"(",
"self",
",",
"order",
",",
"transaction",
")",
":",
"cost_per_share",
"=",
"transaction",
".",
"price",
"*",
"self",
".",
"cost_per_dollar",
"return",
"abs",
"(",
"transaction",
".",
"amount",
")",
"*",
"cost_per_share"
] | Pay commission based on dollar value of shares. | [
"Pay",
"commission",
"based",
"on",
"dollar",
"value",
"of",
"shares",
"."
] | python | train | 39.5 |
ianclegg/ntlmlib | ntlmlib/authentication.py | https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L338-L376 | def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info):
"""
[MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol
3.3.2 NTLM v2 Authentication
Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and th... | [
"def",
"get_ntlmv2_response",
"(",
"domain",
",",
"user",
",",
"password",
",",
"server_challenge",
",",
"client_challenge",
",",
"timestamp",
",",
"target_info",
")",
":",
"lo_response_version",
"=",
"b'\\x01'",
"hi_response_version",
"=",
"b'\\x01'",
"reserved_dword... | [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol
3.3.2 NTLM v2 Authentication
Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse()
implementation the protocol documentation.
Note: The MS ComputeResponse() implementation refe... | [
"[",
"MS",
"-",
"NLMP",
"]",
"v20140502",
"NT",
"LAN",
"Manager",
"(",
"NTLM",
")",
"Authentication",
"Protocol",
"3",
".",
"3",
".",
"2",
"NTLM",
"v2",
"Authentication"
] | python | train | 52.74359 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_local_predict.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L175-L239 | def get_prediction_results(model_dir_or_id, data, headers, img_cols=None,
cloud=False, with_source=True, show_image=True):
""" Predict with a specified model.
It predicts with the model, join source data with prediction results, and formats
the results so they can be displayed nicely i... | [
"def",
"get_prediction_results",
"(",
"model_dir_or_id",
",",
"data",
",",
"headers",
",",
"img_cols",
"=",
"None",
",",
"cloud",
"=",
"False",
",",
"with_source",
"=",
"True",
",",
"show_image",
"=",
"True",
")",
":",
"if",
"img_cols",
"is",
"None",
":",
... | Predict with a specified model.
It predicts with the model, join source data with prediction results, and formats
the results so they can be displayed nicely in Datalab.
Args:
model_dir_or_id: The model directory if cloud is False, or model.version if cloud is True.
data: Can be a list of dictionaries, ... | [
"Predict",
"with",
"a",
"specified",
"model",
"."
] | python | train | 40.123077 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/execution_history.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/execution_history.py#L251-L265 | def get_history_item_for_tree_iter(self, child_tree_iter):
"""Hands history item for tree iter and compensate if tree item is a dummy item
:param Gtk.TreeIter child_tree_iter: Tree iter of row
:rtype rafcon.core.execution.execution_history.HistoryItem:
:return history tree item:
... | [
"def",
"get_history_item_for_tree_iter",
"(",
"self",
",",
"child_tree_iter",
")",
":",
"history_item",
"=",
"self",
".",
"history_tree_store",
"[",
"child_tree_iter",
"]",
"[",
"self",
".",
"HISTORY_ITEM_STORAGE_ID",
"]",
"if",
"history_item",
"is",
"None",
":",
... | Hands history item for tree iter and compensate if tree item is a dummy item
:param Gtk.TreeIter child_tree_iter: Tree iter of row
:rtype rafcon.core.execution.execution_history.HistoryItem:
:return history tree item: | [
"Hands",
"history",
"item",
"for",
"tree",
"iter",
"and",
"compensate",
"if",
"tree",
"item",
"is",
"a",
"dummy",
"item"
] | python | train | 56.866667 |
noahbenson/pimms | pimms/table.py | https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/table.py#L402-L432 | def itable(*args, **kwargs):
'''
itable(...) yields a new immutable table object from the given set of arguments. The arguments
may be any number of maps or itables followed by any number of keyword arguments. All the
entries from the arguments and keywords are collapsed left-to-right (respecting la... | [
"def",
"itable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# a couple things we want to check first... does our argument list reduce to just an empty",
"# itable or just a single itable?",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"and",
"len",
"(",
"kwargs"... | itable(...) yields a new immutable table object from the given set of arguments. The arguments
may be any number of maps or itables followed by any number of keyword arguments. All the
entries from the arguments and keywords are collapsed left-to-right (respecting laziness),
and the resulting column s... | [
"itable",
"(",
"...",
")",
"yields",
"a",
"new",
"immutable",
"table",
"object",
"from",
"the",
"given",
"set",
"of",
"arguments",
".",
"The",
"arguments",
"may",
"be",
"any",
"number",
"of",
"maps",
"or",
"itables",
"followed",
"by",
"any",
"number",
"o... | python | train | 50.387097 |
bunq/sdk_python | bunq/sdk/model/generated/endpoint.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L16500-L16544 | def create(cls, statement_format, date_start, date_end,
monetary_account_id=None, regional_format=None,
custom_headers=None):
"""
:type user_id: int
:type monetary_account_id: int
:param statement_format: The format type of statement. Allowed values:
... | [
"def",
"create",
"(",
"cls",
",",
"statement_format",
",",
"date_start",
",",
"date_end",
",",
"monetary_account_id",
"=",
"None",
",",
"regional_format",
"=",
"None",
",",
"custom_headers",
"=",
"None",
")",
":",
"if",
"custom_headers",
"is",
"None",
":",
"... | :type user_id: int
:type monetary_account_id: int
:param statement_format: The format type of statement. Allowed values:
MT940, CSV, PDF.
:type statement_format: str
:param date_start: The start date for making statements.
:type date_start: str
:param date_end: Th... | [
":",
"type",
"user_id",
":",
"int",
":",
"type",
"monetary_account_id",
":",
"int",
":",
"param",
"statement_format",
":",
"The",
"format",
"type",
"of",
"statement",
".",
"Allowed",
"values",
":",
"MT940",
"CSV",
"PDF",
".",
":",
"type",
"statement_format",... | python | train | 41.644444 |
ff0000/scarlet | scarlet/cms/item.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L505-L534 | def post(self, request, *args, **kwargs):
"""
Method for handling POST requests.
Validates submitted form and
formsets. Saves if valid, re displays
page with errors if invalid.
"""
self.object = self.get_object()
form_class = self.get_form_class()
... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"object",
"=",
"self",
".",
"get_object",
"(",
")",
"form_class",
"=",
"self",
".",
"get_form_class",
"(",
")",
"form",
"=",
"self",
".",
... | Method for handling POST requests.
Validates submitted form and
formsets. Saves if valid, re displays
page with errors if invalid. | [
"Method",
"for",
"handling",
"POST",
"requests",
".",
"Validates",
"submitted",
"form",
"and",
"formsets",
".",
"Saves",
"if",
"valid",
"re",
"displays",
"page",
"with",
"errors",
"if",
"invalid",
"."
] | python | train | 32.966667 |
DataKitchen/DKCloudCommand | DKCloudCommand/cli/__main__.py | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L525-L539 | def file_add(backend, kitchen, recipe, message, filepath):
"""
Add a newly created file to a Recipe
"""
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitchen is None:
raise click.ClickException(err_str)
if recipe is None:
recipe = DKRecipeDisk.find_recipe_n... | [
"def",
"file_add",
"(",
"backend",
",",
"kitchen",
",",
"recipe",
",",
"message",
",",
"filepath",
")",
":",
"err_str",
",",
"use_kitchen",
"=",
"Backend",
".",
"get_kitchen_from_user",
"(",
"kitchen",
")",
"if",
"use_kitchen",
"is",
"None",
":",
"raise",
... | Add a newly created file to a Recipe | [
"Add",
"a",
"newly",
"created",
"file",
"to",
"a",
"Recipe"
] | python | train | 47.933333 |
wrboyce/telegrambot | telegrambot/api/__init__.py | https://github.com/wrboyce/telegrambot/blob/c35ce19886df4c306a2a19851cc1f63e3066d70d/telegrambot/api/__init__.py#L85-L95 | def send_photo(self, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send photos. On success, the sent Message is returned.
"""
self.logger.info('send photo %s', photo)
payload = dict(chat_id=chat_id,
c... | [
"def",
"send_photo",
"(",
"self",
",",
"chat_id",
",",
"photo",
",",
"caption",
"=",
"None",
",",
"reply_to_message_id",
"=",
"None",
",",
"reply_markup",
"=",
"None",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'send photo %s'",
",",
"photo",
")... | Use this method to send photos. On success, the sent Message is returned. | [
"Use",
"this",
"method",
"to",
"send",
"photos",
".",
"On",
"success",
"the",
"sent",
"Message",
"is",
"returned",
"."
] | python | train | 51.454545 |
keon/algorithms | algorithms/linkedlist/add_two_numbers.py | https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/add_two_numbers.py#L66-L74 | def convert_to_str(l: Node) -> str:
"""
converts the non-negative number list into a string.
"""
result = ""
while l:
result += str(l.val)
l = l.next
return result | [
"def",
"convert_to_str",
"(",
"l",
":",
"Node",
")",
"->",
"str",
":",
"result",
"=",
"\"\"",
"while",
"l",
":",
"result",
"+=",
"str",
"(",
"l",
".",
"val",
")",
"l",
"=",
"l",
".",
"next",
"return",
"result"
] | converts the non-negative number list into a string. | [
"converts",
"the",
"non",
"-",
"negative",
"number",
"list",
"into",
"a",
"string",
"."
] | python | train | 22.111111 |
guma44/GEOparse | GEOparse/sra_downloader.py | https://github.com/guma44/GEOparse/blob/7ee8d5b8678d780382a6bf884afa69d2033f5ca0/GEOparse/sra_downloader.py#L211-L285 | def download(self):
"""Download SRA files.
Returns:
:obj:`list` of :obj:`str`: List of downloaded files.
"""
self.downloaded_paths = list()
for path in self.paths_for_download:
downloaded_path = list()
utils.mkdir_p(os.path.abspath(self.direct... | [
"def",
"download",
"(",
"self",
")",
":",
"self",
".",
"downloaded_paths",
"=",
"list",
"(",
")",
"for",
"path",
"in",
"self",
".",
"paths_for_download",
":",
"downloaded_path",
"=",
"list",
"(",
")",
"utils",
".",
"mkdir_p",
"(",
"os",
".",
"path",
".... | Download SRA files.
Returns:
:obj:`list` of :obj:`str`: List of downloaded files. | [
"Download",
"SRA",
"files",
"."
] | python | train | 39.666667 |
uchicago-cs/deepdish | deepdish/util/padding.py | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/util/padding.py#L53-L96 | def pad_to_size(data, shape, value=0.0):
"""
This is similar to `pad`, except you specify the final shape of the array.
Parameters
----------
data : ndarray
Numpy array of any dimension and type.
shape : tuple
Final shape of padded array. Should be tuple of length ``data.ndim``.... | [
"def",
"pad_to_size",
"(",
"data",
",",
"shape",
",",
"value",
"=",
"0.0",
")",
":",
"shape",
"=",
"[",
"data",
".",
"shape",
"[",
"i",
"]",
"if",
"shape",
"[",
"i",
"]",
"==",
"-",
"1",
"else",
"shape",
"[",
"i",
"]",
"for",
"i",
"in",
"rang... | This is similar to `pad`, except you specify the final shape of the array.
Parameters
----------
data : ndarray
Numpy array of any dimension and type.
shape : tuple
Final shape of padded array. Should be tuple of length ``data.ndim``.
If it has to pad unevenly, it will pad one m... | [
"This",
"is",
"similar",
"to",
"pad",
"except",
"you",
"specify",
"the",
"final",
"shape",
"of",
"the",
"array",
"."
] | python | train | 32.659091 |
Qiskit/qiskit-terra | qiskit/qasm/node/prefix.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/prefix.py#L42-L46 | def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
operation = self.children[0].operation()
expr = self.children[1].sym(nested_scope)
return operation(expr) | [
"def",
"sym",
"(",
"self",
",",
"nested_scope",
"=",
"None",
")",
":",
"operation",
"=",
"self",
".",
"children",
"[",
"0",
"]",
".",
"operation",
"(",
")",
"expr",
"=",
"self",
".",
"children",
"[",
"1",
"]",
".",
"sym",
"(",
"nested_scope",
")",
... | Return the correspond symbolic number. | [
"Return",
"the",
"correspond",
"symbolic",
"number",
"."
] | python | test | 42.4 |
saltstack/salt | salt/modules/systemd_service.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L423-L458 | def get_running():
'''
Return a list of all running services, so far as systemd is concerned
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
# Get running systemd units
out = __salt__['cmd.run'](
_systemctl_cmd('--full --no-legend --no-pa... | [
"def",
"get_running",
"(",
")",
":",
"ret",
"=",
"set",
"(",
")",
"# Get running systemd units",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"_systemctl_cmd",
"(",
"'--full --no-legend --no-pager'",
")",
",",
"python_shell",
"=",
"False",
",",
"ignore_re... | Return a list of all running services, so far as systemd is concerned
CLI Example:
.. code-block:: bash
salt '*' service.get_running | [
"Return",
"a",
"list",
"of",
"all",
"running",
"services",
"so",
"far",
"as",
"systemd",
"is",
"concerned"
] | python | train | 27.222222 |
minhhoit/yacms | yacms/accounts/__init__.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/__init__.py#L64-L75 | def get_profile_form():
"""
Returns the profile form defined by
``settings.ACCOUNTS_PROFILE_FORM_CLASS``.
"""
from yacms.conf import settings
try:
return import_dotted_path(settings.ACCOUNTS_PROFILE_FORM_CLASS)
except ImportError:
raise ImproperlyConfigured("Value for ACCOUNT... | [
"def",
"get_profile_form",
"(",
")",
":",
"from",
"yacms",
".",
"conf",
"import",
"settings",
"try",
":",
"return",
"import_dotted_path",
"(",
"settings",
".",
"ACCOUNTS_PROFILE_FORM_CLASS",
")",
"except",
"ImportError",
":",
"raise",
"ImproperlyConfigured",
"(",
... | Returns the profile form defined by
``settings.ACCOUNTS_PROFILE_FORM_CLASS``. | [
"Returns",
"the",
"profile",
"form",
"defined",
"by",
"settings",
".",
"ACCOUNTS_PROFILE_FORM_CLASS",
"."
] | python | train | 39.083333 |
saltstack/salt | salt/modules/nilrt_ip.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L731-L757 | def set_dhcp_only_all(interface):
'''
Configure specified adapter to use DHCP only
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:return: True if the settings were applied, otherwise an exception will be thr... | [
"def",
"set_dhcp_only_all",
"(",
"interface",
")",
":",
"if",
"not",
"__grains__",
"[",
"'lsb_distrib_id'",
"]",
"==",
"'nilrt'",
":",
"raise",
"salt",
".",
"exceptions",
".",
"CommandExecutionError",
"(",
"'Not supported in this version'",
")",
"initial_mode",
"=",... | Configure specified adapter to use DHCP only
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:return: True if the settings were applied, otherwise an exception will be thrown.
:rtype: bool
CLI Example:
.... | [
"Configure",
"specified",
"adapter",
"to",
"use",
"DHCP",
"only"
] | python | train | 33.407407 |
HPENetworking/PYHPEIMC | archived/pyhpimc.py | https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L441-L458 | def get_real_time_locate(ipAddress):
"""
function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the
target host is currently connected to.
:param ipAddress: str value valid IPv4 IP address
:return: dictionary containing hostIp, devId, deviceIP,... | [
"def",
"get_real_time_locate",
"(",
"ipAddress",
")",
":",
"if",
"auth",
"is",
"None",
"or",
"url",
"is",
"None",
":",
"# checks to see if the imc credentials are already available",
"set_imc_creds",
"(",
")",
"real_time_locate_url",
"=",
"\"/imcrs/res/access/realtimeLocate... | function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the
target host is currently connected to.
:param ipAddress: str value valid IPv4 IP address
:return: dictionary containing hostIp, devId, deviceIP, ifDesc, ifIndex | [
"function",
"takes",
"the",
"ipAddress",
"of",
"a",
"specific",
"host",
"and",
"issues",
"a",
"RESTFUL",
"call",
"to",
"get",
"the",
"device",
"and",
"interface",
"that",
"the",
"target",
"host",
"is",
"currently",
"connected",
"to",
".",
":",
"param",
"ip... | python | train | 48.722222 |
devopsconsulting/vdt.version | vdt/version/utils.py | https://github.com/devopsconsulting/vdt.version/blob/25854ac9e1a26f1c7d31c26fd012781f05570574/vdt/version/utils.py#L81-L97 | def change_directory(path=None):
"""
Context manager that changes directory and resets it when existing
>>> with change_directory('/tmp'):
>>> pass
"""
if path is not None:
try:
oldpwd = getcwd()
logger.debug('changing directory from %s to %s' % (oldpwd, ... | [
"def",
"change_directory",
"(",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"not",
"None",
":",
"try",
":",
"oldpwd",
"=",
"getcwd",
"(",
")",
"logger",
".",
"debug",
"(",
"'changing directory from %s to %s'",
"%",
"(",
"oldpwd",
",",
"path",
")",... | Context manager that changes directory and resets it when existing
>>> with change_directory('/tmp'):
>>> pass | [
"Context",
"manager",
"that",
"changes",
"directory",
"and",
"resets",
"it",
"when",
"existing",
">>>",
"with",
"change_directory",
"(",
"/",
"tmp",
")",
":",
">>>",
"pass"
] | python | train | 24.647059 |
ByteInternet/amqpconsumer | amqpconsumer/events.py | https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L314-L321 | def open_channel(self):
"""Open a new channel with RabbitMQ.
When RabbitMQ responds that the channel is open, the on_channel_open
callback will be invoked by pika.
"""
logger.debug('Creating new channel')
self._connection.channel(on_open_callback=self.on_channel_open) | [
"def",
"open_channel",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Creating new channel'",
")",
"self",
".",
"_connection",
".",
"channel",
"(",
"on_open_callback",
"=",
"self",
".",
"on_channel_open",
")"
] | Open a new channel with RabbitMQ.
When RabbitMQ responds that the channel is open, the on_channel_open
callback will be invoked by pika. | [
"Open",
"a",
"new",
"channel",
"with",
"RabbitMQ",
"."
] | python | train | 38.75 |
pyviz/holoviews | holoviews/core/data/__init__.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/data/__init__.py#L338-L389 | def select(self, selection_specs=None, **selection):
"""Applies selection by dimension name
Applies a selection along the dimensions of the object using
keyword arguments. The selection may be narrowed to certain
objects using selection_specs. For container objects the
selection... | [
"def",
"select",
"(",
"self",
",",
"selection_specs",
"=",
"None",
",",
"*",
"*",
"selection",
")",
":",
"if",
"selection_specs",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"selection_specs",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"s... | Applies selection by dimension name
Applies a selection along the dimensions of the object using
keyword arguments. The selection may be narrowed to certain
objects using selection_specs. For container objects the
selection will be applied to all children as well.
Selections ma... | [
"Applies",
"selection",
"by",
"dimension",
"name"
] | python | train | 37.153846 |
fusepy/fusepy | fusell.py | https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L897-L903 | def setxattr(self, req, ino, name, value, flags):
""" Set an extended attribute
Valid replies:
reply_err
"""
self.reply_err(req, errno.ENOSYS) | [
"def",
"setxattr",
"(",
"self",
",",
"req",
",",
"ino",
",",
"name",
",",
"value",
",",
"flags",
")",
":",
"self",
".",
"reply_err",
"(",
"req",
",",
"errno",
".",
"ENOSYS",
")"
] | Set an extended attribute
Valid replies:
reply_err | [
"Set",
"an",
"extended",
"attribute"
] | python | train | 25.428571 |
tensorflow/hub | tensorflow_hub/resolver.py | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L50-L80 | def tfhub_cache_dir(default_cache_dir=None, use_temp=False):
"""Returns cache directory.
Returns cache directory from either TFHUB_CACHE_DIR environment variable
or --tfhub_cache_dir or default, if set.
Args:
default_cache_dir: Default cache location to use if neither TFHUB_CACHE_DIR
... | [
"def",
"tfhub_cache_dir",
"(",
"default_cache_dir",
"=",
"None",
",",
"use_temp",
"=",
"False",
")",
":",
"# Note: We are using FLAGS[\"tfhub_cache_dir\"] (and not FLAGS.tfhub_cache_dir)",
"# to access the flag value in order to avoid parsing argv list. The flags",
"# should have been pa... | Returns cache directory.
Returns cache directory from either TFHUB_CACHE_DIR environment variable
or --tfhub_cache_dir or default, if set.
Args:
default_cache_dir: Default cache location to use if neither TFHUB_CACHE_DIR
environment variable nor --tfhub_cache_dir are
... | [
"Returns",
"cache",
"directory",
"."
] | python | train | 44.774194 |
armenzg/pulse_replay | replay/replay.py | https://github.com/armenzg/pulse_replay/blob/d3fae9f445aaaeb58d17898a597524375e9bf3ce/replay/replay.py#L30-L57 | def create_consumer(user, password, config_file_path, process_message, *args, **kwargs):
'''Create a pulse consumer. Call listen() to start listening.'''
queue_config = _read_json_file(filepath=config_file_path)
exchanges = map(lambda x: queue_config['sources'][x]['exchange'], queue_config['sources'].keys(... | [
"def",
"create_consumer",
"(",
"user",
",",
"password",
",",
"config_file_path",
",",
"process_message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queue_config",
"=",
"_read_json_file",
"(",
"filepath",
"=",
"config_file_path",
")",
"exchanges",
"=... | Create a pulse consumer. Call listen() to start listening. | [
"Create",
"a",
"pulse",
"consumer",
".",
"Call",
"listen",
"()",
"to",
"start",
"listening",
"."
] | python | train | 37.392857 |
cytoscape/py2cytoscape | py2cytoscape/cyrest/styles.py | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/styles.py#L161-L173 | def deleteMapping(self, name, vpName, verbose=None):
"""
Deletes the Visual Property mapping specified by the `vpName` and `name` parameters.
:param name: Name of the Visual Style containing the Visual Mapping
:param vpName: Name of the Visual Property that the Visual Mapping controls
... | [
"def",
"deleteMapping",
"(",
"self",
",",
"name",
",",
"vpName",
",",
"verbose",
"=",
"None",
")",
":",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"___url",
"+",
"'styles/'",
"+",
"str",
"(",
"name",
")",
"+",
"'/mappings/'",
"+",
"str",
... | Deletes the Visual Property mapping specified by the `vpName` and `name` parameters.
:param name: Name of the Visual Style containing the Visual Mapping
:param vpName: Name of the Visual Property that the Visual Mapping controls
:param verbose: print more
:returns: default: successful ... | [
"Deletes",
"the",
"Visual",
"Property",
"mapping",
"specified",
"by",
"the",
"vpName",
"and",
"name",
"parameters",
"."
] | python | train | 42.076923 |
the01/python-paps | paps/si/app/sensorServer.py | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L192-L251 | def _do_update_packet(self, packet, ip, port):
"""
React to update packet - people/person on a device have changed
:param packet: Packet from client with changes
:type packet: paps.si.app.message.APPUpdateMessage
:param ip: Client ip address
:type ip: unicode
:pa... | [
"def",
"_do_update_packet",
"(",
"self",
",",
"packet",
",",
"ip",
",",
"port",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"device_id",
"=",
"packet",
".",
"header",
".",
"device_id",
"if",
"device_id",
"<=",
"Id",
".",
"SERVER",
":",
"self",
... | React to update packet - people/person on a device have changed
:param packet: Packet from client with changes
:type packet: paps.si.app.message.APPUpdateMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: None | [
"React",
"to",
"update",
"packet",
"-",
"people",
"/",
"person",
"on",
"a",
"device",
"have",
"changed"
] | python | train | 35.466667 |
kakwa/ldapcherry | ldapcherry/__init__.py | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L92-L104 | def _get_roles(self, username):
""" Get roles of a user
@str username: name of the user
@rtype: dict, format { 'roles': [<list of roles>],
'unusedgroups': [<list of groups not matching roles>] }
"""
groups = self._get_groups(username)
user_roles = self.roles.g... | [
"def",
"_get_roles",
"(",
"self",
",",
"username",
")",
":",
"groups",
"=",
"self",
".",
"_get_groups",
"(",
"username",
")",
"user_roles",
"=",
"self",
".",
"roles",
".",
"get_roles",
"(",
"groups",
")",
"cherrypy",
".",
"log",
".",
"error",
"(",
"msg... | Get roles of a user
@str username: name of the user
@rtype: dict, format { 'roles': [<list of roles>],
'unusedgroups': [<list of groups not matching roles>] } | [
"Get",
"roles",
"of",
"a",
"user"
] | python | train | 37.923077 |
klmitch/turnstile | turnstile/compactor.py | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L99-L128 | def factory(cls, config, db):
"""
Given a configuration and database, select and return an
appropriate instance of a subclass of GetBucketKey. This will
ensure that both client and server support are available for
the Lua script feature of Redis, and if not, a lock will be
... | [
"def",
"factory",
"(",
"cls",
",",
"config",
",",
"db",
")",
":",
"# Make sure that the client supports register_script()",
"if",
"not",
"hasattr",
"(",
"db",
",",
"'register_script'",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Redis client does not support register_scrip... | Given a configuration and database, select and return an
appropriate instance of a subclass of GetBucketKey. This will
ensure that both client and server support are available for
the Lua script feature of Redis, and if not, a lock will be
used.
:param config: A dictionary of c... | [
"Given",
"a",
"configuration",
"and",
"database",
"select",
"and",
"return",
"an",
"appropriate",
"instance",
"of",
"a",
"subclass",
"of",
"GetBucketKey",
".",
"This",
"will",
"ensure",
"that",
"both",
"client",
"and",
"server",
"support",
"are",
"available",
... | python | train | 41.466667 |
chaoss/grimoirelab-perceval | perceval/backends/core/phabricator.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/phabricator.py#L484-L516 | def tasks(self, from_date=DEFAULT_DATETIME):
"""Retrieve tasks.
:param from_date: retrieve tasks that where updated from that date;
dates are converted epoch time.
"""
# Convert 'from_date' to epoch timestamp.
# Zero value (1970-01-01 00:00:00) is not allowed for
... | [
"def",
"tasks",
"(",
"self",
",",
"from_date",
"=",
"DEFAULT_DATETIME",
")",
":",
"# Convert 'from_date' to epoch timestamp.",
"# Zero value (1970-01-01 00:00:00) is not allowed for",
"# 'modifiedStart' so it will be set to 1, by default.",
"ts",
"=",
"int",
"(",
"datetime_to_utc",... | Retrieve tasks.
:param from_date: retrieve tasks that where updated from that date;
dates are converted epoch time. | [
"Retrieve",
"tasks",
"."
] | python | test | 29.242424 |
ttinies/sc2gameLobby | sc2gameLobby/debugCmds.py | https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/debugCmds.py#L10-L24 | def create(*units):
"""create this unit within the game as specified"""
ret = []
for unit in units: # implemented using sc2simulator.ScenarioUnit
x, y = unit.position[:2]
pt = Point2D(x=x, y=y)
unit.tag = 0 # forget any tag because a new unit will be created
new = DebugComman... | [
"def",
"create",
"(",
"*",
"units",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"unit",
"in",
"units",
":",
"# implemented using sc2simulator.ScenarioUnit",
"x",
",",
"y",
"=",
"unit",
".",
"position",
"[",
":",
"2",
"]",
"pt",
"=",
"Point2D",
"(",
"x",
"... | create this unit within the game as specified | [
"create",
"this",
"unit",
"within",
"the",
"game",
"as",
"specified"
] | python | train | 34.666667 |
harvard-nrg/yaxil | yaxil/commons/__init__.py | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/commons/__init__.py#L83-L91 | def which(x):
'''
Same as which command on Linux
'''
for p in os.environ.get('PATH').split(os.pathsep):
p = os.path.join(p, x)
if os.path.exists(p):
return os.path.abspath(p)
return None | [
"def",
"which",
"(",
"x",
")",
":",
"for",
"p",
"in",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
")",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"p",
",",
"x",
")",
"if",
"os",
... | Same as which command on Linux | [
"Same",
"as",
"which",
"command",
"on",
"Linux"
] | python | train | 25.111111 |
Dentosal/python-sc2 | sc2/bot_ai.py | https://github.com/Dentosal/python-sc2/blob/608bd25f04e89d39cef68b40101d8e9a8a7f1634/sc2/bot_ai.py#L468-L472 | def get_terrain_height(self, pos: Union[Point2, Point3, Unit]) -> int:
""" Returns terrain height at a position. Caution: terrain height is not anywhere near a unit's z-coordinate. """
assert isinstance(pos, (Point2, Point3, Unit))
pos = pos.position.to2.rounded
return self._game_info.te... | [
"def",
"get_terrain_height",
"(",
"self",
",",
"pos",
":",
"Union",
"[",
"Point2",
",",
"Point3",
",",
"Unit",
"]",
")",
"->",
"int",
":",
"assert",
"isinstance",
"(",
"pos",
",",
"(",
"Point2",
",",
"Point3",
",",
"Unit",
")",
")",
"pos",
"=",
"po... | Returns terrain height at a position. Caution: terrain height is not anywhere near a unit's z-coordinate. | [
"Returns",
"terrain",
"height",
"at",
"a",
"position",
".",
"Caution",
":",
"terrain",
"height",
"is",
"not",
"anywhere",
"near",
"a",
"unit",
"s",
"z",
"-",
"coordinate",
"."
] | python | train | 66.6 |
eerimoq/bincopy | bincopy.py | https://github.com/eerimoq/bincopy/blob/5e02cd001c3e9b54729425db6bffad5f03e1beac/bincopy.py#L904-L911 | def add_ihex_file(self, filename, overwrite=False):
"""Open given Intel HEX file and add its records. Set `overwrite` to
``True`` to allow already added data to be overwritten.
"""
with open(filename, 'r') as fin:
self.add_ihex(fin.read(), overwrite) | [
"def",
"add_ihex_file",
"(",
"self",
",",
"filename",
",",
"overwrite",
"=",
"False",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fin",
":",
"self",
".",
"add_ihex",
"(",
"fin",
".",
"read",
"(",
")",
",",
"overwrite",
")"
] | Open given Intel HEX file and add its records. Set `overwrite` to
``True`` to allow already added data to be overwritten. | [
"Open",
"given",
"Intel",
"HEX",
"file",
"and",
"add",
"its",
"records",
".",
"Set",
"overwrite",
"to",
"True",
"to",
"allow",
"already",
"added",
"data",
"to",
"be",
"overwritten",
"."
] | python | train | 36.125 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L137-L159 | def _get_edge_set(self, tol=0.1):
"""
Retrieve set of top edges from all of the individual surfaces,
downsampling the upper edge based on the specified tolerance
"""
edges = []
for surface in self.surfaces:
if isinstance(surface, GriddedSurface):
... | [
"def",
"_get_edge_set",
"(",
"self",
",",
"tol",
"=",
"0.1",
")",
":",
"edges",
"=",
"[",
"]",
"for",
"surface",
"in",
"self",
".",
"surfaces",
":",
"if",
"isinstance",
"(",
"surface",
",",
"GriddedSurface",
")",
":",
"return",
"edges",
".",
"append",
... | Retrieve set of top edges from all of the individual surfaces,
downsampling the upper edge based on the specified tolerance | [
"Retrieve",
"set",
"of",
"top",
"edges",
"from",
"all",
"of",
"the",
"individual",
"surfaces",
"downsampling",
"the",
"upper",
"edge",
"based",
"on",
"the",
"specified",
"tolerance"
] | python | train | 45.652174 |
gwpy/gwpy | gwpy/timeseries/statevector.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/timeseries/statevector.py#L555-L568 | def boolean(self):
"""A mapping of this `StateVector` to a 2-D array containing all
binary bits as booleans, for each time point.
"""
try:
return self._boolean
except AttributeError:
nbits = len(self.bits)
boolean = numpy.zeros((self.size, nbit... | [
"def",
"boolean",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_boolean",
"except",
"AttributeError",
":",
"nbits",
"=",
"len",
"(",
"self",
".",
"bits",
")",
"boolean",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"self",
".",
"size",
",",
... | A mapping of this `StateVector` to a 2-D array containing all
binary bits as booleans, for each time point. | [
"A",
"mapping",
"of",
"this",
"StateVector",
"to",
"a",
"2",
"-",
"D",
"array",
"containing",
"all",
"binary",
"bits",
"as",
"booleans",
"for",
"each",
"time",
"point",
"."
] | python | train | 44 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py#L417-L429 | def build_wxsfile_default_gui(root):
""" This function adds a default GUI to the wxs file
"""
factory = Document()
Product = root.getElementsByTagName('Product')[0]
UIRef = factory.createElement('UIRef')
UIRef.attributes['Id'] = 'WixUI_Mondo'
Product.childNodes.append(UIRef)
UIRef ... | [
"def",
"build_wxsfile_default_gui",
"(",
"root",
")",
":",
"factory",
"=",
"Document",
"(",
")",
"Product",
"=",
"root",
".",
"getElementsByTagName",
"(",
"'Product'",
")",
"[",
"0",
"]",
"UIRef",
"=",
"factory",
".",
"createElement",
"(",
"'UIRef'",
")",
... | This function adds a default GUI to the wxs file | [
"This",
"function",
"adds",
"a",
"default",
"GUI",
"to",
"the",
"wxs",
"file"
] | python | train | 33.230769 |
pyca/pyopenssl | src/OpenSSL/crypto.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L878-L894 | def from_cryptography(cls, crypto_req):
"""
Construct based on a ``cryptography`` *crypto_req*.
:param crypto_req: A ``cryptography`` X.509 certificate signing request
:type crypto_req: ``cryptography.x509.CertificateSigningRequest``
:rtype: X509Req
.. versionadded:: 1... | [
"def",
"from_cryptography",
"(",
"cls",
",",
"crypto_req",
")",
":",
"if",
"not",
"isinstance",
"(",
"crypto_req",
",",
"x509",
".",
"CertificateSigningRequest",
")",
":",
"raise",
"TypeError",
"(",
"\"Must be a certificate signing request\"",
")",
"req",
"=",
"cl... | Construct based on a ``cryptography`` *crypto_req*.
:param crypto_req: A ``cryptography`` X.509 certificate signing request
:type crypto_req: ``cryptography.x509.CertificateSigningRequest``
:rtype: X509Req
.. versionadded:: 17.1.0 | [
"Construct",
"based",
"on",
"a",
"cryptography",
"*",
"crypto_req",
"*",
"."
] | python | test | 31.823529 |
spacetelescope/drizzlepac | drizzlepac/hlautils/astrometric_utils.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L271-L308 | def find_gsc_offset(image, input_catalog='GSC1', output_catalog='GAIA'):
"""Find the GSC to GAIA offset based on guide star coordinates
Parameters
----------
image : str
Filename of image to be processed.
Returns
-------
delta_ra, delta_dec : tuple of floats
Offset in decim... | [
"def",
"find_gsc_offset",
"(",
"image",
",",
"input_catalog",
"=",
"'GSC1'",
",",
"output_catalog",
"=",
"'GAIA'",
")",
":",
"serviceType",
"=",
"\"GSCConvert/GSCconvert.aspx\"",
"spec_str",
"=",
"\"TRANSFORM={}-{}&IPPPSSOOT={}\"",
"if",
"'rootname'",
"in",
"pf",
".",... | Find the GSC to GAIA offset based on guide star coordinates
Parameters
----------
image : str
Filename of image to be processed.
Returns
-------
delta_ra, delta_dec : tuple of floats
Offset in decimal degrees of image based on correction to guide star
coordinates relati... | [
"Find",
"the",
"GSC",
"to",
"GAIA",
"offset",
"based",
"on",
"guide",
"star",
"coordinates"
] | python | train | 32.842105 |
pavlin-policar/openTSNE | openTSNE/tsne.py | https://github.com/pavlin-policar/openTSNE/blob/28513a0d669f2f20e7b971c0c6373dc375f72771/openTSNE/tsne.py#L598-L689 | def transform(self, X, perplexity=5, initialization="median", k=25,
learning_rate=1, n_iter=100, exaggeration=2, momentum=0):
"""Embed new points into the existing embedding.
This procedure optimizes each point only with respect to the existing
embedding i.e. it ignores any in... | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"perplexity",
"=",
"5",
",",
"initialization",
"=",
"\"median\"",
",",
"k",
"=",
"25",
",",
"learning_rate",
"=",
"1",
",",
"n_iter",
"=",
"100",
",",
"exaggeration",
"=",
"2",
",",
"momentum",
"=",
"0"... | Embed new points into the existing embedding.
This procedure optimizes each point only with respect to the existing
embedding i.e. it ignores any interactions between the points in ``X``
among themselves.
Please see the :ref:`parameter-guide` for more information.
Parameters
... | [
"Embed",
"new",
"points",
"into",
"the",
"existing",
"embedding",
"."
] | python | train | 41.228261 |
adaptive-learning/proso-apps | proso/models/environment.py | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/models/environment.py#L18-L38 | def process_answer(self, user, item, asked, answered, time, answer, response_time, guess, **kwargs):
"""
This method is used during the answer streaming and is called after the
predictive model for each answer.
Args:
user (int):
identifier of ther user answer... | [
"def",
"process_answer",
"(",
"self",
",",
"user",
",",
"item",
",",
"asked",
",",
"answered",
",",
"time",
",",
"answer",
",",
"response_time",
",",
"guess",
",",
"*",
"*",
"kwargs",
")",
":",
"pass"
] | This method is used during the answer streaming and is called after the
predictive model for each answer.
Args:
user (int):
identifier of ther user answering the question
asked (int):
identifier of the asked item
answered (int):
... | [
"This",
"method",
"is",
"used",
"during",
"the",
"answer",
"streaming",
"and",
"is",
"called",
"after",
"the",
"predictive",
"model",
"for",
"each",
"answer",
"."
] | python | train | 39.333333 |
m32/endesive | endesive/pdf/fpdf/fpdf.py | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L637-L641 | def link(self, x,y,w,h,link):
"Put a link on the page"
if not self.page in self.page_links:
self.page_links[self.page] = []
self.page_links[self.page] += [(x*self.k,self.h_pt-y*self.k,w*self.k,h*self.k,link),] | [
"def",
"link",
"(",
"self",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"link",
")",
":",
"if",
"not",
"self",
".",
"page",
"in",
"self",
".",
"page_links",
":",
"self",
".",
"page_links",
"[",
"self",
".",
"page",
"]",
"=",
"[",
"]",
"self"... | Put a link on the page | [
"Put",
"a",
"link",
"on",
"the",
"page"
] | python | train | 48.2 |
zxylvlp/PingPHP | pingphp/grammar.py | https://github.com/zxylvlp/PingPHP/blob/2e9a5f1ef4b5b13310e3f8ff350fa91032357bc5/pingphp/grammar.py#L704-L714 | def p_Callable(p):
'''
Callable : NsContentName LPARENT
| NsContentName SCOPEOP INDENTIFIER LPARENT
| Expression LPARENT
| STATIC SCOPEOP INDENTIFIER LPARENT
'''
if len(p) <= 3:
p[0] = Callable(p[1], None)
else:
p[0] = Callable(p[1], p[3]) | [
"def",
"p_Callable",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"<=",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"Callable",
"(",
"p",
"[",
"1",
"]",
",",
"None",
")",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"Callable",
"(",
"p",
"[",
"1",
"... | Callable : NsContentName LPARENT
| NsContentName SCOPEOP INDENTIFIER LPARENT
| Expression LPARENT
| STATIC SCOPEOP INDENTIFIER LPARENT | [
"Callable",
":",
"NsContentName",
"LPARENT",
"|",
"NsContentName",
"SCOPEOP",
"INDENTIFIER",
"LPARENT",
"|",
"Expression",
"LPARENT",
"|",
"STATIC",
"SCOPEOP",
"INDENTIFIER",
"LPARENT"
] | python | train | 27.636364 |
rsteca/sklearn-deap | evolutionary_search/cv.py | https://github.com/rsteca/sklearn-deap/blob/b7ee1722a40cc0c6550d32a2714ab220db2b7430/evolutionary_search/cv.py#L80-L117 | def _evalFunction(individual, name_values, X, y, scorer, cv, iid, fit_params,
verbose=0, error_score='raise', score_cache={}):
""" Developer Note:
--------------------
score_cache was purposefully moved to parameters, and given a dict reference.
It will be modified in-place... | [
"def",
"_evalFunction",
"(",
"individual",
",",
"name_values",
",",
"X",
",",
"y",
",",
"scorer",
",",
"cv",
",",
"iid",
",",
"fit_params",
",",
"verbose",
"=",
"0",
",",
"error_score",
"=",
"'raise'",
",",
"score_cache",
"=",
"{",
"}",
")",
":",
"pa... | Developer Note:
--------------------
score_cache was purposefully moved to parameters, and given a dict reference.
It will be modified in-place by _evalFunction based on it's reference.
This is to allow for a managed, paralell memoization dict,
and also for different memoization ... | [
"Developer",
"Note",
":",
"--------------------",
"score_cache",
"was",
"purposefully",
"moved",
"to",
"parameters",
"and",
"given",
"a",
"dict",
"reference",
".",
"It",
"will",
"be",
"modified",
"in",
"-",
"place",
"by",
"_evalFunction",
"based",
"on",
"it",
... | python | train | 44.921053 |
nameko/nameko | nameko/rpc.py | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/rpc.py#L82-L98 | def unregister_provider(self, provider):
""" Unregister a provider.
Blocks until this RpcConsumer is unregistered from its QueueConsumer,
which only happens when all providers have asked to unregister.
"""
self._unregistering_providers.add(provider)
remaining_providers =... | [
"def",
"unregister_provider",
"(",
"self",
",",
"provider",
")",
":",
"self",
".",
"_unregistering_providers",
".",
"add",
"(",
"provider",
")",
"remaining_providers",
"=",
"self",
".",
"_providers",
"-",
"self",
".",
"_unregistering_providers",
"if",
"not",
"re... | Unregister a provider.
Blocks until this RpcConsumer is unregistered from its QueueConsumer,
which only happens when all providers have asked to unregister. | [
"Unregister",
"a",
"provider",
"."
] | python | train | 49.117647 |
BlueBrain/NeuroM | neurom/apps/morph_stats.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/apps/morph_stats.py#L103-L113 | def get_header(results):
'''Extracts the headers, using the first value in the dict as the template'''
ret = ['name', ]
values = next(iter(results.values()))
for k, v in values.items():
if isinstance(v, dict):
for metric in v.keys():
ret.append('%s:%s' % (k, metric))
... | [
"def",
"get_header",
"(",
"results",
")",
":",
"ret",
"=",
"[",
"'name'",
",",
"]",
"values",
"=",
"next",
"(",
"iter",
"(",
"results",
".",
"values",
"(",
")",
")",
")",
"for",
"k",
",",
"v",
"in",
"values",
".",
"items",
"(",
")",
":",
"if",
... | Extracts the headers, using the first value in the dict as the template | [
"Extracts",
"the",
"headers",
"using",
"the",
"first",
"value",
"in",
"the",
"dict",
"as",
"the",
"template"
] | python | train | 33.090909 |
trendels/rhino | rhino/util.py | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/util.py#L23-L43 | def sse_event(event=None, data=None, id=None, retry=None, comment=None,
encoding='utf-8'):
"""Encode a Server-Sent Event (SSE).
At least one field must be present. All fields are strings, except retry,
which must be an integer. The event and id fields can not contain newlines.
"""
if all(x ... | [
"def",
"sse_event",
"(",
"event",
"=",
"None",
",",
"data",
"=",
"None",
",",
"id",
"=",
"None",
",",
"retry",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"all",
"(",
"x",
"is",
"None",
"for",
"x",
... | Encode a Server-Sent Event (SSE).
At least one field must be present. All fields are strings, except retry,
which must be an integer. The event and id fields can not contain newlines. | [
"Encode",
"a",
"Server",
"-",
"Sent",
"Event",
"(",
"SSE",
")",
"."
] | python | train | 49.428571 |
saltstack/salt | salt/utils/error.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/error.py#L16-L33 | def raise_error(name=None, args=None, message=''):
'''
Raise an exception with __name__ from name, args from args
If args is None Otherwise message from message\
If name is empty then use "Exception"
'''
name = name or 'Exception'
if hasattr(salt.exceptions, name):
ex = getattr(salt.... | [
"def",
"raise_error",
"(",
"name",
"=",
"None",
",",
"args",
"=",
"None",
",",
"message",
"=",
"''",
")",
":",
"name",
"=",
"name",
"or",
"'Exception'",
"if",
"hasattr",
"(",
"salt",
".",
"exceptions",
",",
"name",
")",
":",
"ex",
"=",
"getattr",
"... | Raise an exception with __name__ from name, args from args
If args is None Otherwise message from message\
If name is empty then use "Exception" | [
"Raise",
"an",
"exception",
"with",
"__name__",
"from",
"name",
"args",
"from",
"args",
"If",
"args",
"is",
"None",
"Otherwise",
"message",
"from",
"message",
"\\",
"If",
"name",
"is",
"empty",
"then",
"use",
"Exception"
] | python | train | 31.388889 |
abe-winter/pg13-py | pg13/syncschema.py | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/syncschema.py#L52-L61 | def detect_change_mode(text,change):
"returns 'add' 'delete' or 'internal'. see comments to update_changes for more details."
# warning: some wacky diff logic (in python, probably in JS too) is making some adds / deletes look like replacements (see notes at bottom of diff.py)
if len(change.deltas)>1: return 'i... | [
"def",
"detect_change_mode",
"(",
"text",
",",
"change",
")",
":",
"# warning: some wacky diff logic (in python, probably in JS too) is making some adds / deletes look like replacements (see notes at bottom of diff.py)\r",
"if",
"len",
"(",
"change",
".",
"deltas",
")",
">",
"1",
... | returns 'add' 'delete' or 'internal'. see comments to update_changes for more details. | [
"returns",
"add",
"delete",
"or",
"internal",
".",
"see",
"comments",
"to",
"update_changes",
"for",
"more",
"details",
"."
] | python | train | 75.6 |
inveniosoftware/invenio-search | invenio_search/cli.py | https://github.com/inveniosoftware/invenio-search/blob/19c073d608d4c811f1c5aecb6622402d39715228/invenio_search/cli.py#L124-L153 | def list_cmd(only_active, only_aliases, verbose):
"""List indices."""
def _tree_print(d, rec_list=None, verbose=False, indent=2):
# Note that on every recursion rec_list is copied,
# which might not be very effective for very deep dictionaries.
rec_list = rec_list or []
for idx, ... | [
"def",
"list_cmd",
"(",
"only_active",
",",
"only_aliases",
",",
"verbose",
")",
":",
"def",
"_tree_print",
"(",
"d",
",",
"rec_list",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"indent",
"=",
"2",
")",
":",
"# Note that on every recursion rec_list is cop... | List indices. | [
"List",
"indices",
"."
] | python | train | 44.866667 |
ntoll/microfs | microfs.py | https://github.com/ntoll/microfs/blob/11387109cfc36aaddceb018596ea75d55417ca0c/microfs.py#L122-L158 | def execute(commands, serial=None):
"""
Sends the command to the connected micro:bit via serial and returns the
result. If no serial connection is provided, attempts to autodetect the
device.
For this to work correctly, a particular sequence of commands needs to be
sent to put the device into a... | [
"def",
"execute",
"(",
"commands",
",",
"serial",
"=",
"None",
")",
":",
"close_serial",
"=",
"False",
"if",
"serial",
"is",
"None",
":",
"serial",
"=",
"get_serial",
"(",
")",
"close_serial",
"=",
"True",
"time",
".",
"sleep",
"(",
"0.1",
")",
"result... | Sends the command to the connected micro:bit via serial and returns the
result. If no serial connection is provided, attempts to autodetect the
device.
For this to work correctly, a particular sequence of commands needs to be
sent to put the device into a good state to process the incoming command.
... | [
"Sends",
"the",
"command",
"to",
"the",
"connected",
"micro",
":",
"bit",
"via",
"serial",
"and",
"returns",
"the",
"result",
".",
"If",
"no",
"serial",
"connection",
"is",
"provided",
"attempts",
"to",
"autodetect",
"the",
"device",
"."
] | python | train | 33.864865 |
RI-imaging/nrefocus | nrefocus/pad.py | https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/pad.py#L147-L182 | def pad_rem(pv, size=None):
""" Removes linear padding from array
This is a convenience function that does the opposite
of `pad_add`.
Parameters
----------
pv : 1D or 2D ndarray
The array from which the padding will be removed.
size : tuple of length 1 (1D) or 2 (2D), optional
... | [
"def",
"pad_rem",
"(",
"pv",
",",
"size",
"=",
"None",
")",
":",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"list",
"(",
")",
"for",
"s",
"in",
"pv",
".",
"shape",
":",
"assert",
"s",
"%",
"2",
"==",
"0",
",",
"\"Uneven size; specify correct siz... | Removes linear padding from array
This is a convenience function that does the opposite
of `pad_add`.
Parameters
----------
pv : 1D or 2D ndarray
The array from which the padding will be removed.
size : tuple of length 1 (1D) or 2 (2D), optional
The final size of the un-padded ... | [
"Removes",
"linear",
"padding",
"from",
"array"
] | python | train | 28.055556 |
vpelletier/python-libusb1 | usb1/__init__.py | https://github.com/vpelletier/python-libusb1/blob/740c9778e28523e4ec3543415d95f5400ae0fa24/usb1/__init__.py#L712-L740 | def getISOSetupList(self):
"""
Get individual ISO transfer's setup.
Returns a list of dicts, each containing an individual ISO transfer
parameters:
- length
- actual_length
- status
(see libusb1's API documentation for their signification)
Returned... | [
"def",
"getISOSetupList",
"(",
"self",
")",
":",
"transfer_p",
"=",
"self",
".",
"__transfer",
"transfer",
"=",
"transfer_p",
".",
"contents",
"# pylint: disable=undefined-variable",
"if",
"transfer",
".",
"type",
"!=",
"TRANSFER_TYPE_ISOCHRONOUS",
":",
"# pylint: ena... | Get individual ISO transfer's setup.
Returns a list of dicts, each containing an individual ISO transfer
parameters:
- length
- actual_length
- status
(see libusb1's API documentation for their signification)
Returned list is consistent with getISOBufferList retur... | [
"Get",
"individual",
"ISO",
"transfer",
"s",
"setup",
".",
"Returns",
"a",
"list",
"of",
"dicts",
"each",
"containing",
"an",
"individual",
"ISO",
"transfer",
"parameters",
":",
"-",
"length",
"-",
"actual_length",
"-",
"status",
"(",
"see",
"libusb1",
"s",
... | python | train | 35.310345 |
BlueBrain/hpcbench | hpcbench/benchmark/ior.py | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/ior.py#L244-L256 | def sizes(self):
"""Provides block_size and transfer_size through a list
of dict, for instance: [{'transfer': '1M 4M', 'block': '8M'}]
"""
if self.attributes.get('sizes'):
for settings in self.attributes.get('sizes'):
for pair in itertools.product(
... | [
"def",
"sizes",
"(",
"self",
")",
":",
"if",
"self",
".",
"attributes",
".",
"get",
"(",
"'sizes'",
")",
":",
"for",
"settings",
"in",
"self",
".",
"attributes",
".",
"get",
"(",
"'sizes'",
")",
":",
"for",
"pair",
"in",
"itertools",
".",
"product",
... | Provides block_size and transfer_size through a list
of dict, for instance: [{'transfer': '1M 4M', 'block': '8M'}] | [
"Provides",
"block_size",
"and",
"transfer_size",
"through",
"a",
"list",
"of",
"dict",
"for",
"instance",
":",
"[",
"{",
"transfer",
":",
"1M",
"4M",
"block",
":",
"8M",
"}",
"]"
] | python | train | 42.538462 |
CellProfiler/centrosome | centrosome/threshold.py | https://github.com/CellProfiler/centrosome/blob/7bd9350a2d4ae1b215b81eabcecfe560bbb1f32a/centrosome/threshold.py#L587-L625 | def get_kapur_threshold(image, mask=None):
"""The Kapur, Sahoo, & Wong method of thresholding, adapted to log-space."""
cropped_image = np.array(image.flat) if mask is None else image[mask]
if np.product(cropped_image.shape)<3:
return 0
if np.min(cropped_image) == np.max(cropped_image):
... | [
"def",
"get_kapur_threshold",
"(",
"image",
",",
"mask",
"=",
"None",
")",
":",
"cropped_image",
"=",
"np",
".",
"array",
"(",
"image",
".",
"flat",
")",
"if",
"mask",
"is",
"None",
"else",
"image",
"[",
"mask",
"]",
"if",
"np",
".",
"product",
"(",
... | The Kapur, Sahoo, & Wong method of thresholding, adapted to log-space. | [
"The",
"Kapur",
"Sahoo",
"&",
"Wong",
"method",
"of",
"thresholding",
"adapted",
"to",
"log",
"-",
"space",
"."
] | python | train | 42.923077 |
jalanb/pysyte | pysyte/decorators.py | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/decorators.py#L6-L16 | def _represent_arguments(*arguments, **keyword_arguments):
"""Represent the aruments in a form suitable as a key (hashable)
And which will be recognisable to user in error messages
>>> print(_represent_arguments([1, 2], **{'fred':'here'}))
[1, 2], fred='here'
"""
argument_strings = [repr(a) for... | [
"def",
"_represent_arguments",
"(",
"*",
"arguments",
",",
"*",
"*",
"keyword_arguments",
")",
":",
"argument_strings",
"=",
"[",
"repr",
"(",
"a",
")",
"for",
"a",
"in",
"arguments",
"]",
"keyword_strings",
"=",
"[",
"'='",
".",
"join",
"(",
"(",
"k",
... | Represent the aruments in a form suitable as a key (hashable)
And which will be recognisable to user in error messages
>>> print(_represent_arguments([1, 2], **{'fred':'here'}))
[1, 2], fred='here' | [
"Represent",
"the",
"aruments",
"in",
"a",
"form",
"suitable",
"as",
"a",
"key",
"(",
"hashable",
")"
] | python | train | 43.363636 |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L252-L295 | def decode_value(value, client):
"""Converts a Firestore protobuf ``Value`` to a native Python value.
Args:
value (google.cloud.firestore_v1beta1.types.Value): A
Firestore protobuf to be decoded / parsed / converted.
client (~.firestore_v1beta1.client.Client): A client that has
... | [
"def",
"decode_value",
"(",
"value",
",",
"client",
")",
":",
"value_type",
"=",
"value",
".",
"WhichOneof",
"(",
"\"value_type\"",
")",
"if",
"value_type",
"==",
"\"null_value\"",
":",
"return",
"None",
"elif",
"value_type",
"==",
"\"boolean_value\"",
":",
"r... | Converts a Firestore protobuf ``Value`` to a native Python value.
Args:
value (google.cloud.firestore_v1beta1.types.Value): A
Firestore protobuf to be decoded / parsed / converted.
client (~.firestore_v1beta1.client.Client): A client that has
a document factory.
Returns... | [
"Converts",
"a",
"Firestore",
"protobuf",
"Value",
"to",
"a",
"native",
"Python",
"value",
"."
] | python | train | 40.659091 |
epio/mantrid | mantrid/actions.py | https://github.com/epio/mantrid/blob/1c699f1a4b33888b533c19cb6d025173f2160576/mantrid/actions.py#L140-L159 | def handle(self, sock, read_data, path, headers):
"Sends back a static error page."
for i in range(self.attempts):
try:
server_sock = eventlet.connect(
tuple(random.choice(self.backends)),
)
except socket.error:
... | [
"def",
"handle",
"(",
"self",
",",
"sock",
",",
"read_data",
",",
"path",
",",
"headers",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"attempts",
")",
":",
"try",
":",
"server_sock",
"=",
"eventlet",
".",
"connect",
"(",
"tuple",
"(",
"r... | Sends back a static error page. | [
"Sends",
"back",
"a",
"static",
"error",
"page",
"."
] | python | train | 37.1 |
jciskey/pygraph | pygraph/functions/planarity/kocay_algorithm.py | https://github.com/jciskey/pygraph/blob/037bb2f32503fecb60d62921f9766d54109f15e2/pygraph/functions/planarity/kocay_algorithm.py#L183-L209 | def __embed_branch(dfs_data):
"""Builds the combinatorial embedding of the graph. Returns whether the graph is planar."""
u = dfs_data['ordering'][0]
dfs_data['LF'] = []
dfs_data['RF'] = []
dfs_data['FG'] = {}
n = dfs_data['graph'].num_nodes()
f0 = (0, n)
g0 = (0, n)
L0 = {'u': 0, 'v... | [
"def",
"__embed_branch",
"(",
"dfs_data",
")",
":",
"u",
"=",
"dfs_data",
"[",
"'ordering'",
"]",
"[",
"0",
"]",
"dfs_data",
"[",
"'LF'",
"]",
"=",
"[",
"]",
"dfs_data",
"[",
"'RF'",
"]",
"=",
"[",
"]",
"dfs_data",
"[",
"'FG'",
"]",
"=",
"{",
"}"... | Builds the combinatorial embedding of the graph. Returns whether the graph is planar. | [
"Builds",
"the",
"combinatorial",
"embedding",
"of",
"the",
"graph",
".",
"Returns",
"whether",
"the",
"graph",
"is",
"planar",
"."
] | python | train | 28.814815 |
openego/ding0 | ding0/core/__init__.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/core/__init__.py#L781-L985 | def import_generators(self, session, debug=False):
"""
Imports renewable (res) and conventional (conv) generators
Args:
session : sqlalchemy.orm.session.Session
Database session
debug: If True, information is printed during process
Notes:
... | [
"def",
"import_generators",
"(",
"self",
",",
"session",
",",
"debug",
"=",
"False",
")",
":",
"def",
"import_res_generators",
"(",
")",
":",
"\"\"\"Imports renewable (res) generators\"\"\"",
"# build query",
"generators_sqla",
"=",
"session",
".",
"query",
"(",
"se... | Imports renewable (res) and conventional (conv) generators
Args:
session : sqlalchemy.orm.session.Session
Database session
debug: If True, information is printed during process
Notes:
Connection of generators is done later on in NetworkDing0's method ... | [
"Imports",
"renewable",
"(",
"res",
")",
"and",
"conventional",
"(",
"conv",
")",
"generators"
] | python | train | 46.6 |
quiltdata/quilt | registry/quilt_server/views.py | https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/registry/quilt_server/views.py#L566-L578 | def _private_packages_allowed():
"""
Checks if the current user is allowed to create private packages.
In the public cloud, the user needs to be on a paid plan.
There are no restrictions in other deployments.
"""
if not HAVE_PAYMENTS or TEAM_ID:
return True
customer = _get_or_creat... | [
"def",
"_private_packages_allowed",
"(",
")",
":",
"if",
"not",
"HAVE_PAYMENTS",
"or",
"TEAM_ID",
":",
"return",
"True",
"customer",
"=",
"_get_or_create_customer",
"(",
")",
"plan",
"=",
"_get_customer_plan",
"(",
"customer",
")",
"return",
"plan",
"!=",
"Payme... | Checks if the current user is allowed to create private packages.
In the public cloud, the user needs to be on a paid plan.
There are no restrictions in other deployments. | [
"Checks",
"if",
"the",
"current",
"user",
"is",
"allowed",
"to",
"create",
"private",
"packages",
"."
] | python | train | 30.461538 |
shaunduncan/nosqlite | nosqlite.py | https://github.com/shaunduncan/nosqlite/blob/3033c029b7c8290c66a8b36dc512e560505d4c85/nosqlite.py#L471-L479 | def _lte(field, value, document):
"""
Returns True if the value of a document field is less than or
equal to a given value
"""
try:
return document.get(field, None) <= value
except TypeError: # pragma: no cover Python < 3.0
return False | [
"def",
"_lte",
"(",
"field",
",",
"value",
",",
"document",
")",
":",
"try",
":",
"return",
"document",
".",
"get",
"(",
"field",
",",
"None",
")",
"<=",
"value",
"except",
"TypeError",
":",
"# pragma: no cover Python < 3.0",
"return",
"False"
] | Returns True if the value of a document field is less than or
equal to a given value | [
"Returns",
"True",
"if",
"the",
"value",
"of",
"a",
"document",
"field",
"is",
"less",
"than",
"or",
"equal",
"to",
"a",
"given",
"value"
] | python | train | 29.888889 |
bitesofcode/projexui | projexui/xcolorset.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xcolorset.py#L35-L51 | def color( self, name, colorGroup = None ):
"""
Returns the color for the given name at the inputed group. If no \
group is specified, the first group in the list is used.
:param name | <str>
colorGroup | <str> || None
:retu... | [
"def",
"color",
"(",
"self",
",",
"name",
",",
"colorGroup",
"=",
"None",
")",
":",
"if",
"(",
"not",
"colorGroup",
"and",
"self",
".",
"_colorGroups",
")",
":",
"colorGroup",
"=",
"self",
".",
"_colorGroups",
"[",
"0",
"]",
"if",
"(",
"not",
"colorG... | Returns the color for the given name at the inputed group. If no \
group is specified, the first group in the list is used.
:param name | <str>
colorGroup | <str> || None
:return <QColor> | [
"Returns",
"the",
"color",
"for",
"the",
"given",
"name",
"at",
"the",
"inputed",
"group",
".",
"If",
"no",
"\\",
"group",
"is",
"specified",
"the",
"first",
"group",
"in",
"the",
"list",
"is",
"used",
".",
":",
"param",
"name",
"|",
"<str",
">",
"co... | python | train | 34.411765 |
MisterY/asset-allocation | asset_allocation/maps.py | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L87-L108 | def __get_stock_row(self, stock: Stock, depth: int) -> str:
""" formats stock row """
assert isinstance(stock, Stock)
view_model = AssetAllocationViewModel()
view_model.depth = depth
# Symbol
view_model.name = stock.symbol
# Current allocation
view_mod... | [
"def",
"__get_stock_row",
"(",
"self",
",",
"stock",
":",
"Stock",
",",
"depth",
":",
"int",
")",
"->",
"str",
":",
"assert",
"isinstance",
"(",
"stock",
",",
"Stock",
")",
"view_model",
"=",
"AssetAllocationViewModel",
"(",
")",
"view_model",
".",
"depth"... | formats stock row | [
"formats",
"stock",
"row"
] | python | train | 27.5 |
xen/webcraft | webcraft/apiview.py | https://github.com/xen/webcraft/blob/74ff1e5b253048d9260446bfbc95de2e402a8005/webcraft/apiview.py#L10-L15 | def alchemyencoder(obj):
"""JSON encoder function for SQLAlchemy special classes."""
if isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):
return float(obj) | [
"def",
"alchemyencoder",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"date",
")",
":",
"return",
"obj",
".",
"isoformat",
"(",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"decimal",
".",
"Decimal",
")",
":",
"return",
... | JSON encoder function for SQLAlchemy special classes. | [
"JSON",
"encoder",
"function",
"for",
"SQLAlchemy",
"special",
"classes",
"."
] | python | train | 37 |
facebook/pyre-check | sapp/sapp/cli_lib.py | https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/cli_lib.py#L33-L52 | def require_option(current_ctx: click.Context, param_name: str) -> None:
"""Throw an exception if an option wasn't required. This is useful when its
optional in some contexts but required for a subcommand"""
ctx = current_ctx
param_definition = None
while ctx is not None:
# ctx.command.para... | [
"def",
"require_option",
"(",
"current_ctx",
":",
"click",
".",
"Context",
",",
"param_name",
":",
"str",
")",
"->",
"None",
":",
"ctx",
"=",
"current_ctx",
"param_definition",
"=",
"None",
"while",
"ctx",
"is",
"not",
"None",
":",
"# ctx.command.params has th... | Throw an exception if an option wasn't required. This is useful when its
optional in some contexts but required for a subcommand | [
"Throw",
"an",
"exception",
"if",
"an",
"option",
"wasn",
"t",
"required",
".",
"This",
"is",
"useful",
"when",
"its",
"optional",
"in",
"some",
"contexts",
"but",
"required",
"for",
"a",
"subcommand"
] | python | train | 40.65 |
google/grr | grr/core/grr_response_core/lib/util/compat/yaml.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/util/compat/yaml.py#L127-L143 | def DumpMany(objs):
"""Stringifies a sequence of Python objects to a multi-document YAML.
Args:
objs: An iterable of Python objects to convert to YAML.
Returns:
A multi-document YAML representation of the given objects.
"""
precondition.AssertIterableType(objs, object)
text = yaml.safe_dump_all(o... | [
"def",
"DumpMany",
"(",
"objs",
")",
":",
"precondition",
".",
"AssertIterableType",
"(",
"objs",
",",
"object",
")",
"text",
"=",
"yaml",
".",
"safe_dump_all",
"(",
"objs",
",",
"default_flow_style",
"=",
"False",
",",
"allow_unicode",
"=",
"True",
")",
"... | Stringifies a sequence of Python objects to a multi-document YAML.
Args:
objs: An iterable of Python objects to convert to YAML.
Returns:
A multi-document YAML representation of the given objects. | [
"Stringifies",
"a",
"sequence",
"of",
"Python",
"objects",
"to",
"a",
"multi",
"-",
"document",
"YAML",
"."
] | python | train | 25.058824 |
dcaune/perseus-lib-python-common | majormode/perseus/utils/rdbms.py | https://github.com/dcaune/perseus-lib-python-common/blob/ba48fe0fd9bb4a75b53e7d10c41ada36a72d4496/majormode/perseus/utils/rdbms.py#L486-L590 | def execute(self, sql_statement, parameters=None):
"""
Execute the specified Structured Query Language (SQL) parameterized
statement.
@note: each result column MUST be named with distinct names.
@param sql_statement: a string representation of a Structured Query
L... | [
"def",
"execute",
"(",
"self",
",",
"sql_statement",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"parameters",
":",
"# Convert the simple value of parameters which the database adapter",
"# cannot adapt to SQL type, such as enum values.",
"# [http://initd.org/psycopg/docs/usage... | Execute the specified Structured Query Language (SQL) parameterized
statement.
@note: each result column MUST be named with distinct names.
@param sql_statement: a string representation of a Structured Query
Language (SQL) expression including Python extended format codes,
... | [
"Execute",
"the",
"specified",
"Structured",
"Query",
"Language",
"(",
"SQL",
")",
"parameterized",
"statement",
"."
] | python | train | 39.638095 |
adrn/gala | gala/io.py | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/io.py#L4-L25 | def quantity_from_hdf5(dset):
"""
Return an Astropy Quantity object from a key in an HDF5 file,
group, or dataset. This checks to see if the input file/group/dataset
contains a ``'unit'`` attribute (e.g., in `f.attrs`).
Parameters
----------
dset : :class:`h5py.DataSet`
Returns
---... | [
"def",
"quantity_from_hdf5",
"(",
"dset",
")",
":",
"if",
"'unit'",
"in",
"dset",
".",
"attrs",
"and",
"dset",
".",
"attrs",
"[",
"'unit'",
"]",
"is",
"not",
"None",
":",
"unit",
"=",
"u",
".",
"Unit",
"(",
"dset",
".",
"attrs",
"[",
"'unit'",
"]",... | Return an Astropy Quantity object from a key in an HDF5 file,
group, or dataset. This checks to see if the input file/group/dataset
contains a ``'unit'`` attribute (e.g., in `f.attrs`).
Parameters
----------
dset : :class:`h5py.DataSet`
Returns
-------
q : `astropy.units.Quantity`, `nu... | [
"Return",
"an",
"Astropy",
"Quantity",
"object",
"from",
"a",
"key",
"in",
"an",
"HDF5",
"file",
"group",
"or",
"dataset",
".",
"This",
"checks",
"to",
"see",
"if",
"the",
"input",
"file",
"/",
"group",
"/",
"dataset",
"contains",
"a",
"unit",
"attribute... | python | train | 28.545455 |
xav/Grapefruit | grapefruit.py | https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1867-L1885 | def desaturate(self, level):
"""Create a new instance based on this one but less saturated.
Parameters:
:level:
The amount by which the color should be desaturated to produce
the new one [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 0.5, 0.5).desatu... | [
"def",
"desaturate",
"(",
"self",
",",
"level",
")",
":",
"h",
",",
"s",
",",
"l",
"=",
"self",
".",
"__hsl",
"return",
"Color",
"(",
"(",
"h",
",",
"max",
"(",
"s",
"-",
"level",
",",
"0",
")",
",",
"l",
")",
",",
"'hsl'",
",",
"self",
"."... | Create a new instance based on this one but less saturated.
Parameters:
:level:
The amount by which the color should be desaturated to produce
the new one [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25)
Color(0.625, 0.5, 0.3... | [
"Create",
"a",
"new",
"instance",
"based",
"on",
"this",
"one",
"but",
"less",
"saturated",
"."
] | python | train | 28.105263 |
swharden/SWHLab | doc/oldcode/swhlab/core/common.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L98-L102 | def listCount(l):
"""returns len() of each item in a list, as a list."""
for i in range(len(l)):
l[i]=len(l[i])
return l | [
"def",
"listCount",
"(",
"l",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"l",
")",
")",
":",
"l",
"[",
"i",
"]",
"=",
"len",
"(",
"l",
"[",
"i",
"]",
")",
"return",
"l"
] | returns len() of each item in a list, as a list. | [
"returns",
"len",
"()",
"of",
"each",
"item",
"in",
"a",
"list",
"as",
"a",
"list",
"."
] | python | valid | 27.2 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py#L893-L898 | def _exclusively_used(self, context, hosting_device, tenant_id):
"""Checks if only <tenant_id>'s resources use <hosting_device>."""
return (context.session.query(hd_models.SlotAllocation).filter(
hd_models.SlotAllocation.hosting_device_id == hosting_device['id'],
hd_models.SlotAl... | [
"def",
"_exclusively_used",
"(",
"self",
",",
"context",
",",
"hosting_device",
",",
"tenant_id",
")",
":",
"return",
"(",
"context",
".",
"session",
".",
"query",
"(",
"hd_models",
".",
"SlotAllocation",
")",
".",
"filter",
"(",
"hd_models",
".",
"SlotAlloc... | Checks if only <tenant_id>'s resources use <hosting_device>. | [
"Checks",
"if",
"only",
"<tenant_id",
">",
"s",
"resources",
"use",
"<hosting_device",
">",
"."
] | python | train | 65 |
bokeh/bokeh | bokeh/server/server.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/server.py#L226-L261 | def show(self, app_path, browser=None, new='tab'):
''' Opens an app in a browser window or tab.
This method is useful for testing or running Bokeh server applications
on a local machine but should not call when running Bokeh server for
an actual deployment.
Args:
ap... | [
"def",
"show",
"(",
"self",
",",
"app_path",
",",
"browser",
"=",
"None",
",",
"new",
"=",
"'tab'",
")",
":",
"if",
"not",
"app_path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"raise",
"ValueError",
"(",
"\"app_path must start with a /\"",
")",
"address_... | Opens an app in a browser window or tab.
This method is useful for testing or running Bokeh server applications
on a local machine but should not call when running Bokeh server for
an actual deployment.
Args:
app_path (str) : the app path to open
The part of... | [
"Opens",
"an",
"app",
"in",
"a",
"browser",
"window",
"or",
"tab",
"."
] | python | train | 39.861111 |
twilio/twilio-python | twilio/rest/api/v2010/account/balance.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/balance.py#L34-L49 | def fetch(self):
"""
Fetch a BalanceInstance
:returns: Fetched BalanceInstance
:rtype: twilio.rest.api.v2010.account.balance.BalanceInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=pa... | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"Balan... | Fetch a BalanceInstance
:returns: Fetched BalanceInstance
:rtype: twilio.rest.api.v2010.account.balance.BalanceInstance | [
"Fetch",
"a",
"BalanceInstance"
] | python | train | 26.3125 |
artizirk/python-axp209 | axp209.py | https://github.com/artizirk/python-axp209/blob/dc48015b23ea3695bf1ee076355c96ea434b77e4/axp209.py#L197-L204 | def battery_charge_current(self):
""" Returns current in mA """
msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_CHARGE_CURRENT_MSB_REG)
lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_CHARGE_CURRENT_LSB_REG)
# (12 bits)
charge_bin = msb << 4 | lsb & 0x0f
# 0 m... | [
"def",
"battery_charge_current",
"(",
"self",
")",
":",
"msb",
"=",
"self",
".",
"bus",
".",
"read_byte_data",
"(",
"AXP209_ADDRESS",
",",
"BATTERY_CHARGE_CURRENT_MSB_REG",
")",
"lsb",
"=",
"self",
".",
"bus",
".",
"read_byte_data",
"(",
"AXP209_ADDRESS",
",",
... | Returns current in mA | [
"Returns",
"current",
"in",
"mA"
] | python | train | 47.75 |
awslabs/sockeye | sockeye/scoring.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/scoring.py#L98-L212 | def _initialize(self,
provide_data: List[mx.io.DataDesc],
provide_label: List[mx.io.DataDesc],
default_bucket_key: Tuple[int, int]) -> None:
"""
Initializes model components, creates scoring symbol and module, and binds it.
:param prov... | [
"def",
"_initialize",
"(",
"self",
",",
"provide_data",
":",
"List",
"[",
"mx",
".",
"io",
".",
"DataDesc",
"]",
",",
"provide_label",
":",
"List",
"[",
"mx",
".",
"io",
".",
"DataDesc",
"]",
",",
"default_bucket_key",
":",
"Tuple",
"[",
"int",
",",
... | Initializes model components, creates scoring symbol and module, and binds it.
:param provide_data: List of data descriptors.
:param provide_label: List of label descriptors.
:param default_bucket_key: The default maximum (source, target) lengths. | [
"Initializes",
"model",
"components",
"creates",
"scoring",
"symbol",
"and",
"module",
"and",
"binds",
"it",
"."
] | python | train | 50.791304 |
ianclegg/ntlmlib | ntlmlib/context.py | https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/context.py#L114-L125 | def wrap_message(self, message):
"""
Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if
'confidentiality' was negotiated, otherwise the message is left untouched.
:return: A tuple containing the message signature and the optionally encr... | [
"def",
"wrap_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"self",
".",
"is_established",
":",
"raise",
"Exception",
"(",
"\"Context has not been established\"",
")",
"if",
"self",
".",
"_wrapper",
"is",
"None",
":",
"raise",
"Exception",
"(",
... | Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if
'confidentiality' was negotiated, otherwise the message is left untouched.
:return: A tuple containing the message signature and the optionally encrypted message | [
"Cryptographically",
"signs",
"and",
"optionally",
"encrypts",
"the",
"supplied",
"message",
".",
"The",
"message",
"is",
"only",
"encrypted",
"if",
"confidentiality",
"was",
"negotiated",
"otherwise",
"the",
"message",
"is",
"left",
"untouched",
".",
":",
"return... | python | train | 50.666667 |
boriel/zxbasic | api/symboltable.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L596-L614 | def declare_type(self, type_):
""" Declares a type.
Checks its name is not already used in the current scope,
and that it's not a basic type.
Returns the given type_ Symbol, or None on error.
"""
assert isinstance(type_, symbols.TYPE)
# Checks it's not a basic ty... | [
"def",
"declare_type",
"(",
"self",
",",
"type_",
")",
":",
"assert",
"isinstance",
"(",
"type_",
",",
"symbols",
".",
"TYPE",
")",
"# Checks it's not a basic type",
"if",
"not",
"type_",
".",
"is_basic",
"and",
"type_",
".",
"name",
".",
"lower",
"(",
")"... | Declares a type.
Checks its name is not already used in the current scope,
and that it's not a basic type.
Returns the given type_ Symbol, or None on error. | [
"Declares",
"a",
"type",
".",
"Checks",
"its",
"name",
"is",
"not",
"already",
"used",
"in",
"the",
"current",
"scope",
"and",
"that",
"it",
"s",
"not",
"a",
"basic",
"type",
"."
] | python | train | 39.684211 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/interactive.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/interactive.py#L1642-L1652 | def do_bm(self, arg):
"""
[~process] bm <address-address> - set memory breakpoint
"""
pid = self.get_process_id_from_prefix()
if not self.debug.is_debugee(pid):
raise CmdError("target process is not being debugged")
process = self.get_process(pid)
... | [
"def",
"do_bm",
"(",
"self",
",",
"arg",
")",
":",
"pid",
"=",
"self",
".",
"get_process_id_from_prefix",
"(",
")",
"if",
"not",
"self",
".",
"debug",
".",
"is_debugee",
"(",
"pid",
")",
":",
"raise",
"CmdError",
"(",
"\"target process is not being debugged\... | [~process] bm <address-address> - set memory breakpoint | [
"[",
"~process",
"]",
"bm",
"<address",
"-",
"address",
">",
"-",
"set",
"memory",
"breakpoint"
] | python | train | 43.363636 |
foremast/foremast | src/foremast/elb/destroy_elb/destroy_elb.py | https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/elb/destroy_elb/destroy_elb.py#L21-L41 | def destroy_elb(app='', env='dev', region='us-east-1', **_):
"""Destroy ELB Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
True upon successful completion.
"""
task_json = get_template(
... | [
"def",
"destroy_elb",
"(",
"app",
"=",
"''",
",",
"env",
"=",
"'dev'",
",",
"region",
"=",
"'us-east-1'",
",",
"*",
"*",
"_",
")",
":",
"task_json",
"=",
"get_template",
"(",
"template_file",
"=",
"'destroy/destroy_elb.json.j2'",
",",
"app",
"=",
"app",
... | Destroy ELB Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
True upon successful completion. | [
"Destroy",
"ELB",
"Resources",
"."
] | python | train | 24.142857 |
evhub/coconut | coconut/compiler/compiler.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/compiler.py#L603-L612 | def make_parse_err(self, err, reformat=True, include_ln=True):
"""Make a CoconutParseError from a ParseBaseException."""
err_line = err.line
err_index = err.col - 1
err_lineno = err.lineno if include_ln else None
if reformat:
err_line, err_index = self.reformat(err_li... | [
"def",
"make_parse_err",
"(",
"self",
",",
"err",
",",
"reformat",
"=",
"True",
",",
"include_ln",
"=",
"True",
")",
":",
"err_line",
"=",
"err",
".",
"line",
"err_index",
"=",
"err",
".",
"col",
"-",
"1",
"err_lineno",
"=",
"err",
".",
"lineno",
"if... | Make a CoconutParseError from a ParseBaseException. | [
"Make",
"a",
"CoconutParseError",
"from",
"a",
"ParseBaseException",
"."
] | python | train | 48.9 |
sassoo/goldman | goldman/middleware/model_qps/__init__.py | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/middleware/model_qps/__init__.py#L41-L60 | def process_resource(self, req, resp, resource):
""" Process the request after routing.
The resource is required to determine if a model based
resource is being used for validations so skip
processing if no `resource.model` attribute is present.
"""
try:
mod... | [
"def",
"process_resource",
"(",
"self",
",",
"req",
",",
"resp",
",",
"resource",
")",
":",
"try",
":",
"model",
"=",
"resource",
".",
"model",
"req",
".",
"fields",
"=",
"fields",
".",
"init",
"(",
"req",
",",
"model",
")",
"req",
".",
"filters",
... | Process the request after routing.
The resource is required to determine if a model based
resource is being used for validations so skip
processing if no `resource.model` attribute is present. | [
"Process",
"the",
"request",
"after",
"routing",
"."
] | python | train | 34.05 |
MisterY/gnucash-portfolio | setup.alt.py | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/setup.alt.py#L67-L87 | def get_project_files():
"""Retrieve a list of project files, ignoring hidden files.
:return: sorted list of project files
:rtype: :class:`list`
"""
if is_git_project():
return get_git_project_files()
project_files = []
for top, subdirs, files in os.walk('.'):
for subdir in... | [
"def",
"get_project_files",
"(",
")",
":",
"if",
"is_git_project",
"(",
")",
":",
"return",
"get_git_project_files",
"(",
")",
"project_files",
"=",
"[",
"]",
"for",
"top",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"'.'",
")",
":",
"f... | Retrieve a list of project files, ignoring hidden files.
:return: sorted list of project files
:rtype: :class:`list` | [
"Retrieve",
"a",
"list",
"of",
"project",
"files",
"ignoring",
"hidden",
"files",
"."
] | python | train | 26.285714 |
AnalogJ/lexicon | lexicon/providers/hetzner.py | https://github.com/AnalogJ/lexicon/blob/9330b871988753cad44fe2876a217b4c67b1fa0e/lexicon/providers/hetzner.py#L516-L536 | def _propagated_record(self, rdtype, name, content, nameservers=None):
"""
If the publicly propagation check should be done, waits until the domain nameservers
responses with the propagated record type, name & content and returns a boolean,
if the publicly propagation was successful or n... | [
"def",
"_propagated_record",
"(",
"self",
",",
"rdtype",
",",
"name",
",",
"content",
",",
"nameservers",
"=",
"None",
")",
":",
"latency",
"=",
"self",
".",
"_get_provider_option",
"(",
"'latency'",
")",
"propagated",
"=",
"self",
".",
"_get_provider_option",... | If the publicly propagation check should be done, waits until the domain nameservers
responses with the propagated record type, name & content and returns a boolean,
if the publicly propagation was successful or not. | [
"If",
"the",
"publicly",
"propagation",
"check",
"should",
"be",
"done",
"waits",
"until",
"the",
"domain",
"nameservers",
"responses",
"with",
"the",
"propagated",
"record",
"type",
"name",
"&",
"content",
"and",
"returns",
"a",
"boolean",
"if",
"the",
"publi... | python | train | 53.095238 |
cimm-kzn/CGRtools | CGRtools/algorithms/morgan.py | https://github.com/cimm-kzn/CGRtools/blob/15a19b04f6e4e1d0dab8e0d32a0877c7f7d70f34/CGRtools/algorithms/morgan.py#L29-L85 | def atoms_order(self):
"""
Morgan like algorithm for graph nodes ordering
:return: dict of atom-weight pairs
"""
if not len(self): # for empty containers
return {}
elif len(self) == 1: # optimize single atom containers
return dict.fromkeys(self,... | [
"def",
"atoms_order",
"(",
"self",
")",
":",
"if",
"not",
"len",
"(",
"self",
")",
":",
"# for empty containers",
"return",
"{",
"}",
"elif",
"len",
"(",
"self",
")",
"==",
"1",
":",
"# optimize single atom containers",
"return",
"dict",
".",
"fromkeys",
"... | Morgan like algorithm for graph nodes ordering
:return: dict of atom-weight pairs | [
"Morgan",
"like",
"algorithm",
"for",
"graph",
"nodes",
"ordering"
] | python | train | 34.298246 |
tanghaibao/jcvi | jcvi/algorithms/ec.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/ec.py#L99-L161 | def eaSimpleConverge(population, toolbox, cxpb, mutpb, ngen, stats=None,
halloffame=None, callback=None, verbose=True):
"""This algorithm reproduce the simplest evolutionary algorithm as
presented in chapter 7 of [Back2000]_.
Modified to allow checking if there is no change for ngen, a... | [
"def",
"eaSimpleConverge",
"(",
"population",
",",
"toolbox",
",",
"cxpb",
",",
"mutpb",
",",
"ngen",
",",
"stats",
"=",
"None",
",",
"halloffame",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"# Evaluate the individual... | This algorithm reproduce the simplest evolutionary algorithm as
presented in chapter 7 of [Back2000]_.
Modified to allow checking if there is no change for ngen, as a simple
rule for convergence. Interface is similar to eaSimple(). However, in
eaSimple, ngen is total number of iterations; in eaSimpleCo... | [
"This",
"algorithm",
"reproduce",
"the",
"simplest",
"evolutionary",
"algorithm",
"as",
"presented",
"in",
"chapter",
"7",
"of",
"[",
"Back2000",
"]",
"_",
"."
] | python | train | 36.253968 |
KeplerGO/K2fov | K2fov/rotate2.py | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/rotate2.py#L128-L171 | def rotateAboutVectorMatrix(vec, theta_deg):
"""Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should... | [
"def",
"rotateAboutVectorMatrix",
"(",
"vec",
",",
"theta_deg",
")",
":",
"ct",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"theta_deg",
")",
")",
"st",
"=",
"np",
".",
"sin",
"(",
"np",
".",
"radians",
"(",
"theta_deg",
")",
")",
"# Ens... | Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:... | [
"Construct",
"the",
"matrix",
"that",
"rotates",
"vector",
"a",
"about",
"vector",
"vec",
"by",
"an",
"angle",
"of",
"theta_deg",
"degrees"
] | python | train | 25.113636 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.