repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
mouradmourafiq/pandas2sklearn | pandas_sklearn/__init__.py | https://github.com/mouradmourafiq/pandas2sklearn/blob/dbaf5180a893f4612852c1c217551b161fd519d4/pandas_sklearn/__init__.py#L218-L243 | def transform(self, X):
"""
Transform the given data. Assumes that fit has already been called.
:param X (DataSet): the data to transform
"""
extracted = []
for columns, transformer in self.mapping:
if transformer is not None:
feature = transf... | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"extracted",
"=",
"[",
"]",
"for",
"columns",
",",
"transformer",
"in",
"self",
".",
"mapping",
":",
"if",
"transformer",
"is",
"not",
"None",
":",
"feature",
"=",
"transformer",
".",
"transform",
"(... | Transform the given data. Assumes that fit has already been called.
:param X (DataSet): the data to transform | [
"Transform",
"the",
"given",
"data",
".",
"Assumes",
"that",
"fit",
"has",
"already",
"been",
"called",
".",
":",
"param",
"X",
"(",
"DataSet",
")",
":",
"the",
"data",
"to",
"transform"
] | python | train |
the-allanc/greyupnp | greyupnp/ssdp.py | https://github.com/the-allanc/greyupnp/blob/7d40c4c306f3e87a453494c9ad3c1ac1626d02c5/greyupnp/ssdp.py#L37-L51 | def encode_request(request_line, **headers):
'''Creates the data for a SSDP request.
Args:
request_line (string): The request line for the request (e.g.
``"M-SEARCH * HTTP/1.1"``).
headers (dict of string -> string): Dictionary of header name - header
value pairs to pres... | [
"def",
"encode_request",
"(",
"request_line",
",",
"*",
"*",
"headers",
")",
":",
"lines",
"=",
"[",
"request_line",
"]",
"lines",
".",
"extend",
"(",
"[",
"'%s: %s'",
"%",
"kv",
"for",
"kv",
"in",
"headers",
".",
"items",
"(",
")",
"]",
")",
"return... | Creates the data for a SSDP request.
Args:
request_line (string): The request line for the request (e.g.
``"M-SEARCH * HTTP/1.1"``).
headers (dict of string -> string): Dictionary of header name - header
value pairs to present in the request.
Returns:
bytes: The... | [
"Creates",
"the",
"data",
"for",
"a",
"SSDP",
"request",
"."
] | python | train |
SuperCowPowers/workbench | workbench/workers/pcap_bro.py | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pcap_bro.py#L113-L125 | def subprocess_manager(self, exec_args):
''' Bro subprocess manager '''
try:
sp = gevent.subprocess.Popen(exec_args, stdout=gevent.subprocess.PIPE, stderr=gevent.subprocess.PIPE)
except OSError:
raise RuntimeError('Could not run bro executable (either not installed or not... | [
"def",
"subprocess_manager",
"(",
"self",
",",
"exec_args",
")",
":",
"try",
":",
"sp",
"=",
"gevent",
".",
"subprocess",
".",
"Popen",
"(",
"exec_args",
",",
"stdout",
"=",
"gevent",
".",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"gevent",
".",
"... | Bro subprocess manager | [
"Bro",
"subprocess",
"manager"
] | python | train |
opencobra/cobrapy | cobra/core/dictlist.py | https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L167-L173 | def union(self, iterable):
"""adds elements with id's not already in the model"""
_dict = self._dict
append = self.append
for i in iterable:
if i.id not in _dict:
append(i) | [
"def",
"union",
"(",
"self",
",",
"iterable",
")",
":",
"_dict",
"=",
"self",
".",
"_dict",
"append",
"=",
"self",
".",
"append",
"for",
"i",
"in",
"iterable",
":",
"if",
"i",
".",
"id",
"not",
"in",
"_dict",
":",
"append",
"(",
"i",
")"
] | adds elements with id's not already in the model | [
"adds",
"elements",
"with",
"id",
"s",
"not",
"already",
"in",
"the",
"model"
] | python | valid |
keflavich/plfit | plfit/plfit.py | https://github.com/keflavich/plfit/blob/7dafa6302b427ba8c89651148e3e9d29add436c3/plfit/plfit.py#L159-L394 | def plfit(self, nosmall=True, finite=False, quiet=False, silent=False,
usefortran=False, usecy=False, xmin=None, verbose=False,
discrete=None, discrete_approx=True, discrete_n_alpha=1000,
skip_consistency_check=False):
"""
A Python implementation of the Matlab c... | [
"def",
"plfit",
"(",
"self",
",",
"nosmall",
"=",
"True",
",",
"finite",
"=",
"False",
",",
"quiet",
"=",
"False",
",",
"silent",
"=",
"False",
",",
"usefortran",
"=",
"False",
",",
"usecy",
"=",
"False",
",",
"xmin",
"=",
"None",
",",
"verbose",
"... | A Python implementation of the Matlab code
http://www.santafe.edu/~aaronc/powerlaws/plfit.m
from http://www.santafe.edu/~aaronc/powerlaws/
See A. Clauset, C.R. Shalizi, and M.E.J. Newman, "Power-law distributions
in empirical data" SIAM Review, 51, 661-703 (2009). (arXiv:0706.1062)
... | [
"A",
"Python",
"implementation",
"of",
"the",
"Matlab",
"code",
"http",
":",
"//",
"www",
".",
"santafe",
".",
"edu",
"/",
"~aaronc",
"/",
"powerlaws",
"/",
"plfit",
".",
"m",
"from",
"http",
":",
"//",
"www",
".",
"santafe",
".",
"edu",
"/",
"~aaron... | python | test |
tgsmith61591/pmdarima | pmdarima/compat/statsmodels.py | https://github.com/tgsmith61591/pmdarima/blob/a133de78ba5bd68da9785b061f519ba28cd514cc/pmdarima/compat/statsmodels.py#L15-L33 | def bind_df_model(model_fit, arima_results):
"""Set model degrees of freedom.
Older versions of statsmodels don't handle this issue. Sets the
model degrees of freedom in place if not already present.
Parameters
----------
model_fit : ARMA, ARIMA or SARIMAX
The fitted model.
arima_... | [
"def",
"bind_df_model",
"(",
"model_fit",
",",
"arima_results",
")",
":",
"if",
"not",
"hasattr",
"(",
"arima_results",
",",
"'df_model'",
")",
":",
"df_model",
"=",
"model_fit",
".",
"k_exog",
"+",
"model_fit",
".",
"k_trend",
"+",
"model_fit",
".",
"k_ar",... | Set model degrees of freedom.
Older versions of statsmodels don't handle this issue. Sets the
model degrees of freedom in place if not already present.
Parameters
----------
model_fit : ARMA, ARIMA or SARIMAX
The fitted model.
arima_results : ModelResultsWrapper
The results wr... | [
"Set",
"model",
"degrees",
"of",
"freedom",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/opennebula.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L4515-L4539 | def _get_xml_rpc():
'''
Uses the OpenNebula cloud provider configurations to connect to the
OpenNebula API.
Returns the server connection created as well as the user and password
values from the cloud provider config file used to make the connection.
'''
vm_ = get_configured_provider()
... | [
"def",
"_get_xml_rpc",
"(",
")",
":",
"vm_",
"=",
"get_configured_provider",
"(",
")",
"xml_rpc",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'xml_rpc'",
",",
"vm_",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
"user",
"=",
"config",
"."... | Uses the OpenNebula cloud provider configurations to connect to the
OpenNebula API.
Returns the server connection created as well as the user and password
values from the cloud provider config file used to make the connection. | [
"Uses",
"the",
"OpenNebula",
"cloud",
"provider",
"configurations",
"to",
"connect",
"to",
"the",
"OpenNebula",
"API",
"."
] | python | train |
googleapis/google-cloud-python | datastore/google/cloud/datastore/batch.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/batch.py#L224-L237 | def begin(self):
"""Begins a batch.
This method is called automatically when entering a with
statement, however it can be called explicitly if you don't want
to use a context manager.
Overridden by :class:`google.cloud.datastore.transaction.Transaction`.
:raises: :clas... | [
"def",
"begin",
"(",
"self",
")",
":",
"if",
"self",
".",
"_status",
"!=",
"self",
".",
"_INITIAL",
":",
"raise",
"ValueError",
"(",
"\"Batch already started previously.\"",
")",
"self",
".",
"_status",
"=",
"self",
".",
"_IN_PROGRESS"
] | Begins a batch.
This method is called automatically when entering a with
statement, however it can be called explicitly if you don't want
to use a context manager.
Overridden by :class:`google.cloud.datastore.transaction.Transaction`.
:raises: :class:`ValueError` if the batch ... | [
"Begins",
"a",
"batch",
"."
] | python | train |
kdeldycke/maildir-deduplicate | maildir_deduplicate/deduplicate.py | https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L172-L181 | def pretty_diff(self, mail_a, mail_b):
""" Returns a verbose unified diff between two mails' normalized body.
"""
return ''.join(unified_diff(
mail_a.body_lines, mail_b.body_lines,
fromfile='Normalized body of {}'.format(mail_a.path),
tofile='Normalized body o... | [
"def",
"pretty_diff",
"(",
"self",
",",
"mail_a",
",",
"mail_b",
")",
":",
"return",
"''",
".",
"join",
"(",
"unified_diff",
"(",
"mail_a",
".",
"body_lines",
",",
"mail_b",
".",
"body_lines",
",",
"fromfile",
"=",
"'Normalized body of {}'",
".",
"format",
... | Returns a verbose unified diff between two mails' normalized body. | [
"Returns",
"a",
"verbose",
"unified",
"diff",
"between",
"two",
"mails",
"normalized",
"body",
"."
] | python | train |
gabstopper/smc-python | smc/administration/certificates/tls.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/certificates/tls.py#L326-L355 | def create_csr(cls, name, common_name, public_key_algorithm='rsa',
signature_algorithm='rsa_sha_512', key_length=4096):
"""
Create a certificate signing request.
:param str name: name of TLS Server Credential
:param str rcommon_name: common name for certificate. ... | [
"def",
"create_csr",
"(",
"cls",
",",
"name",
",",
"common_name",
",",
"public_key_algorithm",
"=",
"'rsa'",
",",
"signature_algorithm",
"=",
"'rsa_sha_512'",
",",
"key_length",
"=",
"4096",
")",
":",
"json",
"=",
"{",
"'name'",
":",
"name",
",",
"'info'",
... | Create a certificate signing request.
:param str name: name of TLS Server Credential
:param str rcommon_name: common name for certificate. An example
would be: "CN=CommonName,O=Organization,OU=Unit,C=FR,ST=PACA,L=Nice".
At minimum, a "CN" is required.
:param str... | [
"Create",
"a",
"certificate",
"signing",
"request",
".",
":",
"param",
"str",
"name",
":",
"name",
"of",
"TLS",
"Server",
"Credential",
":",
"param",
"str",
"rcommon_name",
":",
"common",
"name",
"for",
"certificate",
".",
"An",
"example",
"would",
"be",
"... | python | train |
pudo/jsonmapping | jsonmapping/value.py | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/value.py#L28-L36 | def get_type(bind):
""" Detect the ideal type for the data, either using the explicit type
definition or the format (for date, date-time, not supported by JSON). """
types = bind.types + [bind.schema.get('format')]
for type_name in ('date-time', 'date', 'decimal', 'integer', 'boolean',
... | [
"def",
"get_type",
"(",
"bind",
")",
":",
"types",
"=",
"bind",
".",
"types",
"+",
"[",
"bind",
".",
"schema",
".",
"get",
"(",
"'format'",
")",
"]",
"for",
"type_name",
"in",
"(",
"'date-time'",
",",
"'date'",
",",
"'decimal'",
",",
"'integer'",
","... | Detect the ideal type for the data, either using the explicit type
definition or the format (for date, date-time, not supported by JSON). | [
"Detect",
"the",
"ideal",
"type",
"for",
"the",
"data",
"either",
"using",
"the",
"explicit",
"type",
"definition",
"or",
"the",
"format",
"(",
"for",
"date",
"date",
"-",
"time",
"not",
"supported",
"by",
"JSON",
")",
"."
] | python | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/__notebook_support__.py | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/__notebook_support__.py#L478-L548 | def plot_emg_graphical_statistical(time, signal, max_sample_value, min_sample_value, avg_sample_value,
std_sample_value):
"""
-----
Brief
-----
This plotting function ensures a graphical representation of maximum, minimum and average sample
values registered on... | [
"def",
"plot_emg_graphical_statistical",
"(",
"time",
",",
"signal",
",",
"max_sample_value",
",",
"min_sample_value",
",",
"avg_sample_value",
",",
"std_sample_value",
")",
":",
"# List that store the figure handler",
"list_figures",
"=",
"[",
"]",
"# Plotting of EMG.",
... | -----
Brief
-----
This plotting function ensures a graphical representation of maximum, minimum and average sample
values registered on the entire EMG acquisition.
-----------
Description
-----------
Function intended to generate a single Bokeh figure with graphically describing and ide... | [
"-----",
"Brief",
"-----",
"This",
"plotting",
"function",
"ensures",
"a",
"graphical",
"representation",
"of",
"maximum",
"minimum",
"and",
"average",
"sample",
"values",
"registered",
"on",
"the",
"entire",
"EMG",
"acquisition",
"."
] | python | train |
binux/pyspider | pyspider/scheduler/scheduler.py | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L653-L659 | def quit(self):
'''Set quit signal'''
self._quit = True
# stop xmlrpc server
if hasattr(self, 'xmlrpc_server'):
self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop)
self.xmlrpc_ioloop.add_callback(self.xmlrpc_ioloop.stop) | [
"def",
"quit",
"(",
"self",
")",
":",
"self",
".",
"_quit",
"=",
"True",
"# stop xmlrpc server",
"if",
"hasattr",
"(",
"self",
",",
"'xmlrpc_server'",
")",
":",
"self",
".",
"xmlrpc_ioloop",
".",
"add_callback",
"(",
"self",
".",
"xmlrpc_server",
".",
"sto... | Set quit signal | [
"Set",
"quit",
"signal"
] | python | train |
SiLab-Bonn/pyBAR | pybar/analysis/analysis_utils.py | https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/analysis/analysis_utils.py#L817-L859 | def get_hits_of_scan_parameter(input_file_hits, scan_parameters=None, try_speedup=False, chunk_size=10000000):
'''Takes the hit table of a hdf5 file and returns hits in chunks for each unique combination of scan_parameters.
Yields the hits in chunks, since they usually do not fit into memory.
Parameters
... | [
"def",
"get_hits_of_scan_parameter",
"(",
"input_file_hits",
",",
"scan_parameters",
"=",
"None",
",",
"try_speedup",
"=",
"False",
",",
"chunk_size",
"=",
"10000000",
")",
":",
"with",
"tb",
".",
"open_file",
"(",
"input_file_hits",
",",
"mode",
"=",
"\"r+\"",
... | Takes the hit table of a hdf5 file and returns hits in chunks for each unique combination of scan_parameters.
Yields the hits in chunks, since they usually do not fit into memory.
Parameters
----------
input_file_hits : pytable hdf5 file
Has to include a hits node
scan_parameters : iterable... | [
"Takes",
"the",
"hit",
"table",
"of",
"a",
"hdf5",
"file",
"and",
"returns",
"hits",
"in",
"chunks",
"for",
"each",
"unique",
"combination",
"of",
"scan_parameters",
".",
"Yields",
"the",
"hits",
"in",
"chunks",
"since",
"they",
"usually",
"do",
"not",
"fi... | python | train |
wonambi-python/wonambi | wonambi/attr/annotations.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L149-L220 | def create_annotation(xml_file, from_fasst):
"""Create annotations by importing from FASST sleep scoring file.
Parameters
----------
xml_file : path to xml file
annotation file that will be created
from_fasst : path to FASST file
.mat file containing the scores
Returns
----... | [
"def",
"create_annotation",
"(",
"xml_file",
",",
"from_fasst",
")",
":",
"xml_file",
"=",
"Path",
"(",
"xml_file",
")",
"try",
":",
"mat",
"=",
"loadmat",
"(",
"str",
"(",
"from_fasst",
")",
",",
"variable_names",
"=",
"'D'",
",",
"struct_as_record",
"=",... | Create annotations by importing from FASST sleep scoring file.
Parameters
----------
xml_file : path to xml file
annotation file that will be created
from_fasst : path to FASST file
.mat file containing the scores
Returns
-------
instance of Annotations
TODO
----
... | [
"Create",
"annotations",
"by",
"importing",
"from",
"FASST",
"sleep",
"scoring",
"file",
"."
] | python | train |
SolutionsCloud/apidoc | apidoc/object/source_dto.py | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L301-L304 | def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (str(self.name), str(self.description), str(self.type), bool(self.optional), str(self.constraints) if isinstance(self, Constraintable) else "") | [
"def",
"get_comparable_values",
"(",
"self",
")",
":",
"return",
"(",
"str",
"(",
"self",
".",
"name",
")",
",",
"str",
"(",
"self",
".",
"description",
")",
",",
"str",
"(",
"self",
".",
"type",
")",
",",
"bool",
"(",
"self",
".",
"optional",
")",... | Return a tupple of values representing the unicity of the object | [
"Return",
"a",
"tupple",
"of",
"values",
"representing",
"the",
"unicity",
"of",
"the",
"object"
] | python | train |
reingart/gui2py | gui/dialog.py | https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/dialog.py#L127-L131 | def find(default='', whole_words=0, case_sensitive=0, parent=None):
"Shows a find text dialog"
result = dialogs.findDialog(parent, default, whole_words, case_sensitive)
return {'text': result.searchText, 'whole_words': result.wholeWordsOnly,
'case_sensitive': result.caseSensitive} | [
"def",
"find",
"(",
"default",
"=",
"''",
",",
"whole_words",
"=",
"0",
",",
"case_sensitive",
"=",
"0",
",",
"parent",
"=",
"None",
")",
":",
"result",
"=",
"dialogs",
".",
"findDialog",
"(",
"parent",
",",
"default",
",",
"whole_words",
",",
"case_se... | Shows a find text dialog | [
"Shows",
"a",
"find",
"text",
"dialog"
] | python | test |
spaam/svtplay-dl | lib/svtplay_dl/utils/stream.py | https://github.com/spaam/svtplay-dl/blob/d33186e54e436ebb1537e5baf67758e3bd3bf076/lib/svtplay_dl/utils/stream.py#L28-L43 | def protocol_prio(streams, priolist):
"""
Given a list of VideoRetriever objects and a prioritized list of
accepted protocols (as strings) (highest priority first), return
a list of VideoRetriever objects that are accepted, and sorted
by bitrate, and then protocol priority.
"""
# Map score's... | [
"def",
"protocol_prio",
"(",
"streams",
",",
"priolist",
")",
":",
"# Map score's to the reverse of the list's index values",
"proto_score",
"=",
"dict",
"(",
"zip",
"(",
"priolist",
",",
"range",
"(",
"len",
"(",
"priolist",
")",
",",
"0",
",",
"-",
"1",
")",... | Given a list of VideoRetriever objects and a prioritized list of
accepted protocols (as strings) (highest priority first), return
a list of VideoRetriever objects that are accepted, and sorted
by bitrate, and then protocol priority. | [
"Given",
"a",
"list",
"of",
"VideoRetriever",
"objects",
"and",
"a",
"prioritized",
"list",
"of",
"accepted",
"protocols",
"(",
"as",
"strings",
")",
"(",
"highest",
"priority",
"first",
")",
"return",
"a",
"list",
"of",
"VideoRetriever",
"objects",
"that",
... | python | train |
saltstack/salt | salt/modules/xfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xfs.py#L112-L125 | def info(device):
'''
Get filesystem geometry information.
CLI Example:
.. code-block:: bash
salt '*' xfs.info /dev/sda1
'''
out = __salt__['cmd.run_all']("xfs_info {0}".format(device))
if out.get('stderr'):
raise CommandExecutionError(out['stderr'].replace("xfs_info:", ""... | [
"def",
"info",
"(",
"device",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"\"xfs_info {0}\"",
".",
"format",
"(",
"device",
")",
")",
"if",
"out",
".",
"get",
"(",
"'stderr'",
")",
":",
"raise",
"CommandExecutionError",
"(",
"out",
... | Get filesystem geometry information.
CLI Example:
.. code-block:: bash
salt '*' xfs.info /dev/sda1 | [
"Get",
"filesystem",
"geometry",
"information",
"."
] | python | train |
saltstack/salt | salt/utils/platform.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/platform.py#L87-L106 | def is_smartos_globalzone():
'''
Function to return if host is SmartOS (Illumos) global zone or not
'''
if not is_smartos():
return False
else:
cmd = ['zonename']
try:
zonename = subprocess.Popen(
cmd, shell=False,
stdout=subprocess... | [
"def",
"is_smartos_globalzone",
"(",
")",
":",
"if",
"not",
"is_smartos",
"(",
")",
":",
"return",
"False",
"else",
":",
"cmd",
"=",
"[",
"'zonename'",
"]",
"try",
":",
"zonename",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"False"... | Function to return if host is SmartOS (Illumos) global zone or not | [
"Function",
"to",
"return",
"if",
"host",
"is",
"SmartOS",
"(",
"Illumos",
")",
"global",
"zone",
"or",
"not"
] | python | train |
StagPython/StagPy | stagpy/processing.py | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L114-L131 | def r_edges(step):
"""Cell border.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the position of the bottom and top walls
of the cells. The two elements of the tuple are identical.
"""
rbo... | [
"def",
"r_edges",
"(",
"step",
")",
":",
"rbot",
",",
"rtop",
"=",
"misc",
".",
"get_rbounds",
"(",
"step",
")",
"centers",
"=",
"step",
".",
"rprof",
".",
"loc",
"[",
":",
",",
"'r'",
"]",
".",
"values",
"+",
"rbot",
"# assume walls are mid-way betwee... | Cell border.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the position of the bottom and top walls
of the cells. The two elements of the tuple are identical. | [
"Cell",
"border",
"."
] | python | train |
ArchiveTeam/wpull | wpull/processor/rule.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L74-L105 | def consult_filters(self, url_info: URLInfo, url_record: URLRecord, is_redirect: bool=False) \
-> Tuple[bool, str, dict]:
'''Consult the URL filter.
Args:
url_record: The URL record.
is_redirect: Whether the request is a redirect and it is
desired tha... | [
"def",
"consult_filters",
"(",
"self",
",",
"url_info",
":",
"URLInfo",
",",
"url_record",
":",
"URLRecord",
",",
"is_redirect",
":",
"bool",
"=",
"False",
")",
"->",
"Tuple",
"[",
"bool",
",",
"str",
",",
"dict",
"]",
":",
"if",
"not",
"self",
".",
... | Consult the URL filter.
Args:
url_record: The URL record.
is_redirect: Whether the request is a redirect and it is
desired that it spans hosts.
Returns
tuple:
1. bool: The verdict
2. str: A short reason string: nofilters, fil... | [
"Consult",
"the",
"URL",
"filter",
"."
] | python | train |
ZELLMECHANIK-DRESDEN/dclab | dclab/features/fl_crosstalk.py | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/fl_crosstalk.py#L61-L98 | def correct_crosstalk(fl1, fl2, fl3, fl_channel,
ct21=0, ct31=0, ct12=0, ct32=0, ct13=0, ct23=0):
"""Perform crosstalk correction
Parameters
----------
fli: int, float, or np.ndarray
Measured fluorescence signals
fl_channel: int (1, 2, or 3)
The channel number ... | [
"def",
"correct_crosstalk",
"(",
"fl1",
",",
"fl2",
",",
"fl3",
",",
"fl_channel",
",",
"ct21",
"=",
"0",
",",
"ct31",
"=",
"0",
",",
"ct12",
"=",
"0",
",",
"ct32",
"=",
"0",
",",
"ct13",
"=",
"0",
",",
"ct23",
"=",
"0",
")",
":",
"fl_channel",... | Perform crosstalk correction
Parameters
----------
fli: int, float, or np.ndarray
Measured fluorescence signals
fl_channel: int (1, 2, or 3)
The channel number for which the crosstalk-corrected signal
should be computed
cij: float
Spill (crosstalk or bleed-through) f... | [
"Perform",
"crosstalk",
"correction"
] | python | train |
danielperna84/pyhomematic | pyhomematic/_hm.py | https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L895-L908 | def homegearCheckInit(self, remote):
"""Check if proxy is still initialized"""
rdict = self.remotes.get(remote)
if not rdict:
return False
if rdict.get('type') != BACKEND_HOMEGEAR:
return False
try:
interface_id = "%s-%s" % (self._interface_id,... | [
"def",
"homegearCheckInit",
"(",
"self",
",",
"remote",
")",
":",
"rdict",
"=",
"self",
".",
"remotes",
".",
"get",
"(",
"remote",
")",
"if",
"not",
"rdict",
":",
"return",
"False",
"if",
"rdict",
".",
"get",
"(",
"'type'",
")",
"!=",
"BACKEND_HOMEGEAR... | Check if proxy is still initialized | [
"Check",
"if",
"proxy",
"is",
"still",
"initialized"
] | python | train |
HIPS/autograd | examples/variational_autoencoder.py | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/variational_autoencoder.py#L34-L38 | def init_net_params(scale, layer_sizes, rs=npr.RandomState(0)):
"""Build a (weights, biases) tuples for all layers."""
return [(scale * rs.randn(m, n), # weight matrix
scale * rs.randn(n)) # bias vector
for m, n in zip(layer_sizes[:-1], layer_sizes[1:])] | [
"def",
"init_net_params",
"(",
"scale",
",",
"layer_sizes",
",",
"rs",
"=",
"npr",
".",
"RandomState",
"(",
"0",
")",
")",
":",
"return",
"[",
"(",
"scale",
"*",
"rs",
".",
"randn",
"(",
"m",
",",
"n",
")",
",",
"# weight matrix",
"scale",
"*",
"rs... | Build a (weights, biases) tuples for all layers. | [
"Build",
"a",
"(",
"weights",
"biases",
")",
"tuples",
"for",
"all",
"layers",
"."
] | python | train |
spacetelescope/pysynphot | pysynphot/binning.py | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/binning.py#L45-L68 | def calculate_bin_widths(edges):
"""
Calculate the widths of wavelengths bins given their edges.
Parameters
----------
edges : array_like
Sequence of bin edges. Must be 1D and have at least two values.
Returns
-------
widths : ndarray
Array of bin widths. Will be 1D and... | [
"def",
"calculate_bin_widths",
"(",
"edges",
")",
":",
"edges",
"=",
"np",
".",
"asanyarray",
"(",
"edges",
")",
"if",
"edges",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'edges input array must be 1D.'",
")",
"if",
"edges",
".",
"size",
"<"... | Calculate the widths of wavelengths bins given their edges.
Parameters
----------
edges : array_like
Sequence of bin edges. Must be 1D and have at least two values.
Returns
-------
widths : ndarray
Array of bin widths. Will be 1D and have one less value than ``edges``. | [
"Calculate",
"the",
"widths",
"of",
"wavelengths",
"bins",
"given",
"their",
"edges",
"."
] | python | train |
bkjones/pyrabbit | pyrabbit/api.py | https://github.com/bkjones/pyrabbit/blob/e8a9f74ed5c6bba958994fb9a72c396e6a99ea0f/pyrabbit/api.py#L143-L155 | def get_whoami(self):
"""
A convenience function used in the event that you need to confirm that
the broker thinks you are who you think you are.
:returns dict whoami: Dict structure contains:
* administrator: whether the user is has admin privileges
* name: user... | [
"def",
"get_whoami",
"(",
"self",
")",
":",
"path",
"=",
"Client",
".",
"urls",
"[",
"'whoami'",
"]",
"whoami",
"=",
"self",
".",
"_call",
"(",
"path",
",",
"'GET'",
")",
"return",
"whoami"
] | A convenience function used in the event that you need to confirm that
the broker thinks you are who you think you are.
:returns dict whoami: Dict structure contains:
* administrator: whether the user is has admin privileges
* name: user name
* auth_backend: backend ... | [
"A",
"convenience",
"function",
"used",
"in",
"the",
"event",
"that",
"you",
"need",
"to",
"confirm",
"that",
"the",
"broker",
"thinks",
"you",
"are",
"who",
"you",
"think",
"you",
"are",
"."
] | python | train |
CZ-NIC/yangson | yangson/schemanode.py | https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemanode.py#L201-L205 | def _iname2qname(self, iname: InstanceName) -> QualName:
"""Translate instance name to qualified name in the receiver's context.
"""
p, s, loc = iname.partition(":")
return (loc, p) if s else (p, self.ns) | [
"def",
"_iname2qname",
"(",
"self",
",",
"iname",
":",
"InstanceName",
")",
"->",
"QualName",
":",
"p",
",",
"s",
",",
"loc",
"=",
"iname",
".",
"partition",
"(",
"\":\"",
")",
"return",
"(",
"loc",
",",
"p",
")",
"if",
"s",
"else",
"(",
"p",
","... | Translate instance name to qualified name in the receiver's context. | [
"Translate",
"instance",
"name",
"to",
"qualified",
"name",
"in",
"the",
"receiver",
"s",
"context",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2086-L2225 | def dot_product_unmasked_self_attention_relative_2d(
q, k, v, bias, max_relative_position=None, dropout_rate=0.0,
image_shapes=None, name=None, make_image_summary=True,
dropout_broadcast_dims=None, heads_share_relative_embedding=False,
add_relative_to_values=False):
"""Calculate relative position unma... | [
"def",
"dot_product_unmasked_self_attention_relative_2d",
"(",
"q",
",",
"k",
",",
"v",
",",
"bias",
",",
"max_relative_position",
"=",
"None",
",",
"dropout_rate",
"=",
"0.0",
",",
"image_shapes",
"=",
"None",
",",
"name",
"=",
"None",
",",
"make_image_summary"... | Calculate relative position unmasked dot-product self-attention 2d.
The attention calculation is augmented with learned representations for the
relative position between each element in q and each element in k and v in
height and width dimensions. for query index (i,j) and key index (l, m),
the logit is q_i k... | [
"Calculate",
"relative",
"position",
"unmasked",
"dot",
"-",
"product",
"self",
"-",
"attention",
"2d",
"."
] | python | train |
tensorflow/datasets | tensorflow_datasets/core/features/text/subword_text_encoder.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/subword_text_encoder.py#L261-L336 | def build_from_corpus(cls,
corpus_generator,
target_vocab_size,
max_subword_length=20,
max_corpus_chars=None,
reserved_tokens=None):
"""Builds a `SubwordTextEncoder` based on the `corpus_generator... | [
"def",
"build_from_corpus",
"(",
"cls",
",",
"corpus_generator",
",",
"target_vocab_size",
",",
"max_subword_length",
"=",
"20",
",",
"max_corpus_chars",
"=",
"None",
",",
"reserved_tokens",
"=",
"None",
")",
":",
"reserved_tokens",
"=",
"reserved_tokens",
"or",
"... | Builds a `SubwordTextEncoder` based on the `corpus_generator`.
Args:
corpus_generator: generator yielding `str`, from which subwords will be
constructed.
target_vocab_size: `int`, approximate size of the vocabulary to create.
max_subword_length: `int`, maximum length of a subword. Note th... | [
"Builds",
"a",
"SubwordTextEncoder",
"based",
"on",
"the",
"corpus_generator",
"."
] | python | train |
skibblenybbles/django-commando | commando/management/base.py | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L194-L203 | def get_option_lists(self):
"""
A hook to override the option lists used to generate option names
and defaults.
"""
return [self.get_option_list()] + \
[option_list
for name, description, option_list
in self.get_option_groups()... | [
"def",
"get_option_lists",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"get_option_list",
"(",
")",
"]",
"+",
"[",
"option_list",
"for",
"name",
",",
"description",
",",
"option_list",
"in",
"self",
".",
"get_option_groups",
"(",
")",
"]"
] | A hook to override the option lists used to generate option names
and defaults. | [
"A",
"hook",
"to",
"override",
"the",
"option",
"lists",
"used",
"to",
"generate",
"option",
"names",
"and",
"defaults",
"."
] | python | train |
humilis/humilis-lambdautils | lambdautils/utils.py | https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/utils.py#L127-L133 | def replace_event_annotations(event, newanns):
"""Replace event annotations with the provided ones."""
_humilis = event.get("_humilis", {})
if not _humilis:
event["_humilis"] = {"annotation": newanns}
else:
event["_humilis"]["annotation"] = newanns | [
"def",
"replace_event_annotations",
"(",
"event",
",",
"newanns",
")",
":",
"_humilis",
"=",
"event",
".",
"get",
"(",
"\"_humilis\"",
",",
"{",
"}",
")",
"if",
"not",
"_humilis",
":",
"event",
"[",
"\"_humilis\"",
"]",
"=",
"{",
"\"annotation\"",
":",
"... | Replace event annotations with the provided ones. | [
"Replace",
"event",
"annotations",
"with",
"the",
"provided",
"ones",
"."
] | python | train |
tcalmant/ipopo | pelix/framework.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1277-L1321 | def uninstall_bundle(self, bundle):
# type: (Bundle) -> None
"""
Ends the uninstallation of the given bundle (must be called by Bundle)
:param bundle: The bundle to uninstall
:raise BundleException: Invalid bundle
"""
if bundle is None:
# Do nothing
... | [
"def",
"uninstall_bundle",
"(",
"self",
",",
"bundle",
")",
":",
"# type: (Bundle) -> None",
"if",
"bundle",
"is",
"None",
":",
"# Do nothing",
"return",
"with",
"self",
".",
"__bundles_lock",
":",
"# Stop the bundle first",
"bundle",
".",
"stop",
"(",
")",
"bun... | Ends the uninstallation of the given bundle (must be called by Bundle)
:param bundle: The bundle to uninstall
:raise BundleException: Invalid bundle | [
"Ends",
"the",
"uninstallation",
"of",
"the",
"given",
"bundle",
"(",
"must",
"be",
"called",
"by",
"Bundle",
")"
] | python | train |
openstack/python-monascaclient | monascaclient/client.py | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/client.py#L45-L69 | def _session(kwargs):
"""Returns or reuses session.
Method takes care of providing instance of
session object for the client.
:param kwargs: all params (without api_version) client was initialized with
:type kwargs: dict
:returns: session object
:rtype keystoneauth1.session.Session
"... | [
"def",
"_session",
"(",
"kwargs",
")",
":",
"if",
"'session'",
"in",
"kwargs",
":",
"LOG",
".",
"debug",
"(",
"'Reusing session'",
")",
"sess",
"=",
"kwargs",
".",
"get",
"(",
"'session'",
")",
"if",
"not",
"isinstance",
"(",
"sess",
",",
"k_session",
... | Returns or reuses session.
Method takes care of providing instance of
session object for the client.
:param kwargs: all params (without api_version) client was initialized with
:type kwargs: dict
:returns: session object
:rtype keystoneauth1.session.Session | [
"Returns",
"or",
"reuses",
"session",
"."
] | python | train |
waqasbhatti/astrobase | astrobase/lcfit/transits.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/transits.py#L571-L625 | def _log_likelihood_transit_plus_line(theta, params, model, t, data_flux,
err_flux, priorbounds):
'''
Given a batman TransitModel and its proposed parameters (theta), update the
batman params object with the proposed parameters and evaluate the gaussian
likelihood.
... | [
"def",
"_log_likelihood_transit_plus_line",
"(",
"theta",
",",
"params",
",",
"model",
",",
"t",
",",
"data_flux",
",",
"err_flux",
",",
"priorbounds",
")",
":",
"u",
"=",
"[",
"]",
"for",
"ix",
",",
"key",
"in",
"enumerate",
"(",
"sorted",
"(",
"priorbo... | Given a batman TransitModel and its proposed parameters (theta), update the
batman params object with the proposed parameters and evaluate the gaussian
likelihood.
Note: the priorbounds are only needed to parse theta. | [
"Given",
"a",
"batman",
"TransitModel",
"and",
"its",
"proposed",
"parameters",
"(",
"theta",
")",
"update",
"the",
"batman",
"params",
"object",
"with",
"the",
"proposed",
"parameters",
"and",
"evaluate",
"the",
"gaussian",
"likelihood",
"."
] | python | valid |
dancsalo/TensorBase | tensorbase/base.py | https://github.com/dancsalo/TensorBase/blob/3d42a326452bd03427034916ff2fb90730020204/tensorbase/base.py#L312-L320 | def _init_uninit_vars(self):
""" Initialize all other trainable variables, i.e. those which are uninitialized """
uninit_vars = self.sess.run(tf.report_uninitialized_variables())
vars_list = list()
for v in uninit_vars:
var = v.decode("utf-8")
vars_list.append(var... | [
"def",
"_init_uninit_vars",
"(",
"self",
")",
":",
"uninit_vars",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"tf",
".",
"report_uninitialized_variables",
"(",
")",
")",
"vars_list",
"=",
"list",
"(",
")",
"for",
"v",
"in",
"uninit_vars",
":",
"var",
"=",... | Initialize all other trainable variables, i.e. those which are uninitialized | [
"Initialize",
"all",
"other",
"trainable",
"variables",
"i",
".",
"e",
".",
"those",
"which",
"are",
"uninitialized"
] | python | train |
kivy/python-for-android | pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/ext.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/ext.py#L381-L446 | def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,
babel_style=True):
"""Extract localizable strings from the given template node. Per
default this function returns matches in babel style that means non string
parameters as well as keyword arguments are returned as `None`.... | [
"def",
"extract_from_ast",
"(",
"node",
",",
"gettext_functions",
"=",
"GETTEXT_FUNCTIONS",
",",
"babel_style",
"=",
"True",
")",
":",
"for",
"node",
"in",
"node",
".",
"find_all",
"(",
"nodes",
".",
"Call",
")",
":",
"if",
"not",
"isinstance",
"(",
"node"... | Extract localizable strings from the given template node. Per
default this function returns matches in babel style that means non string
parameters as well as keyword arguments are returned as `None`. This
allows Babel to figure out what you really meant if you are using
gettext functions that allow k... | [
"Extract",
"localizable",
"strings",
"from",
"the",
"given",
"template",
"node",
".",
"Per",
"default",
"this",
"function",
"returns",
"matches",
"in",
"babel",
"style",
"that",
"means",
"non",
"string",
"parameters",
"as",
"well",
"as",
"keyword",
"arguments",
... | python | train |
linuxsoftware/ls.joyous | ls/joyous/models/events.py | https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1153-L1162 | def _getMyFirstDatetimeTo(self):
"""
The datetime this event first finished, or None if it never did.
"""
myFirstDt = self._getMyFirstDatetimeFrom()
if myFirstDt is not None:
daysDelta = dt.timedelta(days=self.num_days - 1)
return getAwareDatetime(myFirstD... | [
"def",
"_getMyFirstDatetimeTo",
"(",
"self",
")",
":",
"myFirstDt",
"=",
"self",
".",
"_getMyFirstDatetimeFrom",
"(",
")",
"if",
"myFirstDt",
"is",
"not",
"None",
":",
"daysDelta",
"=",
"dt",
".",
"timedelta",
"(",
"days",
"=",
"self",
".",
"num_days",
"-"... | The datetime this event first finished, or None if it never did. | [
"The",
"datetime",
"this",
"event",
"first",
"finished",
"or",
"None",
"if",
"it",
"never",
"did",
"."
] | python | train |
janpipek/physt | physt/histogram1d.py | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L166-L168 | def numpy_like(self) -> Tuple[np.ndarray, np.ndarray]:
"""Return """
return self.frequencies, self.numpy_bins | [
"def",
"numpy_like",
"(",
"self",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
"]",
":",
"return",
"self",
".",
"frequencies",
",",
"self",
".",
"numpy_bins"
] | Return | [
"Return"
] | python | train |
eruvanos/openbrokerapi | openbrokerapi/request_filter.py | https://github.com/eruvanos/openbrokerapi/blob/29d514e5932f2eac27e03995dd41c8cecf40bb10/openbrokerapi/request_filter.py#L24-L42 | def check_originating_identity():
"""
Check and decode the "X-Broker-API-Originating-Identity" header
https://github.com/openservicebrokerapi/servicebroker/blob/v2.13/spec.md#originating-identity
"""
from flask import request, json
if "X-Broker-API-Originating-Identity" in request.headers:
... | [
"def",
"check_originating_identity",
"(",
")",
":",
"from",
"flask",
"import",
"request",
",",
"json",
"if",
"\"X-Broker-API-Originating-Identity\"",
"in",
"request",
".",
"headers",
":",
"try",
":",
"platform",
",",
"value",
"=",
"request",
".",
"headers",
"[",... | Check and decode the "X-Broker-API-Originating-Identity" header
https://github.com/openservicebrokerapi/servicebroker/blob/v2.13/spec.md#originating-identity | [
"Check",
"and",
"decode",
"the",
"X",
"-",
"Broker",
"-",
"API",
"-",
"Originating",
"-",
"Identity",
"header",
"https",
":",
"//",
"github",
".",
"com",
"/",
"openservicebrokerapi",
"/",
"servicebroker",
"/",
"blob",
"/",
"v2",
".",
"13",
"/",
"spec",
... | python | train |
idlesign/uwsgiconf | uwsgiconf/options/routing_routers.py | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/options/routing_routers.py#L319-L364 | def set_basic_params(
self, workers=None, zerg_server=None, fallback_node=None, concurrent_events=None,
cheap_mode=None, stats_server=None, quiet=None, buffer_size=None,
keepalive=None, resubscribe_addresses=None):
"""
:param int workers: Number of worker processes to... | [
"def",
"set_basic_params",
"(",
"self",
",",
"workers",
"=",
"None",
",",
"zerg_server",
"=",
"None",
",",
"fallback_node",
"=",
"None",
",",
"concurrent_events",
"=",
"None",
",",
"cheap_mode",
"=",
"None",
",",
"stats_server",
"=",
"None",
",",
"quiet",
... | :param int workers: Number of worker processes to spawn.
:param str|unicode zerg_server: Attach the router to a zerg server.
:param str|unicode fallback_node: Fallback to the specified node in case of error.
:param int concurrent_events: Set the maximum number of concurrent events router can ... | [
":",
"param",
"int",
"workers",
":",
"Number",
"of",
"worker",
"processes",
"to",
"spawn",
"."
] | python | train |
mcrute/pydora | pandora/transport.py | https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pandora/transport.py#L29-L65 | def retries(max_tries, exceptions=(Exception,)):
"""Function decorator implementing retrying logic.
exceptions: A tuple of exception classes; default (Exception,)
The decorator will call the function up to max_tries times if it raises
an exception.
By default it catches instances of the Exception... | [
"def",
"retries",
"(",
"max_tries",
",",
"exceptions",
"=",
"(",
"Exception",
",",
")",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"retries_left",
"=",
"max_tries",
"wh... | Function decorator implementing retrying logic.
exceptions: A tuple of exception classes; default (Exception,)
The decorator will call the function up to max_tries times if it raises
an exception.
By default it catches instances of the Exception class and subclasses.
This will recover after all b... | [
"Function",
"decorator",
"implementing",
"retrying",
"logic",
"."
] | python | valid |
saltstack/salt | salt/platform/win.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/platform/win.py#L1118-L1128 | def impersonate_sid(sid, session_id=None, privs=None):
'''
Find an existing process token for the given sid and impersonate the token.
'''
for tok in enumerate_tokens(sid, session_id, privs):
tok = dup_token(tok)
elevate_token(tok)
if win32security.ImpersonateLoggedOnUser(tok) ==... | [
"def",
"impersonate_sid",
"(",
"sid",
",",
"session_id",
"=",
"None",
",",
"privs",
"=",
"None",
")",
":",
"for",
"tok",
"in",
"enumerate_tokens",
"(",
"sid",
",",
"session_id",
",",
"privs",
")",
":",
"tok",
"=",
"dup_token",
"(",
"tok",
")",
"elevate... | Find an existing process token for the given sid and impersonate the token. | [
"Find",
"an",
"existing",
"process",
"token",
"for",
"the",
"given",
"sid",
"and",
"impersonate",
"the",
"token",
"."
] | python | train |
shaypal5/cachier | cachier/core.py | https://github.com/shaypal5/cachier/blob/998233b97b9d905292e9d33413677f98d131f17d/cachier/core.py#L74-L185 | def cachier(stale_after=None, next_time=False, pickle_reload=True,
mongetter=None):
"""A persistent, stale-free memoization decorator.
The positional and keyword arguments to the wrapped function must be
hashable (i.e. Python's immutable built-in objects, not mutable
containers). Also, noti... | [
"def",
"cachier",
"(",
"stale_after",
"=",
"None",
",",
"next_time",
"=",
"False",
",",
"pickle_reload",
"=",
"True",
",",
"mongetter",
"=",
"None",
")",
":",
"# print('Inside the wrapper maker')",
"# print('mongetter={}'.format(mongetter))",
"# print('stale_after={}'.for... | A persistent, stale-free memoization decorator.
The positional and keyword arguments to the wrapped function must be
hashable (i.e. Python's immutable built-in objects, not mutable
containers). Also, notice that since objects which are instances of
user-defined classes are hashable but all compare uneq... | [
"A",
"persistent",
"stale",
"-",
"free",
"memoization",
"decorator",
"."
] | python | train |
saltstack/salt | salt/modules/cimc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L542-L608 | def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
Th... | [
"def",
"mount_share",
"(",
"name",
"=",
"None",
",",
"remote_share",
"=",
"None",
",",
"remote_file",
"=",
"None",
",",
"mount_type",
"=",
"\"nfs\"",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"raise... | Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media ... | [
"Mounts",
"a",
"remote",
"file",
"through",
"a",
"remote",
"share",
".",
"Currently",
"this",
"feature",
"is",
"supported",
"in",
"version",
"1",
".",
"5",
"or",
"greater",
".",
"The",
"remote",
"share",
"can",
"be",
"either",
"NFS",
"CIFS",
"or",
"WWW",... | python | train |
raamana/pyradigm | pyradigm/pyradigm.py | https://github.com/raamana/pyradigm/blob/8ffb7958329c88b09417087b86887a3c92f438c2/pyradigm/pyradigm.py#L1576-L1604 | def cli_run():
"""
Command line interface
This interface saves you coding effort to:
- display basic info (classes, sizes etc) about datasets
- display meta data (class membership) for samples
- perform basic arithmetic (add multiple classes or feature sets)
"""
path_lis... | [
"def",
"cli_run",
"(",
")",
":",
"path_list",
",",
"meta_requested",
",",
"summary_requested",
",",
"add_path_list",
",",
"out_path",
"=",
"parse_args",
"(",
")",
"# printing info if requested",
"if",
"path_list",
":",
"for",
"ds_path",
"in",
"path_list",
":",
"... | Command line interface
This interface saves you coding effort to:
- display basic info (classes, sizes etc) about datasets
- display meta data (class membership) for samples
- perform basic arithmetic (add multiple classes or feature sets) | [
"Command",
"line",
"interface"
] | python | train |
atztogo/phonopy | phonopy/structure/spglib.py | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L301-L343 | def get_pointgroup(rotations):
"""Return point group in international table symbol and number.
The symbols are mapped to the numbers as follows:
1 "1 "
2 "-1 "
3 "2 "
4 "m "
5 "2/m "
6 "222 "
7 "mm2 "
8 "mmm "
9 "4 "
10 "-4 "
11... | [
"def",
"get_pointgroup",
"(",
"rotations",
")",
":",
"_set_no_error",
"(",
")",
"# (symbol, pointgroup_number, transformation_matrix)",
"pointgroup",
"=",
"spg",
".",
"pointgroup",
"(",
"np",
".",
"array",
"(",
"rotations",
",",
"dtype",
"=",
"'intc'",
",",
"order... | Return point group in international table symbol and number.
The symbols are mapped to the numbers as follows:
1 "1 "
2 "-1 "
3 "2 "
4 "m "
5 "2/m "
6 "222 "
7 "mm2 "
8 "mmm "
9 "4 "
10 "-4 "
11 "4/m "
12 "422 "
13 "4mm... | [
"Return",
"point",
"group",
"in",
"international",
"table",
"symbol",
"and",
"number",
"."
] | python | train |
pmichali/whodunit | whodunit/__init__.py | https://github.com/pmichali/whodunit/blob/eed9107533766d716469e35fbb647a39dfa07035/whodunit/__init__.py#L359-L382 | def determine_coverage(cls, coverage_file):
"""Scan the summary section of report looking for coverage data.
Will see CSS class with "stm mis" (missing coverage), or "stm par"
(partial coverage), and can extract line number. Will get file name
from title tag.
"""
lines =... | [
"def",
"determine_coverage",
"(",
"cls",
",",
"coverage_file",
")",
":",
"lines",
"=",
"[",
"]",
"source_file",
"=",
"'ERROR'",
"for",
"line",
"in",
"coverage_file",
":",
"m",
"=",
"title_re",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"if",
"m",
... | Scan the summary section of report looking for coverage data.
Will see CSS class with "stm mis" (missing coverage), or "stm par"
(partial coverage), and can extract line number. Will get file name
from title tag. | [
"Scan",
"the",
"summary",
"section",
"of",
"report",
"looking",
"for",
"coverage",
"data",
"."
] | python | train |
buzzfeed/caliendo | caliendo/patch.py | https://github.com/buzzfeed/caliendo/blob/1628a10f7782ad67c0422b5cbc9bf4979ac40abc/caliendo/patch.py#L118-L140 | def get_replacement_method(method_to_patch, side_effect=UNDEFINED, rvalue=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, context=UNDEFINED, subsequent_rvalue=UNDEFINED):
"""
Returns the method to be applied in place of an original method. This method either executes a side effect, returns an rvalue, or implem... | [
"def",
"get_replacement_method",
"(",
"method_to_patch",
",",
"side_effect",
"=",
"UNDEFINED",
",",
"rvalue",
"=",
"UNDEFINED",
",",
"ignore",
"=",
"UNDEFINED",
",",
"callback",
"=",
"UNDEFINED",
",",
"context",
"=",
"UNDEFINED",
",",
"subsequent_rvalue",
"=",
"... | Returns the method to be applied in place of an original method. This method either executes a side effect, returns an rvalue, or implements caching in place of the method_to_patch
:param function method_to_patch: A reference to the method that will be patched.
:param mixed side_effect: The side effect to exec... | [
"Returns",
"the",
"method",
"to",
"be",
"applied",
"in",
"place",
"of",
"an",
"original",
"method",
".",
"This",
"method",
"either",
"executes",
"a",
"side",
"effect",
"returns",
"an",
"rvalue",
"or",
"implements",
"caching",
"in",
"place",
"of",
"the",
"m... | python | train |
gabstopper/smc-python | smc/core/node.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/node.py#L517-L530 | def ssh(self, enable=True, comment=None):
"""
Enable or disable SSH
:param bool enable: enable or disable SSH daemon
:param str comment: optional comment for audit
:raises NodeCommandFailed: cannot enable SSH daemon
:return: None
"""
self.make_request(
... | [
"def",
"ssh",
"(",
"self",
",",
"enable",
"=",
"True",
",",
"comment",
"=",
"None",
")",
":",
"self",
".",
"make_request",
"(",
"NodeCommandFailed",
",",
"method",
"=",
"'update'",
",",
"resource",
"=",
"'ssh'",
",",
"params",
"=",
"{",
"'enable'",
":"... | Enable or disable SSH
:param bool enable: enable or disable SSH daemon
:param str comment: optional comment for audit
:raises NodeCommandFailed: cannot enable SSH daemon
:return: None | [
"Enable",
"or",
"disable",
"SSH"
] | python | train |
qacafe/cdrouter.py | cdrouter/packages.py | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/packages.py#L301-L310 | def analyze(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get a list of tests that will be skipped for a package.
:param id: Package ID as an int.
:return: :class:`packages.Analysis <packages.Analysis>` object
:rtype: packages.Analysis
"""
schema = Analy... | [
"def",
"analyze",
"(",
"self",
",",
"id",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"AnalysisSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"base",
"+",
"str",
"(",
"id",
")",
"+",
... | Get a list of tests that will be skipped for a package.
:param id: Package ID as an int.
:return: :class:`packages.Analysis <packages.Analysis>` object
:rtype: packages.Analysis | [
"Get",
"a",
"list",
"of",
"tests",
"that",
"will",
"be",
"skipped",
"for",
"a",
"package",
"."
] | python | train |
gboeing/osmnx | osmnx/utils.py | https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L1055-L1071 | def round_point_coords(pt, precision):
"""
Round the coordinates of a shapely Point to some decimal precision.
Parameters
----------
pt : shapely Point
the Point to round the coordinates of
precision : int
decimal precision to round coordinates to
Returns
-------
Po... | [
"def",
"round_point_coords",
"(",
"pt",
",",
"precision",
")",
":",
"return",
"Point",
"(",
"[",
"round",
"(",
"x",
",",
"precision",
")",
"for",
"x",
"in",
"pt",
".",
"coords",
"[",
"0",
"]",
"]",
")"
] | Round the coordinates of a shapely Point to some decimal precision.
Parameters
----------
pt : shapely Point
the Point to round the coordinates of
precision : int
decimal precision to round coordinates to
Returns
-------
Point | [
"Round",
"the",
"coordinates",
"of",
"a",
"shapely",
"Point",
"to",
"some",
"decimal",
"precision",
"."
] | python | train |
solvebio/solvebio-python | solvebio/utils/tabulate.py | https://github.com/solvebio/solvebio-python/blob/b29614643043afd19c1d8074e8f25c6700d51a73/solvebio/utils/tabulate.py#L498-L505 | def _mediawiki_cell_attrs(row, colaligns):
"Prefix every cell in a row with an HTML alignment attribute."
alignment = {"left": '',
"right": 'align="right"| ',
"center": 'align="center"| ',
"decimal": 'align="right"| '}
row2 = [alignment[a] + c for c, a in z... | [
"def",
"_mediawiki_cell_attrs",
"(",
"row",
",",
"colaligns",
")",
":",
"alignment",
"=",
"{",
"\"left\"",
":",
"''",
",",
"\"right\"",
":",
"'align=\"right\"| '",
",",
"\"center\"",
":",
"'align=\"center\"| '",
",",
"\"decimal\"",
":",
"'align=\"right\"| '",
"}",... | Prefix every cell in a row with an HTML alignment attribute. | [
"Prefix",
"every",
"cell",
"in",
"a",
"row",
"with",
"an",
"HTML",
"alignment",
"attribute",
"."
] | python | test |
frnsys/broca | broca/knowledge/phrases.py | https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/knowledge/phrases.py#L6-L26 | def train_phrases(paths, out='data/bigram_model.phrases', tokenizer=word_tokenize, **kwargs):
"""
Train a bigram phrase model on a list of files.
"""
n = 0
for path in paths:
print('Counting lines for {0}...'.format(path))
n += sum(1 for line in open(path, 'r'))
print('Processing... | [
"def",
"train_phrases",
"(",
"paths",
",",
"out",
"=",
"'data/bigram_model.phrases'",
",",
"tokenizer",
"=",
"word_tokenize",
",",
"*",
"*",
"kwargs",
")",
":",
"n",
"=",
"0",
"for",
"path",
"in",
"paths",
":",
"print",
"(",
"'Counting lines for {0}...'",
".... | Train a bigram phrase model on a list of files. | [
"Train",
"a",
"bigram",
"phrase",
"model",
"on",
"a",
"list",
"of",
"files",
"."
] | python | train |
rossant/ipymd | ipymd/core/format_manager.py | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L38-L46 | def _is_path(s):
"""Return whether an object is a path."""
if isinstance(s, string_types):
try:
return op.exists(s)
except (OSError, ValueError):
return False
else:
return False | [
"def",
"_is_path",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"string_types",
")",
":",
"try",
":",
"return",
"op",
".",
"exists",
"(",
"s",
")",
"except",
"(",
"OSError",
",",
"ValueError",
")",
":",
"return",
"False",
"else",
":",
"re... | Return whether an object is a path. | [
"Return",
"whether",
"an",
"object",
"is",
"a",
"path",
"."
] | python | train |
gwastro/pycbc | pycbc/pnutils.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/pnutils.py#L814-L879 | def hybridEnergy(v, m1, m2, chi1, chi2, qm1, qm2):
"""Return hybrid MECO energy.
Return the hybrid energy [eq. (6)] whose minimum defines the hybrid MECO
up to 3.5PN (including the 3PN spin-spin)
Parameters
----------
m1 : float
Mass of the primary object in solar masses.
m2 : floa... | [
"def",
"hybridEnergy",
"(",
"v",
",",
"m1",
",",
"m2",
",",
"chi1",
",",
"chi2",
",",
"qm1",
",",
"qm2",
")",
":",
"pi_sq",
"=",
"numpy",
".",
"pi",
"**",
"2",
"v2",
",",
"v3",
",",
"v4",
",",
"v5",
",",
"v6",
",",
"v7",
"=",
"v",
"**",
"... | Return hybrid MECO energy.
Return the hybrid energy [eq. (6)] whose minimum defines the hybrid MECO
up to 3.5PN (including the 3PN spin-spin)
Parameters
----------
m1 : float
Mass of the primary object in solar masses.
m2 : float
Mass of the secondary object in solar masses.
... | [
"Return",
"hybrid",
"MECO",
"energy",
"."
] | python | train |
h2oai/h2o-3 | h2o-py/h2o/model/clustering.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/clustering.py#L151-L157 | def centers_std(self):
"""The standardized centers for the kmeans model."""
o = self._model_json["output"]
cvals = o["centers_std"].cell_values
centers_std = [list(cval[1:]) for cval in cvals]
centers_std = [list(x) for x in zip(*centers_std)]
return centers_std | [
"def",
"centers_std",
"(",
"self",
")",
":",
"o",
"=",
"self",
".",
"_model_json",
"[",
"\"output\"",
"]",
"cvals",
"=",
"o",
"[",
"\"centers_std\"",
"]",
".",
"cell_values",
"centers_std",
"=",
"[",
"list",
"(",
"cval",
"[",
"1",
":",
"]",
")",
"for... | The standardized centers for the kmeans model. | [
"The",
"standardized",
"centers",
"for",
"the",
"kmeans",
"model",
"."
] | python | test |
quodlibet/mutagen | mutagen/_util.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L686-L741 | def mmap_move(fileobj, dest, src, count):
"""Mmaps the file object if possible and moves 'count' data
from 'src' to 'dest'. All data has to be inside the file size
(enlarging the file through this function isn't possible)
Will adjust the file offset.
Args:
fileobj (fileobj)
dest (i... | [
"def",
"mmap_move",
"(",
"fileobj",
",",
"dest",
",",
"src",
",",
"count",
")",
":",
"assert",
"mmap",
"is",
"not",
"None",
",",
"\"no mmap support\"",
"if",
"dest",
"<",
"0",
"or",
"src",
"<",
"0",
"or",
"count",
"<",
"0",
":",
"raise",
"ValueError"... | Mmaps the file object if possible and moves 'count' data
from 'src' to 'dest'. All data has to be inside the file size
(enlarging the file through this function isn't possible)
Will adjust the file offset.
Args:
fileobj (fileobj)
dest (int): The destination offset
src (int): Th... | [
"Mmaps",
"the",
"file",
"object",
"if",
"possible",
"and",
"moves",
"count",
"data",
"from",
"src",
"to",
"dest",
".",
"All",
"data",
"has",
"to",
"be",
"inside",
"the",
"file",
"size",
"(",
"enlarging",
"the",
"file",
"through",
"this",
"function",
"isn... | python | train |
pywbem/pywbem | pywbem/cim_operations.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L2506-L2618 | def EnumerateInstanceNames(self, ClassName, namespace=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Enumerate the instance paths of instances of a class (including
instances of its subclasses) in a namespace.
This method performs the EnumerateInstanceNames ope... | [
"def",
"EnumerateInstanceNames",
"(",
"self",
",",
"ClassName",
",",
"namespace",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid-name,line-too-long",
"exc",
"=",
"None",
"instancenames",
"=",
"None",
"method_name",
"=",
"'EnumerateInstance... | Enumerate the instance paths of instances of a class (including
instances of its subclasses) in a namespace.
This method performs the EnumerateInstanceNames operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the ... | [
"Enumerate",
"the",
"instance",
"paths",
"of",
"instances",
"of",
"a",
"class",
"(",
"including",
"instances",
"of",
"its",
"subclasses",
")",
"in",
"a",
"namespace",
"."
] | python | train |
ff0000/scarlet | scarlet/cms/renders.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/renders.py#L32-L45 | def update_kwargs(self, request, **kwargs):
"""
Hook for adding data to the context before
rendering a template.
:param kwargs: The current context keyword arguments.
:param request: The current request object.
"""
if not 'base' in kwargs:
kwargs['bas... | [
"def",
"update_kwargs",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"'base'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'base'",
"]",
"=",
"self",
".",
"base",
"if",
"request",
".",
"is_ajax",
"(",
")",
"or",
"request",
... | Hook for adding data to the context before
rendering a template.
:param kwargs: The current context keyword arguments.
:param request: The current request object. | [
"Hook",
"for",
"adding",
"data",
"to",
"the",
"context",
"before",
"rendering",
"a",
"template",
"."
] | python | train |
SKA-ScienceDataProcessor/integration-prototype | sip/execution_control/processing_controller/scheduler/scheduler.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/processing_controller/scheduler/scheduler.py#L99-L108 | def _processing_controller_status(self):
"""Report on the status of the Processing Block queue(s)."""
LOG.info('Starting Processing Block queue reporter.')
while True:
LOG.info('PB queue length = %d', len(self._queue))
time.sleep(self._report_interval)
if acti... | [
"def",
"_processing_controller_status",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"'Starting Processing Block queue reporter.'",
")",
"while",
"True",
":",
"LOG",
".",
"info",
"(",
"'PB queue length = %d'",
",",
"len",
"(",
"self",
".",
"_queue",
")",
")",... | Report on the status of the Processing Block queue(s). | [
"Report",
"on",
"the",
"status",
"of",
"the",
"Processing",
"Block",
"queue",
"(",
"s",
")",
"."
] | python | train |
mikedh/trimesh | trimesh/path/path.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/path.py#L1390-L1399 | def path_valid(self):
"""
Returns
----------
path_valid: (n,) bool, indexes of self.paths self.polygons_closed
which are valid polygons
"""
valid = [i is not None for i in self.polygons_closed]
valid = np.array(valid, dtype=np.bool)
... | [
"def",
"path_valid",
"(",
"self",
")",
":",
"valid",
"=",
"[",
"i",
"is",
"not",
"None",
"for",
"i",
"in",
"self",
".",
"polygons_closed",
"]",
"valid",
"=",
"np",
".",
"array",
"(",
"valid",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"return",
"... | Returns
----------
path_valid: (n,) bool, indexes of self.paths self.polygons_closed
which are valid polygons | [
"Returns",
"----------",
"path_valid",
":",
"(",
"n",
")",
"bool",
"indexes",
"of",
"self",
".",
"paths",
"self",
".",
"polygons_closed",
"which",
"are",
"valid",
"polygons"
] | python | train |
PMEAL/OpenPNM | openpnm/algorithms/StokesFlow.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/algorithms/StokesFlow.py#L74-L113 | def calc_effective_permeability(self, inlets=None, outlets=None,
domain_area=None, domain_length=None):
r"""
This calculates the effective permeability in this linear transport
algorithm.
Parameters
----------
inlets : array_like
... | [
"def",
"calc_effective_permeability",
"(",
"self",
",",
"inlets",
"=",
"None",
",",
"outlets",
"=",
"None",
",",
"domain_area",
"=",
"None",
",",
"domain_length",
"=",
"None",
")",
":",
"phase",
"=",
"self",
".",
"project",
".",
"phases",
"(",
")",
"[",
... | r"""
This calculates the effective permeability in this linear transport
algorithm.
Parameters
----------
inlets : array_like
The pores where the inlet pressure boundary conditions were
applied. If not given an attempt is made to infer them from the
... | [
"r",
"This",
"calculates",
"the",
"effective",
"permeability",
"in",
"this",
"linear",
"transport",
"algorithm",
"."
] | python | train |
agoragames/chai | chai/expectation.py | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/expectation.py#L226-L241 | def return_value(self):
"""
Returns the value for this expectation or raises the proper exception.
"""
if self._raises:
# Handle exceptions
if inspect.isclass(self._raises):
raise self._raises()
else:
raise self._raises
... | [
"def",
"return_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_raises",
":",
"# Handle exceptions",
"if",
"inspect",
".",
"isclass",
"(",
"self",
".",
"_raises",
")",
":",
"raise",
"self",
".",
"_raises",
"(",
")",
"else",
":",
"raise",
"self",
"."... | Returns the value for this expectation or raises the proper exception. | [
"Returns",
"the",
"value",
"for",
"this",
"expectation",
"or",
"raises",
"the",
"proper",
"exception",
"."
] | python | train |
jorgenschaefer/elpy | elpy/blackutil.py | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/blackutil.py#L21-L42 | def fix_code(code, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
if not black:
raise Fault("black not installed", code=400)
try:
if parse_version(black.__version__) < parse_version("19.0"):
reformatted_source = black.format_file_contents(
... | [
"def",
"fix_code",
"(",
"code",
",",
"directory",
")",
":",
"if",
"not",
"black",
":",
"raise",
"Fault",
"(",
"\"black not installed\"",
",",
"code",
"=",
"400",
")",
"try",
":",
"if",
"parse_version",
"(",
"black",
".",
"__version__",
")",
"<",
"parse_v... | Formats Python code to conform to the PEP 8 style guide. | [
"Formats",
"Python",
"code",
"to",
"conform",
"to",
"the",
"PEP",
"8",
"style",
"guide",
"."
] | python | train |
getpelican/pelican-plugins | rmd_reader/rmd_reader.py | https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/rmd_reader/rmd_reader.py#L69-L118 | def read(self, filename):
"""Parse content and metadata of markdown files"""
QUIET = self.settings.get('RMD_READER_KNITR_QUIET', True)
ENCODING = self.settings.get('RMD_READER_KNITR_ENCODING', 'UTF-8')
CLEANUP = self.settings.get('RMD_READER_CLEANUP', True)
RENAME_PLOT = self.set... | [
"def",
"read",
"(",
"self",
",",
"filename",
")",
":",
"QUIET",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"'RMD_READER_KNITR_QUIET'",
",",
"True",
")",
"ENCODING",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"'RMD_READER_KNITR_ENCODING'",
",",
"'UT... | Parse content and metadata of markdown files | [
"Parse",
"content",
"and",
"metadata",
"of",
"markdown",
"files"
] | python | train |
totalgood/nlpia | src/nlpia/futil.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/futil.py#L235-L275 | def normalize_ext(filepath):
""" Convert file extension(s) to normalized form, e.g. '.tgz' -> '.tar.gz'
Normalized extensions are ordered in reverse order of how they should be processed.
Also extensions are ordered in order of decreasing specificity/detail.
e.g. zip last, then txt/bin, then model type... | [
"def",
"normalize_ext",
"(",
"filepath",
")",
":",
"mapping",
"=",
"tuple",
"(",
"reversed",
"(",
"(",
"(",
"'.tgz'",
",",
"'.tar.gz'",
")",
",",
"(",
"'.bin.gz'",
",",
"'.w2v.bin.gz'",
")",
",",
"(",
"'.6B.zip'",
",",
"'.6b.glove.txt.zip'",
")",
",",
"(... | Convert file extension(s) to normalized form, e.g. '.tgz' -> '.tar.gz'
Normalized extensions are ordered in reverse order of how they should be processed.
Also extensions are ordered in order of decreasing specificity/detail.
e.g. zip last, then txt/bin, then model type, then model dimensionality
.TGZ... | [
"Convert",
"file",
"extension",
"(",
"s",
")",
"to",
"normalized",
"form",
"e",
".",
"g",
".",
".",
"tgz",
"-",
">",
".",
"tar",
".",
"gz"
] | python | train |
Iotic-Labs/py-IoticAgent | src/IoticAgent/Core/Validation.py | https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Validation.py#L104-L113 | def guid_check_convert(guid, allow_none=False):
"""Take a GUID in the form of hex string "32" or "8-4-4-4-12".
Returns hex string "32" or raises ValueError: badly formed hexadecimal UUID string
"""
if isinstance(guid, string_types):
return ensure_unicode(UUID(guid).hex)
... | [
"def",
"guid_check_convert",
"(",
"guid",
",",
"allow_none",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"guid",
",",
"string_types",
")",
":",
"return",
"ensure_unicode",
"(",
"UUID",
"(",
"guid",
")",
".",
"hex",
")",
"elif",
"guid",
"is",
"None",... | Take a GUID in the form of hex string "32" or "8-4-4-4-12".
Returns hex string "32" or raises ValueError: badly formed hexadecimal UUID string | [
"Take",
"a",
"GUID",
"in",
"the",
"form",
"of",
"hex",
"string",
"32",
"or",
"8",
"-",
"4",
"-",
"4",
"-",
"4",
"-",
"12",
".",
"Returns",
"hex",
"string",
"32",
"or",
"raises",
"ValueError",
":",
"badly",
"formed",
"hexadecimal",
"UUID",
"string"
] | python | train |
coleifer/irc | botnet/boss.py | https://github.com/coleifer/irc/blob/f9d2bd6369aafe6cb0916c9406270ca8ecea2080/botnet/boss.py#L51-L56 | def add(self, nick):
"""\
Indicate that the worker with given nick is performing this task
"""
self.data[nick] = ''
self.workers.add(nick) | [
"def",
"add",
"(",
"self",
",",
"nick",
")",
":",
"self",
".",
"data",
"[",
"nick",
"]",
"=",
"''",
"self",
".",
"workers",
".",
"add",
"(",
"nick",
")"
] | \
Indicate that the worker with given nick is performing this task | [
"\\",
"Indicate",
"that",
"the",
"worker",
"with",
"given",
"nick",
"is",
"performing",
"this",
"task"
] | python | test |
twilio/twilio-python | twilio/rest/voice/v1/dialing_permissions/country/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/voice/v1/dialing_permissions/country/__init__.py#L37-L76 | def stream(self, iso_code=values.unset, continent=values.unset,
country_code=values.unset, low_risk_numbers_enabled=values.unset,
high_risk_special_numbers_enabled=values.unset,
high_risk_tollfraud_numbers_enabled=values.unset, limit=None,
page_size=None):
... | [
"def",
"stream",
"(",
"self",
",",
"iso_code",
"=",
"values",
".",
"unset",
",",
"continent",
"=",
"values",
".",
"unset",
",",
"country_code",
"=",
"values",
".",
"unset",
",",
"low_risk_numbers_enabled",
"=",
"values",
".",
"unset",
",",
"high_risk_special... | Streams CountryInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode iso_code: Filter to retrieve the ... | [
"Streams",
"CountryInstance",
"records",
"from",
"the",
"API",
"as",
"a",
"generator",
"stream",
".",
"This",
"operation",
"lazily",
"loads",
"records",
"as",
"efficiently",
"as",
"possible",
"until",
"the",
"limit",
"is",
"reached",
".",
"The",
"results",
"ar... | python | train |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/genetic_balancer.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/genetic_balancer.py#L1087-L1094 | def assignment(self):
"""Return the partition assignment that this state represents."""
return {
partition.name: [
self.brokers[bid].id for bid in self.replicas[pid]
]
for pid, partition in enumerate(self.partitions)
} | [
"def",
"assignment",
"(",
"self",
")",
":",
"return",
"{",
"partition",
".",
"name",
":",
"[",
"self",
".",
"brokers",
"[",
"bid",
"]",
".",
"id",
"for",
"bid",
"in",
"self",
".",
"replicas",
"[",
"pid",
"]",
"]",
"for",
"pid",
",",
"partition",
... | Return the partition assignment that this state represents. | [
"Return",
"the",
"partition",
"assignment",
"that",
"this",
"state",
"represents",
"."
] | python | train |
apache/airflow | airflow/contrib/hooks/spark_sql_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/spark_sql_hook.py#L136-L159 | def run_query(self, cmd="", **kwargs):
"""
Remote Popen (actually execute the Spark-sql query)
:param cmd: command to remotely execute
:param kwargs: extra arguments to Popen (see subprocess.Popen)
"""
spark_sql_cmd = self._prepare_command(cmd)
self._sp = subproc... | [
"def",
"run_query",
"(",
"self",
",",
"cmd",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"spark_sql_cmd",
"=",
"self",
".",
"_prepare_command",
"(",
"cmd",
")",
"self",
".",
"_sp",
"=",
"subprocess",
".",
"Popen",
"(",
"spark_sql_cmd",
",",
"stdout... | Remote Popen (actually execute the Spark-sql query)
:param cmd: command to remotely execute
:param kwargs: extra arguments to Popen (see subprocess.Popen) | [
"Remote",
"Popen",
"(",
"actually",
"execute",
"the",
"Spark",
"-",
"sql",
"query",
")"
] | python | test |
ic-labs/django-icekit | icekit_events/sample_data/migrations/0001_initial.py | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/sample_data/migrations/0001_initial.py#L15-L80 | def forwards(apps, schema_editor):
"""
Create sample events.
"""
starts = timeutils.round_datetime(
when=timezone.now(),
precision=timedelta(days=1),
rounding=timeutils.ROUND_DOWN)
ends = starts + appsettings.DEFAULT_ENDS_DELTA
recurrence_rules = dict(
Recurrence... | [
"def",
"forwards",
"(",
"apps",
",",
"schema_editor",
")",
":",
"starts",
"=",
"timeutils",
".",
"round_datetime",
"(",
"when",
"=",
"timezone",
".",
"now",
"(",
")",
",",
"precision",
"=",
"timedelta",
"(",
"days",
"=",
"1",
")",
",",
"rounding",
"=",... | Create sample events. | [
"Create",
"sample",
"events",
"."
] | python | train |
mbarakaja/braulio | braulio/git.py | https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/git.py#L107-L132 | def tag(self, name=None):
"""Create and list tag objects running git-tag command"""
command = ["git", "tag"]
if not name:
command.extend(
[
"-l",
"--sort=creatordate",
"--format=%(creatordate:short)%09%(ref... | [
"def",
"tag",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"command",
"=",
"[",
"\"git\"",
",",
"\"tag\"",
"]",
"if",
"not",
"name",
":",
"command",
".",
"extend",
"(",
"[",
"\"-l\"",
",",
"\"--sort=creatordate\"",
",",
"\"--format=%(creatordate:short)... | Create and list tag objects running git-tag command | [
"Create",
"and",
"list",
"tag",
"objects",
"running",
"git",
"-",
"tag",
"command"
] | python | train |
saltstack/salt | salt/states/win_network.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_network.py#L168-L206 | def _changes(cur, dns_proto, dns_servers, ip_proto, ip_addrs, gateway):
'''
Compares the current interface against the desired configuration and
returns a dictionary describing the changes that need to be made.
'''
changes = {}
cur_dns_proto = (
'static' if 'Statically Configured DNS Ser... | [
"def",
"_changes",
"(",
"cur",
",",
"dns_proto",
",",
"dns_servers",
",",
"ip_proto",
",",
"ip_addrs",
",",
"gateway",
")",
":",
"changes",
"=",
"{",
"}",
"cur_dns_proto",
"=",
"(",
"'static'",
"if",
"'Statically Configured DNS Servers'",
"in",
"cur",
"else",
... | Compares the current interface against the desired configuration and
returns a dictionary describing the changes that need to be made. | [
"Compares",
"the",
"current",
"interface",
"against",
"the",
"desired",
"configuration",
"and",
"returns",
"a",
"dictionary",
"describing",
"the",
"changes",
"that",
"need",
"to",
"be",
"made",
"."
] | python | train |
pyblish/pyblish-houdini | pyblish_houdini/lib.py | https://github.com/pyblish/pyblish-houdini/blob/661b08696f04b4c5d8b03aa0c75cba3ca72f1e8d/pyblish_houdini/lib.py#L104-L124 | def maintained_selection():
"""Maintain selection during context
Example:
>>> with maintained_selection():
... # Modify selection
... node.setSelected(on=False, clear_all_selected=True)
>>> # Selection restored
"""
previous_selection = hou.selectedNodes()
t... | [
"def",
"maintained_selection",
"(",
")",
":",
"previous_selection",
"=",
"hou",
".",
"selectedNodes",
"(",
")",
"try",
":",
"yield",
"finally",
":",
"if",
"previous_selection",
":",
"for",
"node",
"in",
"previous_selection",
":",
"node",
".",
"setSelected",
"(... | Maintain selection during context
Example:
>>> with maintained_selection():
... # Modify selection
... node.setSelected(on=False, clear_all_selected=True)
>>> # Selection restored | [
"Maintain",
"selection",
"during",
"context"
] | python | train |
oasis-open/cti-taxii-client | taxii2client/__init__.py | https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L713-L721 | def refresh_information(self, accept=MEDIA_TYPE_TAXII_V20):
"""Update the properties of this API Root.
This invokes the ``Get API Root Information`` endpoint.
"""
response = self.__raw = self._conn.get(self.url,
headers={"Accept": accept})
... | [
"def",
"refresh_information",
"(",
"self",
",",
"accept",
"=",
"MEDIA_TYPE_TAXII_V20",
")",
":",
"response",
"=",
"self",
".",
"__raw",
"=",
"self",
".",
"_conn",
".",
"get",
"(",
"self",
".",
"url",
",",
"headers",
"=",
"{",
"\"Accept\"",
":",
"accept",... | Update the properties of this API Root.
This invokes the ``Get API Root Information`` endpoint. | [
"Update",
"the",
"properties",
"of",
"this",
"API",
"Root",
"."
] | python | valid |
SpriteLink/NIPAP | nipap/nipap/backend.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap/nipap/backend.py#L3858-L3909 | def edit_asn(self, auth, asn, attr):
""" Edit AS number
* `auth` [BaseAuth]
AAA options.
* `asn` [integer]
AS number to edit.
* `attr` [asn_attr]
New AS attributes.
This is the documentation of the internal backend... | [
"def",
"edit_asn",
"(",
"self",
",",
"auth",
",",
"asn",
",",
"attr",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"edit_asn called; asn: %s attr: %s\"",
"%",
"(",
"unicode",
"(",
"asn",
")",
",",
"unicode",
"(",
"attr",
")",
")",
")",
"# san... | Edit AS number
* `auth` [BaseAuth]
AAA options.
* `asn` [integer]
AS number to edit.
* `attr` [asn_attr]
New AS attributes.
This is the documentation of the internal backend function. It's
exposed over XML-RPC,... | [
"Edit",
"AS",
"number"
] | python | train |
saltstack/salt | salt/modules/netscaler.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L838-L863 | def vserver_servicegroup_add(v_name, sg_name, **connection_args):
'''
Bind a servicegroup to a vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_servicegroup_add 'vserverName' 'serviceGroupName'
'''
ret = True
if vserver_servicegroup_exists(v_name, sg_name, **co... | [
"def",
"vserver_servicegroup_add",
"(",
"v_name",
",",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"if",
"vserver_servicegroup_exists",
"(",
"v_name",
",",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
":",
"return",
"False",... | Bind a servicegroup to a vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_servicegroup_add 'vserverName' 'serviceGroupName' | [
"Bind",
"a",
"servicegroup",
"to",
"a",
"vserver"
] | python | train |
delfick/aws_syncr | aws_syncr/collector.py | https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/collector.py#L81-L84 | def extra_prepare_after_activation(self, configuration, args_dict):
"""Setup our connection to amazon"""
aws_syncr = configuration['aws_syncr']
configuration["amazon"] = Amazon(configuration['aws_syncr'].environment, configuration['accounts'], debug=aws_syncr.debug, dry_run=aws_syncr.dry_run) | [
"def",
"extra_prepare_after_activation",
"(",
"self",
",",
"configuration",
",",
"args_dict",
")",
":",
"aws_syncr",
"=",
"configuration",
"[",
"'aws_syncr'",
"]",
"configuration",
"[",
"\"amazon\"",
"]",
"=",
"Amazon",
"(",
"configuration",
"[",
"'aws_syncr'",
"]... | Setup our connection to amazon | [
"Setup",
"our",
"connection",
"to",
"amazon"
] | python | train |
ctuning/ck | ck/kernel.py | https://github.com/ctuning/ck/blob/7e009814e975f8742790d3106340088a46223714/ck/kernel.py#L5277-L5311 | def path(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
Output from from 'detect_cid_in_current_path' function
}
"""
... | [
"def",
"path",
"(",
"i",
")",
":",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",
"r",
"=",
"detect_cid_in_current_path",
"(",
"i",
")",
"if",
"r",
"[",
"'return'",
"]",
">",
"0",
":",
"return",
"r",
"rx",
"=",
"convert_entry_to_cid",
"... | Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
Output from from 'detect_cid_in_current_path' function
} | [
"Input",
":",
"{}"
] | python | train |
shveenkov/aiotarantool-queue-python | aiotarantool_queue/queue.py | https://github.com/shveenkov/aiotarantool-queue-python/blob/b84a1e704f63f7b8cb14cbca5ec99ab8047d1715/aiotarantool_queue/queue.py#L118-L128 | async def peek(self):
"""
Look at a task without changing its state.
Always returns `True`.
"""
the_tuple = await self.queue.peek(self.tube, self.task_id)
self.update_from_tuple(the_tuple)
return True | [
"async",
"def",
"peek",
"(",
"self",
")",
":",
"the_tuple",
"=",
"await",
"self",
".",
"queue",
".",
"peek",
"(",
"self",
".",
"tube",
",",
"self",
".",
"task_id",
")",
"self",
".",
"update_from_tuple",
"(",
"the_tuple",
")",
"return",
"True"
] | Look at a task without changing its state.
Always returns `True`. | [
"Look",
"at",
"a",
"task",
"without",
"changing",
"its",
"state",
"."
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/text_to_speech_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/text_to_speech_v1.py#L1196-L1217 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'url') and self.url is not None:
_dict['url'] = self.url
if hasattr(self, 'gender') and self.gender is not None:
_dict['gender'] = self.gender
if hasatt... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'url'",
")",
"and",
"self",
".",
"url",
"is",
"not",
"None",
":",
"_dict",
"[",
"'url'",
"]",
"=",
"self",
".",
"url",
"if",
"hasattr",
"(",
"... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
skitazaki/python-clitool | clitool/config.py | https://github.com/skitazaki/python-clitool/blob/4971f8d093d51c6fd0e6cc536bbb597f78b570ab/clitool/config.py#L94-L109 | def flip(self):
""" Provide flip view to compare how key/value pair is defined in each
environment for administrative usage.
:rtype: dict
"""
self._load()
groups = self.config.keys()
tabular = {}
for g in groups:
config = self.config[g]
... | [
"def",
"flip",
"(",
"self",
")",
":",
"self",
".",
"_load",
"(",
")",
"groups",
"=",
"self",
".",
"config",
".",
"keys",
"(",
")",
"tabular",
"=",
"{",
"}",
"for",
"g",
"in",
"groups",
":",
"config",
"=",
"self",
".",
"config",
"[",
"g",
"]",
... | Provide flip view to compare how key/value pair is defined in each
environment for administrative usage.
:rtype: dict | [
"Provide",
"flip",
"view",
"to",
"compare",
"how",
"key",
"/",
"value",
"pair",
"is",
"defined",
"in",
"each",
"environment",
"for",
"administrative",
"usage",
"."
] | python | train |
ucsb-cs-education/hairball | hairball/plugins/initialization.py | https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/initialization.py#L108-L116 | def analyze(self, scratch, **kwargs):
"""Run and return the results of the AttributeInitialization plugin."""
changes = dict((x.name, self.sprite_changes(x)) for x in
scratch.sprites)
changes['stage'] = {
'background': self.attribute_state(scratch.stage.scripts... | [
"def",
"analyze",
"(",
"self",
",",
"scratch",
",",
"*",
"*",
"kwargs",
")",
":",
"changes",
"=",
"dict",
"(",
"(",
"x",
".",
"name",
",",
"self",
".",
"sprite_changes",
"(",
"x",
")",
")",
"for",
"x",
"in",
"scratch",
".",
"sprites",
")",
"chang... | Run and return the results of the AttributeInitialization plugin. | [
"Run",
"and",
"return",
"the",
"results",
"of",
"the",
"AttributeInitialization",
"plugin",
"."
] | python | train |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L425-L457 | def apply_relationships(self, data, obj):
"""Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False
"""
... | [
"def",
"apply_relationships",
"(",
"self",
",",
"data",
",",
"obj",
")",
":",
"relationships_to_apply",
"=",
"[",
"]",
"relationship_fields",
"=",
"get_relationships",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"model_field",
"=",
"True",
")",
"for",
... | Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False | [
"Apply",
"relationship",
"provided",
"by",
"data",
"to",
"obj"
] | python | train |
collectiveacuity/labPack | labpack/databases/sql.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/databases/sql.py#L820-L913 | def update(self, new_details, old_details=None):
''' a method to upsert changes to a record in the table
:param new_details: dictionary with updated record fields
:param old_details: [optional] dictionary with original record fields
:return: list of dictionaries with u... | [
"def",
"update",
"(",
"self",
",",
"new_details",
",",
"old_details",
"=",
"None",
")",
":",
"title",
"=",
"'%s.update'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs",
"input_fields",
"=",
"{",
"'new_details'",
":",
"new_details",
",",
... | a method to upsert changes to a record in the table
:param new_details: dictionary with updated record fields
:param old_details: [optional] dictionary with original record fields
:return: list of dictionaries with updated field details
NOTE: if old_details is empty,... | [
"a",
"method",
"to",
"upsert",
"changes",
"to",
"a",
"record",
"in",
"the",
"table",
":",
"param",
"new_details",
":",
"dictionary",
"with",
"updated",
"record",
"fields",
":",
"param",
"old_details",
":",
"[",
"optional",
"]",
"dictionary",
"with",
"origina... | python | train |
useblocks/groundwork | groundwork/docstring.py | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/docstring.py#L44-L56 | def from_meta(cls, meta, meta_all=None):
"""Copy DocstringMeta from another instance."""
if len(meta.args) == 2:
name = meta.args[1]
meta_type = None
for x in meta_all:
if x.args[1] == name and x.args[0] == 'type':
meta_type = x.des... | [
"def",
"from_meta",
"(",
"cls",
",",
"meta",
",",
"meta_all",
"=",
"None",
")",
":",
"if",
"len",
"(",
"meta",
".",
"args",
")",
"==",
"2",
":",
"name",
"=",
"meta",
".",
"args",
"[",
"1",
"]",
"meta_type",
"=",
"None",
"for",
"x",
"in",
"meta_... | Copy DocstringMeta from another instance. | [
"Copy",
"DocstringMeta",
"from",
"another",
"instance",
"."
] | python | train |
idlesign/django-sitemessage | sitemessage/utils.py | https://github.com/idlesign/django-sitemessage/blob/25b179b798370354c5988042ec209e255d23793f/sitemessage/utils.py#L31-L42 | def get_site_url():
"""Returns a URL for current site.
:rtype: str|unicode
"""
site_url = getattr(_THREAD_LOCAL, _THREAD_SITE_URL, None)
if site_url is None:
site_url = SITE_URL or get_site_url_()
setattr(_THREAD_LOCAL, _THREAD_SITE_URL, site_url)
return site_url | [
"def",
"get_site_url",
"(",
")",
":",
"site_url",
"=",
"getattr",
"(",
"_THREAD_LOCAL",
",",
"_THREAD_SITE_URL",
",",
"None",
")",
"if",
"site_url",
"is",
"None",
":",
"site_url",
"=",
"SITE_URL",
"or",
"get_site_url_",
"(",
")",
"setattr",
"(",
"_THREAD_LOC... | Returns a URL for current site.
:rtype: str|unicode | [
"Returns",
"a",
"URL",
"for",
"current",
"site",
"."
] | python | train |
google/grr | grr/core/grr_response_core/path_detection/windows.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/path_detection/windows.py#L100-L140 | def Process(self, path):
"""Processes a given path.
Args:
path: Path (as a string) to post-process.
Returns:
A list of paths with environment variables replaced with their
values. If the mapping had a list of values for a particular variable,
instead of just one value, then all pos... | [
"def",
"Process",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"re",
".",
"sub",
"(",
"self",
".",
"SYSTEMROOT_RE",
",",
"r\"%systemroot%\"",
",",
"path",
",",
"count",
"=",
"1",
")",
"path",
"=",
"re",
".",
"sub",
"(",
"self",
".",
"SYSTEM32_R... | Processes a given path.
Args:
path: Path (as a string) to post-process.
Returns:
A list of paths with environment variables replaced with their
values. If the mapping had a list of values for a particular variable,
instead of just one value, then all possible replacements will be
... | [
"Processes",
"a",
"given",
"path",
"."
] | python | train |
heroku/sf-suds | suds/resolver.py | https://github.com/heroku/sf-suds/blob/44b6743a45ff4447157605d6fecc9bf5922ce68a/suds/resolver.py#L297-L303 | def getchild(self, name, parent):
""" get a child by name """
#log.debug('searching parent (%s) for (%s)', Repr(parent), name)
if name.startswith('@'):
return parent.get_attribute(name[1:])
else:
return parent.get_child(name) | [
"def",
"getchild",
"(",
"self",
",",
"name",
",",
"parent",
")",
":",
"#log.debug('searching parent (%s) for (%s)', Repr(parent), name)",
"if",
"name",
".",
"startswith",
"(",
"'@'",
")",
":",
"return",
"parent",
".",
"get_attribute",
"(",
"name",
"[",
"1",
":",... | get a child by name | [
"get",
"a",
"child",
"by",
"name"
] | python | train |
dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/store.py | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/store.py#L29-L62 | def put_file(self, file, object_type, object_id, width, height, mimetype,
reproducible):
"""Puts the ``file`` of the image.
:param file: the image file to put
:type file: file-like object, :class:`file`
:param object_type: the object type of the image to put
... | [
"def",
"put_file",
"(",
"self",
",",
"file",
",",
"object_type",
",",
"object_id",
",",
"width",
",",
"height",
",",
"mimetype",
",",
"reproducible",
")",
":",
"raise",
"NotImplementedError",
"(",
"'put_file() has to be implemented'",
")"
] | Puts the ``file`` of the image.
:param file: the image file to put
:type file: file-like object, :class:`file`
:param object_type: the object type of the image to put
e.g. ``'comics.cover'``
:type object_type: :class:`str`
:param object_id: the object... | [
"Puts",
"the",
"file",
"of",
"the",
"image",
"."
] | python | train |
MacHu-GWU/angora-project | angora/bot/macro.py | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/bot/macro.py#L211-L215 | def Back(self, n = 1, dl = 0):
"""退格键n次
"""
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.backspace_key, n) | [
"def",
"Back",
"(",
"self",
",",
"n",
"=",
"1",
",",
"dl",
"=",
"0",
")",
":",
"self",
".",
"Delay",
"(",
"dl",
")",
"self",
".",
"keyboard",
".",
"tap_key",
"(",
"self",
".",
"keyboard",
".",
"backspace_key",
",",
"n",
")"
] | 退格键n次 | [
"退格键n次"
] | python | train |
praw-dev/prawcore | prawcore/auth.py | https://github.com/praw-dev/prawcore/blob/b16ae88a1f2bf98095ed6fe64851cb7add7ed752/prawcore/auth.py#L225-L231 | def refresh(self):
"""Obtain a new access token from the refresh_token."""
if self.refresh_token is None:
raise InvalidInvocation("refresh token not provided")
self._request_token(
grant_type="refresh_token", refresh_token=self.refresh_token
) | [
"def",
"refresh",
"(",
"self",
")",
":",
"if",
"self",
".",
"refresh_token",
"is",
"None",
":",
"raise",
"InvalidInvocation",
"(",
"\"refresh token not provided\"",
")",
"self",
".",
"_request_token",
"(",
"grant_type",
"=",
"\"refresh_token\"",
",",
"refresh_toke... | Obtain a new access token from the refresh_token. | [
"Obtain",
"a",
"new",
"access",
"token",
"from",
"the",
"refresh_token",
"."
] | python | train |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/config.py | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/config.py#L166-L250 | def _validate_config(self):
"""
Validate configuration file.
:raises: RuntimeError
"""
# while set().issubset() is easier, we want to tell the user the names
# of any invalid keys
bad_keys = []
for k in self._config.keys():
if k not in self._ex... | [
"def",
"_validate_config",
"(",
"self",
")",
":",
"# while set().issubset() is easier, we want to tell the user the names",
"# of any invalid keys",
"bad_keys",
"=",
"[",
"]",
"for",
"k",
"in",
"self",
".",
"_config",
".",
"keys",
"(",
")",
":",
"if",
"k",
"not",
... | Validate configuration file.
:raises: RuntimeError | [
"Validate",
"configuration",
"file",
".",
":",
"raises",
":",
"RuntimeError"
] | python | train |
7sDream/zhihu-py3 | zhihu/answer.py | https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/answer.py#L128-L141 | def upvoters(self):
"""获取答案点赞用户,返回生成器.
:return: 点赞用户
:rtype: Author.Iterable
"""
self._make_soup()
next_req = '/answer/' + str(self.aid) + '/voters_profile'
while next_req != '':
data = self._session.get(Zhihu_URL + next_req).json()
next_r... | [
"def",
"upvoters",
"(",
"self",
")",
":",
"self",
".",
"_make_soup",
"(",
")",
"next_req",
"=",
"'/answer/'",
"+",
"str",
"(",
"self",
".",
"aid",
")",
"+",
"'/voters_profile'",
"while",
"next_req",
"!=",
"''",
":",
"data",
"=",
"self",
".",
"_session"... | 获取答案点赞用户,返回生成器.
:return: 点赞用户
:rtype: Author.Iterable | [
"获取答案点赞用户,返回生成器",
"."
] | python | train |
globocom/GloboNetworkAPI-client-python | networkapiclient/Network.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Network.py#L328-L350 | def deallocate_network_ipv4(self, id_network_ipv4):
"""
Deallocate all relationships between NetworkIPv4.
:param id_network_ipv4: ID for NetworkIPv4
:return: Nothing
:raise InvalidParameterError: Invalid ID for NetworkIPv4.
:raise NetworkIPv4NotFoundError: NetworkIPv4 ... | [
"def",
"deallocate_network_ipv4",
"(",
"self",
",",
"id_network_ipv4",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_network_ipv4",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'The identifier of NetworkIPv4 is invalid or was not informed.'",
")",
"url",
"=",
... | Deallocate all relationships between NetworkIPv4.
:param id_network_ipv4: ID for NetworkIPv4
:return: Nothing
:raise InvalidParameterError: Invalid ID for NetworkIPv4.
:raise NetworkIPv4NotFoundError: NetworkIPv4 not found.
:raise DataBaseError: Networkapi failed to access the... | [
"Deallocate",
"all",
"relationships",
"between",
"NetworkIPv4",
"."
] | python | train |
erikrose/blessings | blessings/__init__.py | https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L217-L239 | def _height_and_width(self):
"""Return a tuple of (terminal height, terminal width).
Start by trying TIOCGWINSZ (Terminal I/O-Control: Get Window Size),
falling back to environment variables (LINES, COLUMNS), and returning
(None, None) if those are unavailable or invalid.
"""
... | [
"def",
"_height_and_width",
"(",
"self",
")",
":",
"# tigetnum('lines') and tigetnum('cols') update only if we call",
"# setupterm() again.",
"for",
"descriptor",
"in",
"self",
".",
"_init_descriptor",
",",
"sys",
".",
"__stdout__",
":",
"try",
":",
"return",
"struct",
... | Return a tuple of (terminal height, terminal width).
Start by trying TIOCGWINSZ (Terminal I/O-Control: Get Window Size),
falling back to environment variables (LINES, COLUMNS), and returning
(None, None) if those are unavailable or invalid. | [
"Return",
"a",
"tuple",
"of",
"(",
"terminal",
"height",
"terminal",
"width",
")",
"."
] | python | train |
jazzband/django-ddp | dddp/websocket.py | https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/websocket.py#L183-L196 | def on_message(self, message):
"""Process a message received from remote."""
if self.ws.closed:
return None
try:
safe_call(self.logger.debug, '< %s %r', self, message)
# process individual messages
for data in self.ddp_frames_from_message(message)... | [
"def",
"on_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"ws",
".",
"closed",
":",
"return",
"None",
"try",
":",
"safe_call",
"(",
"self",
".",
"logger",
".",
"debug",
",",
"'< %s %r'",
",",
"self",
",",
"message",
")",
"# proce... | Process a message received from remote. | [
"Process",
"a",
"message",
"received",
"from",
"remote",
"."
] | python | test |
luismasuelli/django-trackmodels-ritual | grimoire/django/tracked/reports.py | https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/reports.py#L180-L201 | def get_report_data_rows(self, request, queryset):
"""
Using the builders for the queryset model, iterates over the queryset to generate a result
with headers and rows. This queryset must be the exact same received in the .process method,
which tells us that this function should be c... | [
"def",
"get_report_data_rows",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"model",
"=",
"queryset",
".",
"model",
"meta",
"=",
"model",
".",
"_meta",
"field_names",
"=",
"set",
"(",
"field",
".",
"name",
"for",
"field",
"in",
"meta",
".",
... | Using the builders for the queryset model, iterates over the queryset to generate a result
with headers and rows. This queryset must be the exact same received in the .process method,
which tells us that this function should be called inside .process implementation.
:param queryset: Provided... | [
"Using",
"the",
"builders",
"for",
"the",
"queryset",
"model",
"iterates",
"over",
"the",
"queryset",
"to",
"generate",
"a",
"result",
"with",
"headers",
"and",
"rows",
".",
"This",
"queryset",
"must",
"be",
"the",
"exact",
"same",
"received",
"in",
"the",
... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.