repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
googleapis/google-cloud-python | datastore/google/cloud/datastore/transaction.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/transaction.py#L196-L212 | def begin(self):
"""Begins a transaction.
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.
:raises: :class:`~exceptions.ValueError` if the transaction has
already... | [
"def",
"begin",
"(",
"self",
")",
":",
"super",
"(",
"Transaction",
",",
"self",
")",
".",
"begin",
"(",
")",
"try",
":",
"response_pb",
"=",
"self",
".",
"_client",
".",
"_datastore_api",
".",
"begin_transaction",
"(",
"self",
".",
"project",
")",
"se... | Begins a transaction.
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.
:raises: :class:`~exceptions.ValueError` if the transaction has
already begun. | [
"Begins",
"a",
"transaction",
"."
] | python | train | 38.176471 |
fermiPy/fermipy | fermipy/jobs/scatter_gather.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/scatter_gather.py#L179-L197 | def _build_job_dict(self):
"""Build a dictionary of `JobDetails` objects for the internal `Link`"""
if self.args['dry_run']:
status = JobStatus.unknown
else:
status = JobStatus.not_ready
base_config = self.scatter_link.args
for jobkey, job_config in sort... | [
"def",
"_build_job_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"args",
"[",
"'dry_run'",
"]",
":",
"status",
"=",
"JobStatus",
".",
"unknown",
"else",
":",
"status",
"=",
"JobStatus",
".",
"not_ready",
"base_config",
"=",
"self",
".",
"scatter_link",
... | Build a dictionary of `JobDetails` objects for the internal `Link` | [
"Build",
"a",
"dictionary",
"of",
"JobDetails",
"objects",
"for",
"the",
"internal",
"Link"
] | python | train | 46 |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/handlers.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/handlers.py#L1376-L1415 | def handle(self):
"""Handles kick off request."""
# Get and verify mr state.
mr_id = self.request.get("mapreduce_id")
# Log the mr_id since this is started in an unnamed task
logging.info("Processing kickoff for job %s", mr_id)
state = model.MapreduceState.get_by_job_id(mr_id)
if not self._c... | [
"def",
"handle",
"(",
"self",
")",
":",
"# Get and verify mr state.",
"mr_id",
"=",
"self",
".",
"request",
".",
"get",
"(",
"\"mapreduce_id\"",
")",
"# Log the mr_id since this is started in an unnamed task",
"logging",
".",
"info",
"(",
"\"Processing kickoff for job %s\... | Handles kick off request. | [
"Handles",
"kick",
"off",
"request",
"."
] | python | train | 37.975 |
materialsproject/pymatgen | pymatgen/io/vasp/outputs.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/outputs.py#L3803-L3814 | def get_phonon_frequencies(self):
"""calculate phonon frequencies"""
# TODO: the following is most likely not correct or suboptimal
# hence for demonstration purposes only
frequencies = []
for k, v0 in self.data.iteritems():
for v1 in v0.itervalues():
... | [
"def",
"get_phonon_frequencies",
"(",
"self",
")",
":",
"# TODO: the following is most likely not correct or suboptimal",
"# hence for demonstration purposes only",
"frequencies",
"=",
"[",
"]",
"for",
"k",
",",
"v0",
"in",
"self",
".",
"data",
".",
"iteritems",
"(",
")... | calculate phonon frequencies | [
"calculate",
"phonon",
"frequencies"
] | python | train | 44.083333 |
cltk/cltk | cltk/tokenize/sentence.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tokenize/sentence.py#L219-L230 | def tokenize(self, untokenized_string: str, model=None):
"""Alias for tokenize_sentences()—NLTK's PlaintextCorpusReader needs a
function called tokenize in functions used as a parameter for sentence
tokenization.
:type untokenized_string: str
:param untokenized_string: A string ... | [
"def",
"tokenize",
"(",
"self",
",",
"untokenized_string",
":",
"str",
",",
"model",
"=",
"None",
")",
":",
"if",
"self",
".",
"language",
"in",
"INDIAN_LANGUAGES",
":",
"return",
"self",
".",
"indian_punctuation_tokenize_regex",
"(",
"untokenized_string",
")",
... | Alias for tokenize_sentences()—NLTK's PlaintextCorpusReader needs a
function called tokenize in functions used as a parameter for sentence
tokenization.
:type untokenized_string: str
:param untokenized_string: A string containing one of more sentences. | [
"Alias",
"for",
"tokenize_sentences",
"()",
"—NLTK",
"s",
"PlaintextCorpusReader",
"needs",
"a",
"function",
"called",
"tokenize",
"in",
"functions",
"used",
"as",
"a",
"parameter",
"for",
"sentence",
"tokenization",
"."
] | python | train | 46.25 |
google/grr | api_client/python/grr_api_client/client.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/api_client/python/grr_api_client/client.py#L242-L247 | def Get(self):
"""Fetch client's data and return a proper Client object."""
args = client_pb2.ApiGetClientArgs(client_id=self.client_id)
result = self._context.SendRequest("GetClient", args)
return Client(data=result, context=self._context) | [
"def",
"Get",
"(",
"self",
")",
":",
"args",
"=",
"client_pb2",
".",
"ApiGetClientArgs",
"(",
"client_id",
"=",
"self",
".",
"client_id",
")",
"result",
"=",
"self",
".",
"_context",
".",
"SendRequest",
"(",
"\"GetClient\"",
",",
"args",
")",
"return",
"... | Fetch client's data and return a proper Client object. | [
"Fetch",
"client",
"s",
"data",
"and",
"return",
"a",
"proper",
"Client",
"object",
"."
] | python | train | 42 |
PlaidWeb/Publ | publ/rendering.py | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/rendering.py#L197-L203 | def render_path_alias(path):
""" Render a known path-alias (used primarily for forced .php redirects) """
redir = path_alias.get_redirect('/' + path)
if not redir:
raise http_error.NotFound("Path redirection not found")
return redir | [
"def",
"render_path_alias",
"(",
"path",
")",
":",
"redir",
"=",
"path_alias",
".",
"get_redirect",
"(",
"'/'",
"+",
"path",
")",
"if",
"not",
"redir",
":",
"raise",
"http_error",
".",
"NotFound",
"(",
"\"Path redirection not found\"",
")",
"return",
"redir"
] | Render a known path-alias (used primarily for forced .php redirects) | [
"Render",
"a",
"known",
"path",
"-",
"alias",
"(",
"used",
"primarily",
"for",
"forced",
".",
"php",
"redirects",
")"
] | python | train | 35.857143 |
fermiPy/fermipy | fermipy/gtanalysis.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/gtanalysis.py#L2036-L2051 | def free_shape(self, name, free=True, **kwargs):
"""Free/Fix shape parameters of a source.
Parameters
----------
name : str
Source name.
free : bool
Choose whether to free (free=True) or fix (free=False).
"""
src = self.roi.get_source_by... | [
"def",
"free_shape",
"(",
"self",
",",
"name",
",",
"free",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"src",
"=",
"self",
".",
"roi",
".",
"get_source_by_name",
"(",
"name",
")",
"self",
".",
"free_source",
"(",
"name",
",",
"free",
"=",
"fre... | Free/Fix shape parameters of a source.
Parameters
----------
name : str
Source name.
free : bool
Choose whether to free (free=True) or fix (free=False). | [
"Free",
"/",
"Fix",
"shape",
"parameters",
"of",
"a",
"source",
"."
] | python | train | 28.875 |
StackStorm/pybind | pybind/nos/v6_0_2f/rbridge_id/router/hide_pim_holder/pim/rp_candidate/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/rbridge_id/router/hide_pim_holder/pim/rp_candidate/__init__.py#L94-L115 | def _set_rp_cand_interface(self, v, load=False):
"""
Setter method for rp_cand_interface, mapped from YANG variable /rbridge_id/router/hide_pim_holder/pim/rp_candidate/rp_cand_interface (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_rp_cand_interface is considere... | [
"def",
"_set_rp_cand_interface",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",... | Setter method for rp_cand_interface, mapped from YANG variable /rbridge_id/router/hide_pim_holder/pim/rp_candidate/rp_cand_interface (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_rp_cand_interface is considered as a private
method. Backends looking to populate this ... | [
"Setter",
"method",
"for",
"rp_cand_interface",
"mapped",
"from",
"YANG",
"variable",
"/",
"rbridge_id",
"/",
"router",
"/",
"hide_pim_holder",
"/",
"pim",
"/",
"rp_candidate",
"/",
"rp_cand_interface",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
... | python | train | 130.136364 |
treycucco/bidon | lib/generate_models.py | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L132-L142 | def split_pks(cols):
"""Returns a 2-tuple of tuples of ((primary_key_cols), (non_primary_key_cols))."""
pks = []
others = []
for name, col in cols.items():
if col["is_primary_key"] == "t":
pks.append(name)
else:
others.append(name)
return (tuple(pks), tuple(others)) | [
"def",
"split_pks",
"(",
"cols",
")",
":",
"pks",
"=",
"[",
"]",
"others",
"=",
"[",
"]",
"for",
"name",
",",
"col",
"in",
"cols",
".",
"items",
"(",
")",
":",
"if",
"col",
"[",
"\"is_primary_key\"",
"]",
"==",
"\"t\"",
":",
"pks",
".",
"append",... | Returns a 2-tuple of tuples of ((primary_key_cols), (non_primary_key_cols)). | [
"Returns",
"a",
"2",
"-",
"tuple",
"of",
"tuples",
"of",
"((",
"primary_key_cols",
")",
"(",
"non_primary_key_cols",
"))",
"."
] | python | train | 26.090909 |
joelbm24/brainy | lib/bfinter.py | https://github.com/joelbm24/brainy/blob/bc3e1d6e020f1bb884a9bbbda834dac3a7a7fdb4/lib/bfinter.py#L79-L90 | def get_tape(self, start=0, end=10):
'''Pretty prints the tape values'''
self.tape_start = start
self.tape_end = end
self.tape_length = end - start
tmp = '\n'+"|"+str(start)+"| "
for i in xrange(len(self.tape[start:end])):
if i == self.cur_cell:
... | [
"def",
"get_tape",
"(",
"self",
",",
"start",
"=",
"0",
",",
"end",
"=",
"10",
")",
":",
"self",
".",
"tape_start",
"=",
"start",
"self",
".",
"tape_end",
"=",
"end",
"self",
".",
"tape_length",
"=",
"end",
"-",
"start",
"tmp",
"=",
"'\\n'",
"+",
... | Pretty prints the tape values | [
"Pretty",
"prints",
"the",
"tape",
"values"
] | python | train | 38.083333 |
mfcloud/python-zvm-sdk | zvmsdk/api.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L1081-L1215 | def vswitch_set(self, vswitch_name, **kwargs):
"""Change the configuration of an existing virtual switch
:param str vswitch_name: the name of the virtual switch
:param dict kwargs:
- grant_userid=<value>:
A userid to be added to the access list
- user_vla... | [
"def",
"vswitch_set",
"(",
"self",
",",
"vswitch_name",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"if",
"k",
"not",
"in",
"constants",
".",
"SET_VSWITCH_KEYWORDS",
":",
"errmsg",
"=",
"(",
"'API vswitch_... | Change the configuration of an existing virtual switch
:param str vswitch_name: the name of the virtual switch
:param dict kwargs:
- grant_userid=<value>:
A userid to be added to the access list
- user_vlan_id=<value>:
user VLAN ID. Support follow... | [
"Change",
"the",
"configuration",
"of",
"an",
"existing",
"virtual",
"switch"
] | python | train | 54.585185 |
junzis/pyModeS | pyModeS/decoder/bds/bds44.py | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds44.py#L141-L157 | def hum44(msg):
"""humidity
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
float: percentage of humidity, [0 - 100] %
"""
d = hex2bin(data(msg))
if d[49] == '0':
return None
hm = bin2int(d[50:56]) * 100.0 / 64 # %
return round(hm, 1) | [
"def",
"hum44",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"49",
"]",
"==",
"'0'",
":",
"return",
"None",
"hm",
"=",
"bin2int",
"(",
"d",
"[",
"50",
":",
"56",
"]",
")",
"*",
"100.0",
"/",
... | humidity
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
float: percentage of humidity, [0 - 100] % | [
"humidity"
] | python | train | 17.588235 |
sassoo/goldman | goldman/stores/postgres/store.py | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/stores/postgres/store.py#L146-L262 | def filters_query(filters):
""" Turn the tuple of filters into SQL WHERE statements
The key (column name) & operator have already been vetted
so they can be trusted but the value could still be evil
so it MUST be a parameterized input!
That is done by creating a param dict wher... | [
"def",
"filters_query",
"(",
"filters",
")",
":",
"def",
"_cast_val",
"(",
"filtr",
")",
":",
"\"\"\" Perform any needed casting on the filter value\n\n This could be tasks like including '%' signs at\n certain anchor points based on the filter or\n even wrap... | Turn the tuple of filters into SQL WHERE statements
The key (column name) & operator have already been vetted
so they can be trusted but the value could still be evil
so it MUST be a parameterized input!
That is done by creating a param dict where they key name
& val look like:... | [
"Turn",
"the",
"tuple",
"of",
"filters",
"into",
"SQL",
"WHERE",
"statements"
] | python | train | 29.239316 |
ox-it/python-sharepoint | sharepoint/lists/__init__.py | https://github.com/ox-it/python-sharepoint/blob/f1a1e19189d78115fcfc25850d27319e34d7e699/sharepoint/lists/__init__.py#L237-L251 | def append(self, row):
"""
Appends a row to the list. Takes a dictionary, returns a row.
"""
if isinstance(row, dict):
row = self.Row(row)
elif isinstance(row, self.Row):
pass
elif isinstance(row, SharePointListRow):
raise TypeError("ro... | [
"def",
"append",
"(",
"self",
",",
"row",
")",
":",
"if",
"isinstance",
"(",
"row",
",",
"dict",
")",
":",
"row",
"=",
"self",
".",
"Row",
"(",
"row",
")",
"elif",
"isinstance",
"(",
"row",
",",
"self",
".",
"Row",
")",
":",
"pass",
"elif",
"is... | Appends a row to the list. Takes a dictionary, returns a row. | [
"Appends",
"a",
"row",
"to",
"the",
"list",
".",
"Takes",
"a",
"dictionary",
"returns",
"a",
"row",
"."
] | python | train | 39 |
Alignak-monitoring/alignak | alignak/http/arbiter_interface.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L1390-L1428 | def _build_host_livestate(self, host_name, livestate):
# pylint: disable=no-self-use, too-many-locals
"""Build and notify the external command for an host livestate
PROCESS_HOST_CHECK_RESULT;<host_name>;<status_code>;<plugin_output>
:param host_name: the concerned host name
:pa... | [
"def",
"_build_host_livestate",
"(",
"self",
",",
"host_name",
",",
"livestate",
")",
":",
"# pylint: disable=no-self-use, too-many-locals",
"state",
"=",
"livestate",
".",
"get",
"(",
"'state'",
",",
"'UP'",
")",
".",
"upper",
"(",
")",
"output",
"=",
"livestat... | Build and notify the external command for an host livestate
PROCESS_HOST_CHECK_RESULT;<host_name>;<status_code>;<plugin_output>
:param host_name: the concerned host name
:param livestate: livestate dictionary
:return: external command line | [
"Build",
"and",
"notify",
"the",
"external",
"command",
"for",
"an",
"host",
"livestate"
] | python | train | 37.74359 |
RJT1990/pyflux | pyflux/ssm/llm.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/llm.py#L264-L323 | def plot_fit(self, intervals=True, **kwargs):
""" Plots the fit of the model
Parameters
----------
intervals : Boolean
Whether to plot 95% confidence interval of states
Returns
----------
None (plots data and the fit)
"""
import matpl... | [
"def",
"plot_fit",
"(",
"self",
",",
"intervals",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seaborn",
"as",
"sns",
"figsize",
"=",
"kwargs",
".",
"get",
"(",
"'figsize'",
",",
"(",
... | Plots the fit of the model
Parameters
----------
intervals : Boolean
Whether to plot 95% confidence interval of states
Returns
----------
None (plots data and the fit) | [
"Plots",
"the",
"fit",
"of",
"the",
"model"
] | python | train | 37.7 |
django-py/django-doberman | doberman/auth.py | https://github.com/django-py/django-doberman/blob/2e5959737a1b64234ed5a179c93f96a0de1c3e5c/doberman/auth.py#L97-L137 | def inspect(self):
"""
Inspect access attempt, used for catpcha flow
:return:
"""
last_attempt = self.get_last_failed_access_attempt(
ip_address=self.ip,
captcha_enabled=True,
captcha_passed=False,
is_expired=False
)
... | [
"def",
"inspect",
"(",
"self",
")",
":",
"last_attempt",
"=",
"self",
".",
"get_last_failed_access_attempt",
"(",
"ip_address",
"=",
"self",
".",
"ip",
",",
"captcha_enabled",
"=",
"True",
",",
"captcha_passed",
"=",
"False",
",",
"is_expired",
"=",
"False",
... | Inspect access attempt, used for catpcha flow
:return: | [
"Inspect",
"access",
"attempt",
"used",
"for",
"catpcha",
"flow",
":",
"return",
":"
] | python | train | 35.560976 |
cdeboever3/cdpybio | cdpybio/analysis.py | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/analysis.py#L571-L609 | def plot_color_legend(legend, horizontal=False, ax=None):
"""
Plot a pandas Series with labels and colors.
Parameters
----------
legend : pandas.Series
Pandas Series whose values are RGB triples and whose index contains
categorical labels.
horizontal : bool
If True, plo... | [
"def",
"plot_color_legend",
"(",
"legend",
",",
"horizontal",
"=",
"False",
",",
"ax",
"=",
"None",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"numpy",
"as",
"np",
"t",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"array... | Plot a pandas Series with labels and colors.
Parameters
----------
legend : pandas.Series
Pandas Series whose values are RGB triples and whose index contains
categorical labels.
horizontal : bool
If True, plot horizontally.
ax : matplotlib.axis
Axis to plot on.
... | [
"Plot",
"a",
"pandas",
"Series",
"with",
"labels",
"and",
"colors",
"."
] | python | train | 26.025641 |
oscarlazoarjona/fast | fast/atomic_structure.py | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1844-L1891 | def matrix_element(ji, fi, mi, jj, fj, mj,
II, reduced_matrix_element, q=None,
numeric=True, convention=1):
r"""Calculate a matrix element of the electric dipole (in the helicity
basis).
We calculate the matrix element for the cyclical transition of the D2 line
in ... | [
"def",
"matrix_element",
"(",
"ji",
",",
"fi",
",",
"mi",
",",
"jj",
",",
"fj",
",",
"mj",
",",
"II",
",",
"reduced_matrix_element",
",",
"q",
"=",
"None",
",",
"numeric",
"=",
"True",
",",
"convention",
"=",
"1",
")",
":",
"if",
"q",
"is",
"None... | r"""Calculate a matrix element of the electric dipole (in the helicity
basis).
We calculate the matrix element for the cyclical transition of the D2 line
in Rb 87.
>>> from sympy import symbols
>>> red = symbols("r", positive=True)
>>> half = 1/Integer(2)
>>> II = 3*half
>>> matrix_ele... | [
"r",
"Calculate",
"a",
"matrix",
"element",
"of",
"the",
"electric",
"dipole",
"(",
"in",
"the",
"helicity",
"basis",
")",
"."
] | python | train | 29.333333 |
mbj4668/pyang | pyang/translators/dsdl.py | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/dsdl.py#L432-L448 | def create_roots(self, yam):
"""Create the top-level structure for module `yam`."""
self.local_grammar = SchemaNode("grammar")
self.local_grammar.attr = {
"ns": yam.search_one("namespace").arg,
"nma:module": self.module.arg}
src_text = "YANG module '%s'" % yam.arg... | [
"def",
"create_roots",
"(",
"self",
",",
"yam",
")",
":",
"self",
".",
"local_grammar",
"=",
"SchemaNode",
"(",
"\"grammar\"",
")",
"self",
".",
"local_grammar",
".",
"attr",
"=",
"{",
"\"ns\"",
":",
"yam",
".",
"search_one",
"(",
"\"namespace\"",
")",
"... | Create the top-level structure for module `yam`. | [
"Create",
"the",
"top",
"-",
"level",
"structure",
"for",
"module",
"yam",
"."
] | python | train | 49.764706 |
hannes-brt/cudnn-python-wrappers | libcudnn.py | https://github.com/hannes-brt/cudnn-python-wrappers/blob/55aab1242924c2fd43db150cf2ccc2a3df958dd5/libcudnn.py#L364-L379 | def cudnnCreateTensorDescriptor():
"""
Create a Tensor descriptor object.
Allocates a cudnnTensorDescriptor_t structure and returns a pointer to it.
Returns
-------
tensor_descriptor : int
Tensor descriptor.
"""
tensor = ctypes.c_void_p()
status = _libcudnn.cudnnCreateTens... | [
"def",
"cudnnCreateTensorDescriptor",
"(",
")",
":",
"tensor",
"=",
"ctypes",
".",
"c_void_p",
"(",
")",
"status",
"=",
"_libcudnn",
".",
"cudnnCreateTensorDescriptor",
"(",
"ctypes",
".",
"byref",
"(",
"tensor",
")",
")",
"cudnnCheckStatus",
"(",
"status",
")... | Create a Tensor descriptor object.
Allocates a cudnnTensorDescriptor_t structure and returns a pointer to it.
Returns
-------
tensor_descriptor : int
Tensor descriptor. | [
"Create",
"a",
"Tensor",
"descriptor",
"object",
"."
] | python | train | 24.5 |
glitchassassin/lackey | lackey/SettingsDebug.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L23-L33 | def user(self, message):
""" Creates a user log (if user logging is turned on)
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
Note: Does *not* use Java string formatting like Sikuli.
Format your message with Python ``basestri... | [
"def",
"user",
"(",
"self",
",",
"message",
")",
":",
"if",
"Settings",
".",
"UserLogs",
":",
"self",
".",
"_write_log",
"(",
"Settings",
".",
"UserLogPrefix",
",",
"Settings",
".",
"UserLogTime",
",",
"message",
")"
] | Creates a user log (if user logging is turned on)
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
Note: Does *not* use Java string formatting like Sikuli.
Format your message with Python ``basestring.format()`` instead. | [
"Creates",
"a",
"user",
"log",
"(",
"if",
"user",
"logging",
"is",
"turned",
"on",
")"
] | python | train | 41.545455 |
neithere/argh | argh/constants.py | https://github.com/neithere/argh/blob/dcd3253f2994400a6a58a700c118c53765bc50a4/argh/constants.py#L55-L91 | def _expand_help(self, action):
"""
This method is copied verbatim from ArgumentDefaultsHelpFormatter with
a couple of lines added just before the end. Reason: we need to
`repr()` default values instead of simply inserting them as is.
This helps notice, for example, an empty str... | [
"def",
"_expand_help",
"(",
"self",
",",
"action",
")",
":",
"params",
"=",
"dict",
"(",
"vars",
"(",
"action",
")",
",",
"prog",
"=",
"self",
".",
"_prog",
")",
"for",
"name",
"in",
"list",
"(",
"params",
")",
":",
"if",
"params",
"[",
"name",
"... | This method is copied verbatim from ArgumentDefaultsHelpFormatter with
a couple of lines added just before the end. Reason: we need to
`repr()` default values instead of simply inserting them as is.
This helps notice, for example, an empty string as the default value;
moreover, it preve... | [
"This",
"method",
"is",
"copied",
"verbatim",
"from",
"ArgumentDefaultsHelpFormatter",
"with",
"a",
"couple",
"of",
"lines",
"added",
"just",
"before",
"the",
"end",
".",
"Reason",
":",
"we",
"need",
"to",
"repr",
"()",
"default",
"values",
"instead",
"of",
... | python | test | 42.324324 |
log2timeline/dfvfs | dfvfs/vfs/tsk_file_entry.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L501-L544 | def _GetDataStreams(self):
"""Retrieves the data streams.
Returns:
list[TSKDataStream]: data streams.
"""
if self._data_streams is None:
if self._file_system.IsHFS():
known_data_attribute_types = [
pytsk3.TSK_FS_ATTR_TYPE_HFS_DEFAULT,
pytsk3.TSK_FS_ATTR_TYPE_... | [
"def",
"_GetDataStreams",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_streams",
"is",
"None",
":",
"if",
"self",
".",
"_file_system",
".",
"IsHFS",
"(",
")",
":",
"known_data_attribute_types",
"=",
"[",
"pytsk3",
".",
"TSK_FS_ATTR_TYPE_HFS_DEFAULT",
",",
... | Retrieves the data streams.
Returns:
list[TSKDataStream]: data streams. | [
"Retrieves",
"the",
"data",
"streams",
"."
] | python | train | 32.386364 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/egstore.py | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/egstore.py#L141-L147 | def kill(self):
"""
Delete my persistent file (i.e. pickle file), if it exists.
"""
if os.path.isfile(self.filename):
os.remove(self.filename)
return | [
"def",
"kill",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"filename",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"filename",
")",
"return"
] | Delete my persistent file (i.e. pickle file), if it exists. | [
"Delete",
"my",
"persistent",
"file",
"(",
"i",
".",
"e",
".",
"pickle",
"file",
")",
"if",
"it",
"exists",
"."
] | python | train | 27.857143 |
hsolbrig/PyShEx | pyshex/shex_evaluator.py | https://github.com/hsolbrig/PyShEx/blob/9d659cc36e808afd66d4a6d60e8ea21cb12eb744/pyshex/shex_evaluator.py#L170-L176 | def focus(self, focus: Optional[URIPARM]) -> None:
""" Set the focus node(s). If no focus node is specified, the evaluation will occur for all non-BNode
graph subjects. Otherwise it can be a string, a URIRef or a list of string/URIRef combinations
:param focus: None if focus should be all URI... | [
"def",
"focus",
"(",
"self",
",",
"focus",
":",
"Optional",
"[",
"URIPARM",
"]",
")",
"->",
"None",
":",
"self",
".",
"_focus",
"=",
"normalize_uriparm",
"(",
"focus",
")",
"if",
"focus",
"else",
"None"
] | Set the focus node(s). If no focus node is specified, the evaluation will occur for all non-BNode
graph subjects. Otherwise it can be a string, a URIRef or a list of string/URIRef combinations
:param focus: None if focus should be all URIRefs in the graph otherwise a URI or list of URI's | [
"Set",
"the",
"focus",
"node",
"(",
"s",
")",
".",
"If",
"no",
"focus",
"node",
"is",
"specified",
"the",
"evaluation",
"will",
"occur",
"for",
"all",
"non",
"-",
"BNode",
"graph",
"subjects",
".",
"Otherwise",
"it",
"can",
"be",
"a",
"string",
"a",
... | python | train | 63.142857 |
RudolfCardinal/pythonlib | cardinal_pythonlib/datetimefunc.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L342-L379 | def get_duration_h_m(start: Union[str, DateTime],
end: Union[str, DateTime],
default: str = "N/A") -> str:
"""
Calculate the time between two dates/times expressed as strings.
Args:
start: start date/time
end: end date/time
default: string v... | [
"def",
"get_duration_h_m",
"(",
"start",
":",
"Union",
"[",
"str",
",",
"DateTime",
"]",
",",
"end",
":",
"Union",
"[",
"str",
",",
"DateTime",
"]",
",",
"default",
":",
"str",
"=",
"\"N/A\"",
")",
"->",
"str",
":",
"start",
"=",
"coerce_to_pendulum",
... | Calculate the time between two dates/times expressed as strings.
Args:
start: start date/time
end: end date/time
default: string value to return in case either of the inputs is
``None``
Returns:
a string that is one of
.. code-block:
'hh:mm'
... | [
"Calculate",
"the",
"time",
"between",
"two",
"dates",
"/",
"times",
"expressed",
"as",
"strings",
"."
] | python | train | 29.421053 |
fermiPy/fermipy | fermipy/jobs/link.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/link.py#L475-L480 | def _update_file_args(self, file_mapping):
"""Adjust the arguments to deal with staging files to the scratch area"""
for key, value in self.args.items():
new_value = file_mapping.get(value, value)
if new_value != value:
self.args[key] = new_value | [
"def",
"_update_file_args",
"(",
"self",
",",
"file_mapping",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"args",
".",
"items",
"(",
")",
":",
"new_value",
"=",
"file_mapping",
".",
"get",
"(",
"value",
",",
"value",
")",
"if",
"new_value"... | Adjust the arguments to deal with staging files to the scratch area | [
"Adjust",
"the",
"arguments",
"to",
"deal",
"with",
"staging",
"files",
"to",
"the",
"scratch",
"area"
] | python | train | 49.5 |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/dtypes.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/dtypes.py#L184-L209 | def min(self):
"""Returns the minimum representable value in this data type.
Raises:
TypeError: if this is a non-numeric, unordered, or quantized type.
"""
if self.is_quantized or self.base_dtype in (
bool,
string,
complex64,
co... | [
"def",
"min",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_quantized",
"or",
"self",
".",
"base_dtype",
"in",
"(",
"bool",
",",
"string",
",",
"complex64",
",",
"complex128",
",",
")",
":",
"raise",
"TypeError",
"(",
"\"Cannot find minimum value of %s.\"",
... | Returns the minimum representable value in this data type.
Raises:
TypeError: if this is a non-numeric, unordered, or quantized type. | [
"Returns",
"the",
"minimum",
"representable",
"value",
"in",
"this",
"data",
"type",
"."
] | python | train | 36.230769 |
openstack/proliantutils | proliantutils/ilo/common.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/common.py#L84-L94 | def wait_for_ilo_after_reset(ilo_object):
"""Continuously polls for iLO to come up after reset."""
is_ilo_up_after_reset = lambda: ilo_object.get_product_name() is not None
is_ilo_up_after_reset.__name__ = 'is_ilo_up_after_reset'
wait_for_operation_to_complete(
is_ilo_up_after_reset,
f... | [
"def",
"wait_for_ilo_after_reset",
"(",
"ilo_object",
")",
":",
"is_ilo_up_after_reset",
"=",
"lambda",
":",
"ilo_object",
".",
"get_product_name",
"(",
")",
"is",
"not",
"None",
"is_ilo_up_after_reset",
".",
"__name__",
"=",
"'is_ilo_up_after_reset'",
"wait_for_operati... | Continuously polls for iLO to come up after reset. | [
"Continuously",
"polls",
"for",
"iLO",
"to",
"come",
"up",
"after",
"reset",
"."
] | python | train | 37 |
orbingol/NURBS-Python | geomdl/operations.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1082-L1151 | def split_surface_u(obj, param, **kwargs):
""" Splits the surface at the input parametric coordinate on the u-direction.
This method splits the surface into two pieces at the given parametric coordinate on the u-direction,
generates two different surface objects and returns them. It does not modify the inp... | [
"def",
"split_surface_u",
"(",
"obj",
",",
"param",
",",
"*",
"*",
"kwargs",
")",
":",
"# Validate input",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"abstract",
".",
"Surface",
")",
":",
"raise",
"GeomdlException",
"(",
"\"Input shape must be an instance of ab... | Splits the surface at the input parametric coordinate on the u-direction.
This method splits the surface into two pieces at the given parametric coordinate on the u-direction,
generates two different surface objects and returns them. It does not modify the input surface.
Keyword Arguments:
* ``fin... | [
"Splits",
"the",
"surface",
"at",
"the",
"input",
"parametric",
"coordinate",
"on",
"the",
"u",
"-",
"direction",
"."
] | python | train | 38.614286 |
twilio/twilio-python | twilio/twiml/voice_response.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/twiml/voice_response.py#L953-L979 | def number(self, phone_number, send_digits=None, url=None, method=None,
status_callback_event=None, status_callback=None,
status_callback_method=None, **kwargs):
"""
Create a <Number> element
:param phone_number: Phone Number to dial
:param send_digits: DTM... | [
"def",
"number",
"(",
"self",
",",
"phone_number",
",",
"send_digits",
"=",
"None",
",",
"url",
"=",
"None",
",",
"method",
"=",
"None",
",",
"status_callback_event",
"=",
"None",
",",
"status_callback",
"=",
"None",
",",
"status_callback_method",
"=",
"None... | Create a <Number> element
:param phone_number: Phone Number to dial
:param send_digits: DTMF tones to play when the call is answered
:param url: TwiML URL
:param method: TwiML URL method
:param status_callback_event: Events to call status callback
:param status_callback:... | [
"Create",
"a",
"<Number",
">",
"element"
] | python | train | 37.851852 |
alefnula/tea | tea/shell/__init__.py | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L399-L425 | def touch(path, content="", encoding="utf-8", overwrite=False):
"""Create a file at the given path if it does not already exists.
Args:
path (str): Path to the file.
content (str): Optional content that will be written in the file.
encoding (str): Encoding in which to write the content.... | [
"def",
"touch",
"(",
"path",
",",
"content",
"=",
"\"\"",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"overwrite",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"if",
"not",
"overwrite",
"and",
"os",
".",
"pa... | Create a file at the given path if it does not already exists.
Args:
path (str): Path to the file.
content (str): Optional content that will be written in the file.
encoding (str): Encoding in which to write the content.
Default: ``utf-8``
overwrite (bool): Overwrite the... | [
"Create",
"a",
"file",
"at",
"the",
"given",
"path",
"if",
"it",
"does",
"not",
"already",
"exists",
"."
] | python | train | 36.444444 |
GaretJax/lancet | lancet/commands/configuration.py | https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/commands/configuration.py#L63-L111 | def init(ctx, force):
"""Wizard to create a project-level configuration file."""
if os.path.exists(PROJECT_CONFIG) and not force:
click.secho(
'An existing configuration file was found at "{}".\n'
.format(PROJECT_CONFIG),
fg='red', bold=True
)
click.se... | [
"def",
"init",
"(",
"ctx",
",",
"force",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"PROJECT_CONFIG",
")",
"and",
"not",
"force",
":",
"click",
".",
"secho",
"(",
"'An existing configuration file was found at \"{}\".\\n'",
".",
"format",
"(",
"PR... | Wizard to create a project-level configuration file. | [
"Wizard",
"to",
"create",
"a",
"project",
"-",
"level",
"configuration",
"file",
"."
] | python | train | 33.061224 |
chemlab/chemlab | chemlab/graphics/qt/qttrajectory.py | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qttrajectory.py#L229-L237 | def set_ticks(self, number):
'''Set the number of frames to animate.
'''
self.max_index = number
self.current_index = 0
self.slider.setMaximum(self.max_index-1)
self.slider.setMinimum(0)
self.slider.setPageStep(1) | [
"def",
"set_ticks",
"(",
"self",
",",
"number",
")",
":",
"self",
".",
"max_index",
"=",
"number",
"self",
".",
"current_index",
"=",
"0",
"self",
".",
"slider",
".",
"setMaximum",
"(",
"self",
".",
"max_index",
"-",
"1",
")",
"self",
".",
"slider",
... | Set the number of frames to animate. | [
"Set",
"the",
"number",
"of",
"frames",
"to",
"animate",
"."
] | python | train | 29.111111 |
miquelo/resort | packages/resort/component/glassfish.py | https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/component/glassfish.py#L58-L83 | def get(self, res_path, timeout=10.):
"""
Get operation.
:param str res_path:
Resource path.
:param float timeout:
Timeout in seconds.
:rtype:
tuple
:return:
Tuple with status code and response body.
"""
resp = requests.get(
self.__res_uri(res_path),
headers=self.__head... | [
"def",
"get",
"(",
"self",
",",
"res_path",
",",
"timeout",
"=",
"10.",
")",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"__res_uri",
"(",
"res_path",
")",
",",
"headers",
"=",
"self",
".",
"__headers",
"(",
")",
",",
"verify",
"=",... | Get operation.
:param str res_path:
Resource path.
:param float timeout:
Timeout in seconds.
:rtype:
tuple
:return:
Tuple with status code and response body. | [
"Get",
"operation",
".",
":",
"param",
"str",
"res_path",
":",
"Resource",
"path",
".",
":",
"param",
"float",
"timeout",
":",
"Timeout",
"in",
"seconds",
".",
":",
"rtype",
":",
"tuple",
":",
"return",
":",
"Tuple",
"with",
"status",
"code",
"and",
"r... | python | train | 17.692308 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L890-L901 | def _create_service_nwk(self, tenant_id, tenant_name, direc):
"""Function to create the service in network in DCNM. """
net_dict = self.retrieve_dcnm_net_info(tenant_id, direc)
net = utils.Dict2Obj(net_dict)
subnet_dict = self.retrieve_dcnm_subnet_info(tenant_id, direc)
subnet = ... | [
"def",
"_create_service_nwk",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"direc",
")",
":",
"net_dict",
"=",
"self",
".",
"retrieve_dcnm_net_info",
"(",
"tenant_id",
",",
"direc",
")",
"net",
"=",
"utils",
".",
"Dict2Obj",
"(",
"net_dict",
")",
... | Function to create the service in network in DCNM. | [
"Function",
"to",
"create",
"the",
"service",
"in",
"network",
"in",
"DCNM",
"."
] | python | train | 48.416667 |
poppy-project/pypot | pypot/vrep/remoteApiBindings/vrep.py | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/remoteApiBindings/vrep.py#L875-L888 | def simxGetObjectSelection(clientID, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
objectCount = ct.c_int()
objectHandles = ct.POINTER(ct.c_int)()
ret = c_GetObjectSelection(clientID, ct.byref(objectHandles), ct.byref(objectCount)... | [
"def",
"simxGetObjectSelection",
"(",
"clientID",
",",
"operationMode",
")",
":",
"objectCount",
"=",
"ct",
".",
"c_int",
"(",
")",
"objectHandles",
"=",
"ct",
".",
"POINTER",
"(",
"ct",
".",
"c_int",
")",
"(",
")",
"ret",
"=",
"c_GetObjectSelection",
"(",... | Please have a look at the function description/documentation in the V-REP user manual | [
"Please",
"have",
"a",
"look",
"at",
"the",
"function",
"description",
"/",
"documentation",
"in",
"the",
"V",
"-",
"REP",
"user",
"manual"
] | python | train | 33.428571 |
da4089/simplefix | simplefix/message.py | https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L663-L682 | def _tz_offset_string(offset):
"""(Internal) Convert TZ offset in minutes east to string."""
s = ""
io = int(offset)
if io == 0:
s += "Z"
else:
if -1440 < io < 1440:
ho = abs(io) / 60
mo = abs(io) % 60
s +=... | [
"def",
"_tz_offset_string",
"(",
"offset",
")",
":",
"s",
"=",
"\"\"",
"io",
"=",
"int",
"(",
"offset",
")",
"if",
"io",
"==",
"0",
":",
"s",
"+=",
"\"Z\"",
"else",
":",
"if",
"-",
"1440",
"<",
"io",
"<",
"1440",
":",
"ho",
"=",
"abs",
"(",
"... | (Internal) Convert TZ offset in minutes east to string. | [
"(",
"Internal",
")",
"Convert",
"TZ",
"offset",
"in",
"minutes",
"east",
"to",
"string",
"."
] | python | train | 28.95 |
lgpage/nbtutor | nbtutor/ipython/utils.py | https://github.com/lgpage/nbtutor/blob/07798a044cf6e1fd4eaac2afddeef3e13348dbcd/nbtutor/ipython/utils.py#L128-L162 | def get_type_info(obj):
"""Get type information for a Python object
Args:
obj: The Python object
Returns:
tuple: (object type "catagory", object type name)
"""
if isinstance(obj, primitive_types):
return ('primitive', type(obj).__name__)
if isinstance(obj, sequence_type... | [
"def",
"get_type_info",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"primitive_types",
")",
":",
"return",
"(",
"'primitive'",
",",
"type",
"(",
"obj",
")",
".",
"__name__",
")",
"if",
"isinstance",
"(",
"obj",
",",
"sequence_types",
")",
... | Get type information for a Python object
Args:
obj: The Python object
Returns:
tuple: (object type "catagory", object type name) | [
"Get",
"type",
"information",
"for",
"a",
"Python",
"object"
] | python | valid | 36.171429 |
kstaniek/condoor | condoor/device.py | https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L409-L418 | def update_driver(self, prompt):
"""Update driver based on new prompt."""
prompt = prompt.lstrip()
self.chain.connection.log("({}): Prompt: '{}'".format(self.driver.platform, prompt))
self.prompt = prompt
driver_name = self.driver.update_driver(prompt)
if driver_name is N... | [
"def",
"update_driver",
"(",
"self",
",",
"prompt",
")",
":",
"prompt",
"=",
"prompt",
".",
"lstrip",
"(",
")",
"self",
".",
"chain",
".",
"connection",
".",
"log",
"(",
"\"({}): Prompt: '{}'\"",
".",
"format",
"(",
"self",
".",
"driver",
".",
"platform"... | Update driver based on new prompt. | [
"Update",
"driver",
"based",
"on",
"new",
"prompt",
"."
] | python | train | 49.4 |
chinapnr/fishbase | fishbase/fish_random.py | https://github.com/chinapnr/fishbase/blob/23c5147a6bc0d8ed36409e55352ffb2c5b0edc82/fishbase/fish_random.py#L159-L189 | def gen_random_mobile():
"""
随机生成一个手机号
:return:
* str: (string) 手机号
举例如下::
print('--- gen_random_mobile demo ---')
print(gen_random_mobile())
print(gen_random_mobile())
print('---')
执行结果::
--- gen_random_mobile demo ---
16706146773
... | [
"def",
"gen_random_mobile",
"(",
")",
":",
"prefix_list",
"=",
"[",
"\"13\"",
",",
"\"1400\"",
",",
"\"1410\"",
",",
"\"1440\"",
",",
"\"145\"",
",",
"\"146\"",
",",
"\"147\"",
",",
"\"148\"",
",",
"\"15\"",
",",
"\"162\"",
",",
"\"165\"",
",",
"\"166\"",
... | 随机生成一个手机号
:return:
* str: (string) 手机号
举例如下::
print('--- gen_random_mobile demo ---')
print(gen_random_mobile())
print(gen_random_mobile())
print('---')
执行结果::
--- gen_random_mobile demo ---
16706146773
14402633925
--- | [
"随机生成一个手机号"
] | python | train | 25.193548 |
niccokunzmann/hanging_threads | hanging_threads.py | https://github.com/niccokunzmann/hanging_threads/blob/167f4faa9ef7bf44866d9cda75d30606acb3c416/hanging_threads.py#L199-L204 | def write_log(title, message=''):
"""Write formatted log message to stderr."""
sys.stderr.write(''.join([
title.center(40).center(60, '-'), '\n', message
])) | [
"def",
"write_log",
"(",
"title",
",",
"message",
"=",
"''",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"''",
".",
"join",
"(",
"[",
"title",
".",
"center",
"(",
"40",
")",
".",
"center",
"(",
"60",
",",
"'-'",
")",
",",
"'\\n'",
",",
... | Write formatted log message to stderr. | [
"Write",
"formatted",
"log",
"message",
"to",
"stderr",
"."
] | python | train | 28.833333 |
python-odin/odinweb | odinweb/data_structures.py | https://github.com/python-odin/odinweb/blob/198424133584acc18cb41c8d18d91f803abc810f/odinweb/data_structures.py#L587-L592 | def pre_dispatch(self):
"""
List of pre-dispatch methods from registered middleware.
"""
middleware = sort_by_priority(self)
return tuple(m.pre_dispatch for m in middleware if hasattr(m, 'pre_dispatch')) | [
"def",
"pre_dispatch",
"(",
"self",
")",
":",
"middleware",
"=",
"sort_by_priority",
"(",
"self",
")",
"return",
"tuple",
"(",
"m",
".",
"pre_dispatch",
"for",
"m",
"in",
"middleware",
"if",
"hasattr",
"(",
"m",
",",
"'pre_dispatch'",
")",
")"
] | List of pre-dispatch methods from registered middleware. | [
"List",
"of",
"pre",
"-",
"dispatch",
"methods",
"from",
"registered",
"middleware",
"."
] | python | train | 39.666667 |
gitpython-developers/GitPython | git/index/fun.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/index/fun.py#L159-L168 | def read_header(stream):
"""Return tuple(version_long, num_entries) from the given stream"""
type_id = stream.read(4)
if type_id != b"DIRC":
raise AssertionError("Invalid index file header: %r" % type_id)
version, num_entries = unpack(">LL", stream.read(4 * 2))
# TODO: handle version 3: ext... | [
"def",
"read_header",
"(",
"stream",
")",
":",
"type_id",
"=",
"stream",
".",
"read",
"(",
"4",
")",
"if",
"type_id",
"!=",
"b\"DIRC\"",
":",
"raise",
"AssertionError",
"(",
"\"Invalid index file header: %r\"",
"%",
"type_id",
")",
"version",
",",
"num_entries... | Return tuple(version_long, num_entries) from the given stream | [
"Return",
"tuple",
"(",
"version_long",
"num_entries",
")",
"from",
"the",
"given",
"stream"
] | python | train | 40 |
josiah-wolf-oberholtzer/uqbar | uqbar/containers/UniqueTreeContainer.py | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/containers/UniqueTreeContainer.py#L128-L177 | def depth_first(self, top_down=True):
"""
Iterate depth-first.
::
>>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode
>>> root_container = UniqueTreeContainer(name="root")
>>> outer_container = UniqueTreeContainer(name="outer")
>... | [
"def",
"depth_first",
"(",
"self",
",",
"top_down",
"=",
"True",
")",
":",
"for",
"child",
"in",
"tuple",
"(",
"self",
")",
":",
"if",
"top_down",
":",
"yield",
"child",
"if",
"isinstance",
"(",
"child",
",",
"UniqueTreeContainer",
")",
":",
"yield",
"... | Iterate depth-first.
::
>>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode
>>> root_container = UniqueTreeContainer(name="root")
>>> outer_container = UniqueTreeContainer(name="outer")
>>> inner_container = UniqueTreeContainer(name="inner")
... | [
"Iterate",
"depth",
"-",
"first",
"."
] | python | train | 28.7 |
Azure/azure-cli-extensions | src/express-route-cross-connection/azext_expressroutecrossconnection/vendored_sdks/network_management_client.py | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/express-route-cross-connection/azext_expressroutecrossconnection/vendored_sdks/network_management_client.py#L168-L220 | def models(cls, api_version=DEFAULT_API_VERSION):
"""Module depends on the API version:
* 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.network.v2015_06_15.models>`
* 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.network.v2016_09_01.models>`
* 2016-12-01: :mod:`v2016_12_01.... | [
"def",
"models",
"(",
"cls",
",",
"api_version",
"=",
"DEFAULT_API_VERSION",
")",
":",
"if",
"api_version",
"==",
"'2015-06-15'",
":",
"from",
".",
"v2015_06_15",
"import",
"models",
"return",
"models",
"elif",
"api_version",
"==",
"'2016-09-01'",
":",
"from",
... | Module depends on the API version:
* 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.network.v2015_06_15.models>`
* 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.network.v2016_09_01.models>`
* 2016-12-01: :mod:`v2016_12_01.models<azure.mgmt.network.v2016_12_01.models>`
* 2... | [
"Module",
"depends",
"on",
"the",
"API",
"version",
":"
] | python | train | 48.415094 |
spacetelescope/stsci.tools | lib/stsci/tools/check_files.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/check_files.py#L239-L340 | def splitStis(stisfile, sci_count):
"""
Split a STIS association file into multiple imset MEF files.
Split the corresponding spt file if present into single spt files.
If an spt file can't be split or is missing a Warning is printed.
Returns
-------
names: list
a list with the name... | [
"def",
"splitStis",
"(",
"stisfile",
",",
"sci_count",
")",
":",
"newfiles",
"=",
"[",
"]",
"toclose",
"=",
"False",
"if",
"isinstance",
"(",
"stisfile",
",",
"str",
")",
":",
"f",
"=",
"fits",
".",
"open",
"(",
"stisfile",
")",
"toclose",
"=",
"True... | Split a STIS association file into multiple imset MEF files.
Split the corresponding spt file if present into single spt files.
If an spt file can't be split or is missing a Warning is printed.
Returns
-------
names: list
a list with the names of the new flt files. | [
"Split",
"a",
"STIS",
"association",
"file",
"into",
"multiple",
"imset",
"MEF",
"files",
"."
] | python | train | 32.333333 |
jldantas/libmft | libmft/api.py | https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L405-L427 | def add_data_attribute(self, data_attr):
'''Interprets a DATA attribute and add it to the datastream.'''
if data_attr.header.attr_type_id is not AttrTypes.DATA:
raise DataStreamError("Invalid attribute. A Datastream deals only with DATA attributes")
if data_attr.header.attr_name != s... | [
"def",
"add_data_attribute",
"(",
"self",
",",
"data_attr",
")",
":",
"if",
"data_attr",
".",
"header",
".",
"attr_type_id",
"is",
"not",
"AttrTypes",
".",
"DATA",
":",
"raise",
"DataStreamError",
"(",
"\"Invalid attribute. A Datastream deals only with DATA attributes\"... | Interprets a DATA attribute and add it to the datastream. | [
"Interprets",
"a",
"DATA",
"attribute",
"and",
"add",
"it",
"to",
"the",
"datastream",
"."
] | python | train | 54.608696 |
bitesofcode/projexui | projexui/windows/xdkwindow/xdkwindow.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L503-L529 | def search( self ):
"""
Looks up the current search terms from the xdk files that are loaded.
"""
QApplication.instance().setOverrideCursor(Qt.WaitCursor)
terms = nativestring(self.uiSearchTXT.text())
html = []
entry_html = '<a h... | [
"def",
"search",
"(",
"self",
")",
":",
"QApplication",
".",
"instance",
"(",
")",
".",
"setOverrideCursor",
"(",
"Qt",
".",
"WaitCursor",
")",
"terms",
"=",
"nativestring",
"(",
"self",
".",
"uiSearchTXT",
".",
"text",
"(",
")",
")",
"html",
"=",
"[",... | Looks up the current search terms from the xdk files that are loaded. | [
"Looks",
"up",
"the",
"current",
"search",
"terms",
"from",
"the",
"xdk",
"files",
"that",
"are",
"loaded",
"."
] | python | train | 36.148148 |
pyca/pyopenssl | src/OpenSSL/crypto.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L134-L140 | def _bio_to_string(bio):
"""
Copy the contents of an OpenSSL BIO object into a Python byte string.
"""
result_buffer = _ffi.new('char**')
buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
return _ffi.buffer(result_buffer[0], buffer_length)[:] | [
"def",
"_bio_to_string",
"(",
"bio",
")",
":",
"result_buffer",
"=",
"_ffi",
".",
"new",
"(",
"'char**'",
")",
"buffer_length",
"=",
"_lib",
".",
"BIO_get_mem_data",
"(",
"bio",
",",
"result_buffer",
")",
"return",
"_ffi",
".",
"buffer",
"(",
"result_buffer"... | Copy the contents of an OpenSSL BIO object into a Python byte string. | [
"Copy",
"the",
"contents",
"of",
"an",
"OpenSSL",
"BIO",
"object",
"into",
"a",
"Python",
"byte",
"string",
"."
] | python | test | 38.285714 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L110-L121 | def set_centralized_assembled_rows_cols(self, irn, jcn):
"""Set assembled matrix indices on processor 0.
The row and column indices (irn & jcn) should be one based.
"""
if self.myid != 0:
return
assert irn.size == jcn.size
self._refs.update(irn=irn, jcn=jcn)
... | [
"def",
"set_centralized_assembled_rows_cols",
"(",
"self",
",",
"irn",
",",
"jcn",
")",
":",
"if",
"self",
".",
"myid",
"!=",
"0",
":",
"return",
"assert",
"irn",
".",
"size",
"==",
"jcn",
".",
"size",
"self",
".",
"_refs",
".",
"update",
"(",
"irn",
... | Set assembled matrix indices on processor 0.
The row and column indices (irn & jcn) should be one based. | [
"Set",
"assembled",
"matrix",
"indices",
"on",
"processor",
"0",
"."
] | python | train | 35.333333 |
saltstack/salt | salt/modules/azurearm_compute.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L80-L145 | def availability_set_create_or_update(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Create or update an availability set.
:param name: The availability set to create.
:param resource_group: The resource group name assigned to the
availabil... | [
"def",
"availability_set_create_or_update",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"if",
"'location'",
"not",
"in",
"kwargs",
":",
"rg_props",
"=",
"__salt__",
"[",
"'azurearm_resource.resource_group_get'... | .. versionadded:: 2019.2.0
Create or update an availability set.
:param name: The availability set to create.
:param resource_group: The resource group name assigned to the
availability set.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_set_create_or... | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | python | train | 32.712121 |
wickman/compactor | compactor/process.py | https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/process.py#L15-L43 | def route(cls, path):
"""A decorator to indicate that a method should be a routable HTTP endpoint.
.. code-block:: python
from compactor.process import Process
class WebProcess(Process):
@Process.route('/hello/world')
def hello_world(self, handler):
return hand... | [
"def",
"route",
"(",
"cls",
",",
"path",
")",
":",
"if",
"not",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"raise",
"ValueError",
"(",
"'Routes must start with \"/\"'",
")",
"def",
"wrap",
"(",
"fn",
")",
":",
"setattr",
"(",
"fn",
",",
"cls",
... | A decorator to indicate that a method should be a routable HTTP endpoint.
.. code-block:: python
from compactor.process import Process
class WebProcess(Process):
@Process.route('/hello/world')
def hello_world(self, handler):
return handler.write('<html><title>hello... | [
"A",
"decorator",
"to",
"indicate",
"that",
"a",
"method",
"should",
"be",
"a",
"routable",
"HTTP",
"endpoint",
"."
] | python | train | 27.931034 |
zaturox/glin | glin/app.py | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L273-L277 | def publish_active_scene(self, scene_id):
"""publish changed active scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_active(self.sequence_number, scene_id))
return self.sequence_number | [
"def",
"publish_active_scene",
"(",
"self",
",",
"scene_id",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"scene_active",
"(",
"self",
".",
"sequence_number",
","... | publish changed active scene | [
"publish",
"changed",
"active",
"scene"
] | python | train | 50.8 |
ceph/ceph-deploy | ceph_deploy/install.py | https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/install.py#L658-L670 | def make_purge_data(parser):
"""
Purge (delete, destroy, discard, shred) any Ceph data from /var/lib/ceph
"""
parser.add_argument(
'host',
metavar='HOST',
nargs='+',
help='hosts to purge Ceph data from',
)
parser.set_defaults(
func=purgedata,
) | [
"def",
"make_purge_data",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'host'",
",",
"metavar",
"=",
"'HOST'",
",",
"nargs",
"=",
"'+'",
",",
"help",
"=",
"'hosts to purge Ceph data from'",
",",
")",
"parser",
".",
"set_defaults",
"(",
"func... | Purge (delete, destroy, discard, shred) any Ceph data from /var/lib/ceph | [
"Purge",
"(",
"delete",
"destroy",
"discard",
"shred",
")",
"any",
"Ceph",
"data",
"from",
"/",
"var",
"/",
"lib",
"/",
"ceph"
] | python | train | 23.692308 |
numenta/htmresearch | htmresearch/support/neural_correlations_utils.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L202-L215 | def sampleCellsWithinColumns(numCellPairs, cellsPerColumn, numColumns, seed=42):
"""
Generate indices of cell pairs, each pair of cells are from the same column
@return cellPairs (list) list of cell pairs
"""
np.random.seed(seed)
cellPairs = []
for i in range(numCellPairs):
randCol = np.random.randint... | [
"def",
"sampleCellsWithinColumns",
"(",
"numCellPairs",
",",
"cellsPerColumn",
",",
"numColumns",
",",
"seed",
"=",
"42",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"cellPairs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"numCellPa... | Generate indices of cell pairs, each pair of cells are from the same column
@return cellPairs (list) list of cell pairs | [
"Generate",
"indices",
"of",
"cell",
"pairs",
"each",
"pair",
"of",
"cells",
"are",
"from",
"the",
"same",
"column"
] | python | train | 36.142857 |
brutus/wtforms-html5 | setup.py | https://github.com/brutus/wtforms-html5/blob/a00ab7c68e6238bfa317f40ec3de807dae8ed85e/setup.py#L33-L50 | def read_file(filename, prepend_paths=[]):
"""
Returns the contents of *filename* (UTF-8).
If *prepend_paths* is set, join those before the *fielname*.
If it is `True`, prepend the path to `setup.py`.
"""
if prepend_paths is True:
prepend_paths = [
os.path.abspath(os.path.dirname(__file__)),
... | [
"def",
"read_file",
"(",
"filename",
",",
"prepend_paths",
"=",
"[",
"]",
")",
":",
"if",
"prepend_paths",
"is",
"True",
":",
"prepend_paths",
"=",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
... | Returns the contents of *filename* (UTF-8).
If *prepend_paths* is set, join those before the *fielname*.
If it is `True`, prepend the path to `setup.py`. | [
"Returns",
"the",
"contents",
"of",
"*",
"filename",
"*",
"(",
"UTF",
"-",
"8",
")",
"."
] | python | train | 27.111111 |
dossier/dossier.store | dossier/store/elastic.py | https://github.com/dossier/dossier.store/blob/b22ffe2470bba9fcc98a30cb55b437bfa1521e7f/dossier/store/elastic.py#L255-L263 | def delete_index(self):
'''Deletes the underlying ES index.
Only use this if you know what you're doing. This destroys
the entire underlying ES index, which could be shared by
multiple distinct ElasticStore instances.
'''
if self.conn.indices.exists(index=self.index):
... | [
"def",
"delete_index",
"(",
"self",
")",
":",
"if",
"self",
".",
"conn",
".",
"indices",
".",
"exists",
"(",
"index",
"=",
"self",
".",
"index",
")",
":",
"self",
".",
"conn",
".",
"indices",
".",
"delete",
"(",
"index",
"=",
"self",
".",
"index",
... | Deletes the underlying ES index.
Only use this if you know what you're doing. This destroys
the entire underlying ES index, which could be shared by
multiple distinct ElasticStore instances. | [
"Deletes",
"the",
"underlying",
"ES",
"index",
"."
] | python | test | 40.444444 |
matthew-brett/delocate | delocate/wheeltools.py | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/wheeltools.py#L28-L32 | def _open_for_csv(name, mode):
""" Deal with Python 2/3 open API differences """
if sys.version_info[0] < 3:
return open_rw(name, mode + 'b')
return open_rw(name, mode, newline='', encoding='utf-8') | [
"def",
"_open_for_csv",
"(",
"name",
",",
"mode",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"return",
"open_rw",
"(",
"name",
",",
"mode",
"+",
"'b'",
")",
"return",
"open_rw",
"(",
"name",
",",
"mode",
",",
"newline... | Deal with Python 2/3 open API differences | [
"Deal",
"with",
"Python",
"2",
"/",
"3",
"open",
"API",
"differences"
] | python | train | 42.8 |
funilrys/PyFunceble | PyFunceble/__init__.py | https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/__init__.py#L340-L365 | def ipv4_syntax_check(ip): # pragma: no cover
"""
Check the syntax of the given IPv4.
:param ip: The IPv4 to check the syntax for.
:type ip: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we return :code:`None`.
""... | [
"def",
"ipv4_syntax_check",
"(",
"ip",
")",
":",
"# pragma: no cover",
"if",
"ip",
"and",
"isinstance",
"(",
"ip",
",",
"str",
")",
":",
"# The given IP is not empty nor None.",
"# and",
"# * The given IP is a string.",
"# We silently load the configuration.",
"load_config"... | Check the syntax of the given IPv4.
:param ip: The IPv4 to check the syntax for.
:type ip: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we return :code:`None`. | [
"Check",
"the",
"syntax",
"of",
"the",
"given",
"IPv4",
"."
] | python | test | 23.423077 |
skorch-dev/skorch | skorch/callbacks/training.py | https://github.com/skorch-dev/skorch/blob/5b9b8b7b7712cb6e5aaa759d9608ea6269d5bcd3/skorch/callbacks/training.py#L192-L217 | def save_model(self, net):
"""Save the model.
This function saves some or all of the following:
- model parameters;
- optimizer state;
- training history;
- entire model object.
"""
if self.f_params is not None:
f = self._format_targe... | [
"def",
"save_model",
"(",
"self",
",",
"net",
")",
":",
"if",
"self",
".",
"f_params",
"is",
"not",
"None",
":",
"f",
"=",
"self",
".",
"_format_target",
"(",
"net",
",",
"self",
".",
"f_params",
",",
"-",
"1",
")",
"self",
".",
"_save_params",
"("... | Save the model.
This function saves some or all of the following:
- model parameters;
- optimizer state;
- training history;
- entire model object. | [
"Save",
"the",
"model",
"."
] | python | train | 34.038462 |
diux-dev/ncluster | ncluster/aws_util.py | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L171-L187 | def get_keypair_dict():
"""Returns dictionary of {keypairname: keypair}"""
client = get_ec2_client()
response = client.describe_key_pairs()
assert is_good_response(response)
result = {}
ec2 = get_ec2_resource()
for keypair in response['KeyPairs']:
keypair_name = keypair.get('KeyName', '')
if key... | [
"def",
"get_keypair_dict",
"(",
")",
":",
"client",
"=",
"get_ec2_client",
"(",
")",
"response",
"=",
"client",
".",
"describe_key_pairs",
"(",
")",
"assert",
"is_good_response",
"(",
"response",
")",
"result",
"=",
"{",
"}",
"ec2",
"=",
"get_ec2_resource",
... | Returns dictionary of {keypairname: keypair} | [
"Returns",
"dictionary",
"of",
"{",
"keypairname",
":",
"keypair",
"}"
] | python | train | 32.352941 |
wandb/client | wandb/apis/__init__.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/apis/__init__.py#L24-L29 | def read(self, size=-1):
"""Read bytes and call the callback"""
bites = self.file.read(size)
self.bytes_read += len(bites)
self.callback(len(bites), self.bytes_read)
return bites | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"bites",
"=",
"self",
".",
"file",
".",
"read",
"(",
"size",
")",
"self",
".",
"bytes_read",
"+=",
"len",
"(",
"bites",
")",
"self",
".",
"callback",
"(",
"len",
"(",
"bites",
")... | Read bytes and call the callback | [
"Read",
"bytes",
"and",
"call",
"the",
"callback"
] | python | train | 35.5 |
akesterson/dpath-python | dpath/path.py | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/path.py#L236-L284 | def get(obj, path, view=False, afilter=None):
"""Get the value of the given path.
Arguments:
obj -- Object to look in.
path -- A list of keys representing the path.
Keyword Arguments:
view -- Return a view of the object.
"""
index = 0
path_count = len(path) - 1
target = obj
... | [
"def",
"get",
"(",
"obj",
",",
"path",
",",
"view",
"=",
"False",
",",
"afilter",
"=",
"None",
")",
":",
"index",
"=",
"0",
"path_count",
"=",
"len",
"(",
"path",
")",
"-",
"1",
"target",
"=",
"obj",
"head",
"=",
"type",
"(",
"target",
")",
"("... | Get the value of the given path.
Arguments:
obj -- Object to look in.
path -- A list of keys representing the path.
Keyword Arguments:
view -- Return a view of the object. | [
"Get",
"the",
"value",
"of",
"the",
"given",
"path",
"."
] | python | train | 27.020408 |
tango-controls/pytango | tango/utils.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/utils.py#L589-L606 | def is_numerical(tg_type, inc_array=False):
"""Tells if the given tango type is numerical
:param tg_type: tango type
:type tg_type: :class:`tango.CmdArgType`
:param inc_array: (optional, default is False) determines if include array
in the list of checked types
:type inc_array... | [
"def",
"is_numerical",
"(",
"tg_type",
",",
"inc_array",
"=",
"False",
")",
":",
"global",
"_scalar_numerical_types",
",",
"_array_numerical_types",
"if",
"tg_type",
"in",
"_scalar_numerical_types",
":",
"return",
"True",
"if",
"not",
"inc_array",
":",
"return",
"... | Tells if the given tango type is numerical
:param tg_type: tango type
:type tg_type: :class:`tango.CmdArgType`
:param inc_array: (optional, default is False) determines if include array
in the list of checked types
:type inc_array: :py:obj:`bool`
:return: True if the given ta... | [
"Tells",
"if",
"the",
"given",
"tango",
"type",
"is",
"numerical"
] | python | train | 35.611111 |
SheffieldML/GPy | GPy/models/state_space_main.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/models/state_space_main.py#L1276-L1354 | def _kalman_prediction_step(k, p_m , p_P, p_dyn_model_callable, calc_grad_log_likelihood=False,
p_dm = None, p_dP = None):
"""
Desctrete prediction function
Input:
k:int
Iteration No. Starts at 0. Total number of iterations equal to th... | [
"def",
"_kalman_prediction_step",
"(",
"k",
",",
"p_m",
",",
"p_P",
",",
"p_dyn_model_callable",
",",
"calc_grad_log_likelihood",
"=",
"False",
",",
"p_dm",
"=",
"None",
",",
"p_dP",
"=",
"None",
")",
":",
"# index correspond to values from previous iteration.",
"A"... | Desctrete prediction function
Input:
k:int
Iteration No. Starts at 0. Total number of iterations equal to the
number of measurements.
p_m: matrix of size (state_dim, time_series_no)
Mean value from the previous step. For "multiple time se... | [
"Desctrete",
"prediction",
"function"
] | python | train | 38.177215 |
docker/docker-py | docker/api/client.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/api/client.py#L372-L391 | def _multiplexed_response_stream_helper(self, response):
"""A generator of multiplexed data blocks coming from a response
stream."""
# Disable timeout on the underlying socket to prevent
# Read timed out(s) for long running processes
socket = self._get_raw_response_socket(respon... | [
"def",
"_multiplexed_response_stream_helper",
"(",
"self",
",",
"response",
")",
":",
"# Disable timeout on the underlying socket to prevent",
"# Read timed out(s) for long running processes",
"socket",
"=",
"self",
".",
"_get_raw_response_socket",
"(",
"response",
")",
"self",
... | A generator of multiplexed data blocks coming from a response
stream. | [
"A",
"generator",
"of",
"multiplexed",
"data",
"blocks",
"coming",
"from",
"a",
"response",
"stream",
"."
] | python | train | 35.35 |
biocore/burrito-fillings | bfillings/usearch.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/usearch.py#L934-L951 | def concatenate_fastas(output_fna_clustered,
output_fna_failures,
output_concat_filepath):
""" Concatenates two input fastas, writes to output_concat_filepath
output_fna_clustered: fasta of successful ref clusters
output_fna_failures: de novo fasta of cluster f... | [
"def",
"concatenate_fastas",
"(",
"output_fna_clustered",
",",
"output_fna_failures",
",",
"output_concat_filepath",
")",
":",
"output_fp",
"=",
"open",
"(",
"output_concat_filepath",
",",
"\"w\"",
")",
"for",
"label",
",",
"seq",
"in",
"parse_fasta",
"(",
"open",
... | Concatenates two input fastas, writes to output_concat_filepath
output_fna_clustered: fasta of successful ref clusters
output_fna_failures: de novo fasta of cluster failures
output_concat_filepath: path to write combined fastas to | [
"Concatenates",
"two",
"input",
"fastas",
"writes",
"to",
"output_concat_filepath"
] | python | train | 39.166667 |
tanghaibao/jcvi | jcvi/formats/fastq.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fastq.py#L318-L345 | def readlen(args):
"""
%prog readlen fastqfile
Calculate read length, will only try the first N reads. Output min, max, and
avg for each file.
"""
p = OptionParser(readlen.__doc__)
p.set_firstN()
p.add_option("--silent", default=False, action="store_true",
help="Do not ... | [
"def",
"readlen",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"readlen",
".",
"__doc__",
")",
"p",
".",
"set_firstN",
"(",
")",
"p",
".",
"add_option",
"(",
"\"--silent\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
"... | %prog readlen fastqfile
Calculate read length, will only try the first N reads. Output min, max, and
avg for each file. | [
"%prog",
"readlen",
"fastqfile"
] | python | train | 30.607143 |
noahbenson/neuropythy | neuropythy/freesurfer/core.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/freesurfer/core.py#L385-L432 | def subject(name, meta_data=None, check_path=True):
'''
subject(name) yields a freesurfer Subject object for the subject with the given name. Subjects
are cached and not reloaded, so multiple calls to subject(name) will yield the same immutable
subject object..
Note that subects returned by fre... | [
"def",
"subject",
"(",
"name",
",",
"meta_data",
"=",
"None",
",",
"check_path",
"=",
"True",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"expandvars",
"(",
"name",
")",
")",
"if",
"check_path",
"is",
"... | subject(name) yields a freesurfer Subject object for the subject with the given name. Subjects
are cached and not reloaded, so multiple calls to subject(name) will yield the same immutable
subject object..
Note that subects returned by freesurfer_subject() are always persistent Immutable objects; this
... | [
"subject",
"(",
"name",
")",
"yields",
"a",
"freesurfer",
"Subject",
"object",
"for",
"the",
"subject",
"with",
"the",
"given",
"name",
".",
"Subjects",
"are",
"cached",
"and",
"not",
"reloaded",
"so",
"multiple",
"calls",
"to",
"subject",
"(",
"name",
")"... | python | train | 55.354167 |
blue-yonder/turbodbc | python/turbodbc/cursor.py | https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/python/turbodbc/cursor.py#L249-L263 | def fetchmany(self, size=None):
"""
Fetches a batch of rows in the active result set generated with ``execute()`` or
``executemany()``.
:param size: Controls how many rows are returned. The default ``None`` means that
the value of Cursor.arraysize is used.
:return... | [
"def",
"fetchmany",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"self",
".",
"arraysize",
"if",
"(",
"size",
"<=",
"0",
")",
":",
"raise",
"InterfaceError",
"(",
"\"Invalid arraysize {} for fetchmany()\"",... | Fetches a batch of rows in the active result set generated with ``execute()`` or
``executemany()``.
:param size: Controls how many rows are returned. The default ``None`` means that
the value of Cursor.arraysize is used.
:return: A list of rows | [
"Fetches",
"a",
"batch",
"of",
"rows",
"in",
"the",
"active",
"result",
"set",
"generated",
"with",
"execute",
"()",
"or",
"executemany",
"()",
"."
] | python | train | 37 |
HazardDede/dictmentor | dictmentor/base.py | https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/base.py#L31-L45 | def bind(self, extension: Extension) -> 'DictMentor':
"""
Add any predefined or custom extension.
Args:
extension: Extension to add to the processor.
Returns:
The DictMentor itself for chaining.
"""
if not Extension.is_valid_extension(extension):... | [
"def",
"bind",
"(",
"self",
",",
"extension",
":",
"Extension",
")",
"->",
"'DictMentor'",
":",
"if",
"not",
"Extension",
".",
"is_valid_extension",
"(",
"extension",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot bind extension due to missing interface requirements\... | Add any predefined or custom extension.
Args:
extension: Extension to add to the processor.
Returns:
The DictMentor itself for chaining. | [
"Add",
"any",
"predefined",
"or",
"custom",
"extension",
"."
] | python | train | 30.8 |
openstack/horizon | openstack_dashboard/api/neutron.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1795-L1808 | def list_extensions(request):
"""List neutron extensions.
:param request: django request object
"""
neutron_api = neutronclient(request)
try:
extensions_list = neutron_api.list_extensions()
except exceptions.ServiceCatalogException:
return {}
if 'extensions' in extensions_li... | [
"def",
"list_extensions",
"(",
"request",
")",
":",
"neutron_api",
"=",
"neutronclient",
"(",
"request",
")",
"try",
":",
"extensions_list",
"=",
"neutron_api",
".",
"list_extensions",
"(",
")",
"except",
"exceptions",
".",
"ServiceCatalogException",
":",
"return"... | List neutron extensions.
:param request: django request object | [
"List",
"neutron",
"extensions",
"."
] | python | train | 27.857143 |
spacetelescope/stsci.tools | lib/stsci/tools/check_files.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/check_files.py#L166-L201 | def checkNGOODPIX(filelist):
"""
Only for ACS, WFC3 and STIS, check NGOODPIX
If all pixels are 'bad' on all chips, exclude this image
from further processing.
Similar checks requiring comparing 'driz_sep_bits' against
WFPC2 c1f.fits arrays and NICMOS DQ arrays will need to be
done separately... | [
"def",
"checkNGOODPIX",
"(",
"filelist",
")",
":",
"toclose",
"=",
"False",
"removed_files",
"=",
"[",
"]",
"supported_instruments",
"=",
"[",
"'ACS'",
",",
"'STIS'",
",",
"'WFC3'",
"]",
"for",
"inputfile",
"in",
"filelist",
":",
"if",
"isinstance",
"(",
"... | Only for ACS, WFC3 and STIS, check NGOODPIX
If all pixels are 'bad' on all chips, exclude this image
from further processing.
Similar checks requiring comparing 'driz_sep_bits' against
WFPC2 c1f.fits arrays and NICMOS DQ arrays will need to be
done separately (and later). | [
"Only",
"for",
"ACS",
"WFC3",
"and",
"STIS",
"check",
"NGOODPIX",
"If",
"all",
"pixels",
"are",
"bad",
"on",
"all",
"chips",
"exclude",
"this",
"image",
"from",
"further",
"processing",
".",
"Similar",
"checks",
"requiring",
"comparing",
"driz_sep_bits",
"agai... | python | train | 36.444444 |
senaite/senaite.core | bika/lims/content/analysisrequest.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/analysisrequest.py#L1423-L1426 | def Description(self):
"""Returns searchable data as Description"""
descr = " ".join((self.getId(), self.aq_parent.Title()))
return safe_unicode(descr).encode('utf-8') | [
"def",
"Description",
"(",
"self",
")",
":",
"descr",
"=",
"\" \"",
".",
"join",
"(",
"(",
"self",
".",
"getId",
"(",
")",
",",
"self",
".",
"aq_parent",
".",
"Title",
"(",
")",
")",
")",
"return",
"safe_unicode",
"(",
"descr",
")",
".",
"encode",
... | Returns searchable data as Description | [
"Returns",
"searchable",
"data",
"as",
"Description"
] | python | train | 47 |
arne-cl/discoursegraphs | src/discoursegraphs/discoursegraph.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/discoursegraph.py#L1081-L1108 | def select_neighbors_by_edge_attribute(docgraph, source,
attribute=None, value=None, data=False):
"""Get all neighbors with the given edge attribute value(s)."""
assert isinstance(docgraph, MultiGraph)
for neighbor_id in docgraph.neighbors_iter(source):
edges =... | [
"def",
"select_neighbors_by_edge_attribute",
"(",
"docgraph",
",",
"source",
",",
"attribute",
"=",
"None",
",",
"value",
"=",
"None",
",",
"data",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"docgraph",
",",
"MultiGraph",
")",
"for",
"neighbor_id",
... | Get all neighbors with the given edge attribute value(s). | [
"Get",
"all",
"neighbors",
"with",
"the",
"given",
"edge",
"attribute",
"value",
"(",
"s",
")",
"."
] | python | train | 40.714286 |
tanghaibao/jcvi | jcvi/utils/progressbar.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/progressbar.py#L592-L618 | def start(self):
'''Starts measuring time, and prints the bar at 0%.
It returns self so you can use it like this:
>>> pbar = ProgressBar().start()
>>> for i in range(100):
... # do something
... pbar.update(i+1)
...
>>> pbar.finish()
'''
... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"maxval",
"is",
"None",
":",
"self",
".",
"maxval",
"=",
"self",
".",
"_DEFAULT_MAXVAL",
"self",
".",
"num_intervals",
"=",
"max",
"(",
"100",
",",
"self",
".",
"term_width",
")",
"self",
".",... | Starts measuring time, and prints the bar at 0%.
It returns self so you can use it like this:
>>> pbar = ProgressBar().start()
>>> for i in range(100):
... # do something
... pbar.update(i+1)
...
>>> pbar.finish() | [
"Starts",
"measuring",
"time",
"and",
"prints",
"the",
"bar",
"at",
"0%",
"."
] | python | train | 27.703704 |
cltrudeau/django-flowr | flowr/models.py | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L238-L252 | def ancestors_root(self):
"""Returns a list of the ancestors of this node but does not pass the
root node, even if the root has parents due to cycles."""
if self.is_root():
return []
ancestors = set([])
self._depth_ascend(self, ancestors, True)
try:
... | [
"def",
"ancestors_root",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_root",
"(",
")",
":",
"return",
"[",
"]",
"ancestors",
"=",
"set",
"(",
"[",
"]",
")",
"self",
".",
"_depth_ascend",
"(",
"self",
",",
"ancestors",
",",
"True",
")",
"try",
":",... | Returns a list of the ancestors of this node but does not pass the
root node, even if the root has parents due to cycles. | [
"Returns",
"a",
"list",
"of",
"the",
"ancestors",
"of",
"this",
"node",
"but",
"does",
"not",
"pass",
"the",
"root",
"node",
"even",
"if",
"the",
"root",
"has",
"parents",
"due",
"to",
"cycles",
"."
] | python | valid | 30.733333 |
gem/oq-engine | openquake/hmtk/plotting/seismicity/catalogue_plots.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L84-L100 | def _save_image(fig, filename, filetype='png', resolution=300):
"""
If filename is specified, saves the image
:param str filename:
Name of the file
:param str filetype:
Type of file
:param int resolution:
DPI resolution of the output figure
"""
if filename:
fi... | [
"def",
"_save_image",
"(",
"fig",
",",
"filename",
",",
"filetype",
"=",
"'png'",
",",
"resolution",
"=",
"300",
")",
":",
"if",
"filename",
":",
"filename",
",",
"filetype",
",",
"resolution",
"=",
"build_filename",
"(",
"filename",
",",
"filetype",
",",
... | If filename is specified, saves the image
:param str filename:
Name of the file
:param str filetype:
Type of file
:param int resolution:
DPI resolution of the output figure | [
"If",
"filename",
"is",
"specified",
"saves",
"the",
"image",
":",
"param",
"str",
"filename",
":",
"Name",
"of",
"the",
"file",
":",
"param",
"str",
"filetype",
":",
"Type",
"of",
"file",
":",
"param",
"int",
"resolution",
":",
"DPI",
"resolution",
"of"... | python | train | 34.058824 |
SandstoneHPC/sandstone-ide | sandstone/lib/filesystem/handlers.py | https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L221-L245 | def get(self, filepath):
"""
Get directory details for the specified file. If contents is
set to True (default) then the directory contents will be sent
along with the directory details. If dir_size is set to True
(default=False) then du -hs will be run against subdirectories
... | [
"def",
"get",
"(",
"self",
",",
"filepath",
")",
":",
"contents",
"=",
"self",
".",
"get_argument",
"(",
"'contents'",
",",
"False",
")",
"if",
"contents",
"==",
"u'true'",
":",
"contents",
"=",
"True",
"else",
":",
"contents",
"=",
"False",
"dir_sizes",... | Get directory details for the specified file. If contents is
set to True (default) then the directory contents will be sent
along with the directory details. If dir_size is set to True
(default=False) then du -hs will be run against subdirectories
for accurate content sizes. | [
"Get",
"directory",
"details",
"for",
"the",
"specified",
"file",
".",
"If",
"contents",
"is",
"set",
"to",
"True",
"(",
"default",
")",
"then",
"the",
"directory",
"contents",
"will",
"be",
"sent",
"along",
"with",
"the",
"directory",
"details",
".",
"If"... | python | train | 36.08 |
pyapi-gitlab/pyapi-gitlab | gitlab/users.py | https://github.com/pyapi-gitlab/pyapi-gitlab/blob/f74b6fb5c13cecae9524997847e928905cc60acf/gitlab/users.py#L223-L237 | def deletesshkey(self, key_id):
"""
Deletes an sshkey for the current user identified by id
:param key_id: the id of the key
:return: False if it didn't delete it, True if it was deleted
"""
request = requests.delete(
'{0}/{1}'.format(self.keys_url, key_id), ... | [
"def",
"deletesshkey",
"(",
"self",
",",
"key_id",
")",
":",
"request",
"=",
"requests",
".",
"delete",
"(",
"'{0}/{1}'",
".",
"format",
"(",
"self",
".",
"keys_url",
",",
"key_id",
")",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"verify",
"=",
... | Deletes an sshkey for the current user identified by id
:param key_id: the id of the key
:return: False if it didn't delete it, True if it was deleted | [
"Deletes",
"an",
"sshkey",
"for",
"the",
"current",
"user",
"identified",
"by",
"id"
] | python | train | 33.6 |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L11060-L11077 | def sctiks(sc, clkstr):
"""
Convert a spacecraft clock format string to number of "ticks".
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sctiks_c.html
:param sc: NAIF spacecraft identification code.
:type sc: int
:param clkstr: Character representation of a spacecraft clock.
:typ... | [
"def",
"sctiks",
"(",
"sc",
",",
"clkstr",
")",
":",
"sc",
"=",
"ctypes",
".",
"c_int",
"(",
"sc",
")",
"clkstr",
"=",
"stypes",
".",
"stringToCharP",
"(",
"clkstr",
")",
"ticks",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"libspice",
".",
"sctiks_c",... | Convert a spacecraft clock format string to number of "ticks".
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sctiks_c.html
:param sc: NAIF spacecraft identification code.
:type sc: int
:param clkstr: Character representation of a spacecraft clock.
:type clkstr: str
:return: Number of... | [
"Convert",
"a",
"spacecraft",
"clock",
"format",
"string",
"to",
"number",
"of",
"ticks",
"."
] | python | train | 32.222222 |
Ezhil-Language-Foundation/open-tamil | tamil/txt2unicode/unicode2encode.py | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/txt2unicode/unicode2encode.py#L47-L65 | def unicode2encode(text, charmap):
'''
charmap : dictionary which has both encode as key, unicode as value
'''
if isinstance(text, (list, tuple)):
unitxt = ''
for line in text:
for val,key in charmap.items():
if key in line:
line =... | [
"def",
"unicode2encode",
"(",
"text",
",",
"charmap",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"unitxt",
"=",
"''",
"for",
"line",
"in",
"text",
":",
"for",
"val",
",",
"key",
"in",
"charmap",
".",
... | charmap : dictionary which has both encode as key, unicode as value | [
"charmap",
":",
"dictionary",
"which",
"has",
"both",
"encode",
"as",
"key",
"unicode",
"as",
"value"
] | python | train | 32.894737 |
cmbruns/pyopenvr | src/openvr/glframework/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/glframework/__init__.py#L26-L41 | def shader_substring(body, stack_frame=1):
"""
Call this method from a function that defines a literal shader string as the "body" argument.
Dresses up a shader string in two ways:
1) Insert #line number declaration
2) un-indents
The line number information can help debug glsl comp... | [
"def",
"shader_substring",
"(",
"body",
",",
"stack_frame",
"=",
"1",
")",
":",
"line_count",
"=",
"len",
"(",
"body",
".",
"splitlines",
"(",
"True",
")",
")",
"line_number",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"stack_frame",
"]",
"[",
"2",
... | Call this method from a function that defines a literal shader string as the "body" argument.
Dresses up a shader string in two ways:
1) Insert #line number declaration
2) un-indents
The line number information can help debug glsl compile errors.
The unindenting allows you to type the s... | [
"Call",
"this",
"method",
"from",
"a",
"function",
"that",
"defines",
"a",
"literal",
"shader",
"string",
"as",
"the",
"body",
"argument",
".",
"Dresses",
"up",
"a",
"shader",
"string",
"in",
"two",
"ways",
":",
"1",
")",
"Insert",
"#line",
"number",
"de... | python | train | 42.6875 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L522-L541 | def wait_while_reachable(self, servers, timeout=60):
"""wait while all servers be reachable
Args:
servers - list of servers
"""
t_start = time.time()
while True:
try:
for server in servers:
# TODO: use state code to chec... | [
"def",
"wait_while_reachable",
"(",
"self",
",",
"servers",
",",
"timeout",
"=",
"60",
")",
":",
"t_start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"try",
":",
"for",
"server",
"in",
"servers",
":",
"# TODO: use state code to check if serve... | wait while all servers be reachable
Args:
servers - list of servers | [
"wait",
"while",
"all",
"servers",
"be",
"reachable",
"Args",
":",
"servers",
"-",
"list",
"of",
"servers"
] | python | train | 48.2 |
HiPERCAM/hcam_widgets | hcam_widgets/widgets.py | https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L697-L719 | def set_bind(self):
"""
Sets key bindings -- we need this more than once
"""
IntegerEntry.set_bind(self)
self.unbind('<Shift-Up>')
self.unbind('<Shift-Down>')
self.unbind('<Control-Up>')
self.unbind('<Control-Down>')
self.unbind('<Double-Button-1>'... | [
"def",
"set_bind",
"(",
"self",
")",
":",
"IntegerEntry",
".",
"set_bind",
"(",
"self",
")",
"self",
".",
"unbind",
"(",
"'<Shift-Up>'",
")",
"self",
".",
"unbind",
"(",
"'<Shift-Down>'",
")",
"self",
".",
"unbind",
"(",
"'<Control-Up>'",
")",
"self",
".... | Sets key bindings -- we need this more than once | [
"Sets",
"key",
"bindings",
"--",
"we",
"need",
"this",
"more",
"than",
"once"
] | python | train | 38.652174 |
helixyte/everest | everest/representers/base.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L155-L164 | def data_to_bytes(self, data_element, encoding=None):
"""
Converts the given data element into a string representation using
the :method:`data_to_string` method and encodes the resulting
text with the given encoding.
"""
if encoding is None:
encoding = self.en... | [
"def",
"data_to_bytes",
"(",
"self",
",",
"data_element",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"self",
".",
"encoding",
"text",
"=",
"self",
".",
"data_to_string",
"(",
"data_element",
")",
"return",... | Converts the given data element into a string representation using
the :method:`data_to_string` method and encodes the resulting
text with the given encoding. | [
"Converts",
"the",
"given",
"data",
"element",
"into",
"a",
"string",
"representation",
"using",
"the",
":",
"method",
":",
"data_to_string",
"method",
"and",
"encodes",
"the",
"resulting",
"text",
"with",
"the",
"given",
"encoding",
"."
] | python | train | 41.3 |
FujiMakoto/AgentML | agentml/__init__.py | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/__init__.py#L470-L489 | def set_tag(self, name, tag_class):
"""
Define a new tag parser method
:param name: The name of the tag
:type name: str
:param tag_class: The Tag class, this must be a subclass of base parser.tags.Tag
:type tag_class: Tag
"""
# Has this tag already been... | [
"def",
"set_tag",
"(",
"self",
",",
"name",
",",
"tag_class",
")",
":",
"# Has this tag already been defined?",
"if",
"name",
"in",
"self",
".",
"_tags",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"'Overwriting an existing Tag class: {tag}'",
".",
"format",
"("... | Define a new tag parser method
:param name: The name of the tag
:type name: str
:param tag_class: The Tag class, this must be a subclass of base parser.tags.Tag
:type tag_class: Tag | [
"Define",
"a",
"new",
"tag",
"parser",
"method",
":",
"param",
"name",
":",
"The",
"name",
"of",
"the",
"tag",
":",
"type",
"name",
":",
"str"
] | python | train | 40.85 |
pavelsof/ipalint | ipalint/read.py | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L289-L306 | def gen_ipa_data(self):
"""
Generator for iterating over the IPA strings found in the dataset file.
Yields the IPA data string paired with the respective line number.
"""
dialect = self.get_dialect()
f = self._open()
try:
if dialect:
for res in self._gen_csv_data(f, dialect):
yield res
els... | [
"def",
"gen_ipa_data",
"(",
"self",
")",
":",
"dialect",
"=",
"self",
".",
"get_dialect",
"(",
")",
"f",
"=",
"self",
".",
"_open",
"(",
")",
"try",
":",
"if",
"dialect",
":",
"for",
"res",
"in",
"self",
".",
"_gen_csv_data",
"(",
"f",
",",
"dialec... | Generator for iterating over the IPA strings found in the dataset file.
Yields the IPA data string paired with the respective line number. | [
"Generator",
"for",
"iterating",
"over",
"the",
"IPA",
"strings",
"found",
"in",
"the",
"dataset",
"file",
".",
"Yields",
"the",
"IPA",
"data",
"string",
"paired",
"with",
"the",
"respective",
"line",
"number",
"."
] | python | train | 21.277778 |
RedisJSON/rejson-py | rejson/client.py | https://github.com/RedisJSON/rejson-py/blob/55f0adf3adc40f5a769e28e541dbbf5377b90ec6/rejson/client.py#L243-L248 | def jsonobjlen(self, name, path=Path.rootPath()):
"""
Returns the length of the dictionary JSON value under ``path`` at key
``name``
"""
return self.execute_command('JSON.OBJLEN', name, str_path(path)) | [
"def",
"jsonobjlen",
"(",
"self",
",",
"name",
",",
"path",
"=",
"Path",
".",
"rootPath",
"(",
")",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'JSON.OBJLEN'",
",",
"name",
",",
"str_path",
"(",
"path",
")",
")"
] | Returns the length of the dictionary JSON value under ``path`` at key
``name`` | [
"Returns",
"the",
"length",
"of",
"the",
"dictionary",
"JSON",
"value",
"under",
"path",
"at",
"key",
"name"
] | python | train | 39.333333 |
bitshares/python-bitshares | bitshares/bitshares.py | https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L391-L456 | def allow(
self,
foreign,
weight=None,
permission="active",
account=None,
threshold=None,
**kwargs
):
""" Give additional access to an account by some other public
key or account.
:param str foreign: The foreign account that wi... | [
"def",
"allow",
"(",
"self",
",",
"foreign",
",",
"weight",
"=",
"None",
",",
"permission",
"=",
"\"active\"",
",",
"account",
"=",
"None",
",",
"threshold",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"if",
... | Give additional access to an account by some other public
key or account.
:param str foreign: The foreign account that will obtain access
:param int weight: (optional) The weight to use. If not
define, the threshold will be used. If the weight is
smal... | [
"Give",
"additional",
"access",
"to",
"an",
"account",
"by",
"some",
"other",
"public",
"key",
"or",
"account",
"."
] | python | train | 38.909091 |
PyCQA/astroid | astroid/inference.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L824-L833 | def infer_assign(self, context=None):
"""infer a AssignName/AssignAttr: need to inspect the RHS part of the
assign node
"""
stmt = self.statement()
if isinstance(stmt, nodes.AugAssign):
return stmt.infer(context)
stmts = list(self.assigned_stmts(context=context))
return bases._infer... | [
"def",
"infer_assign",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"stmt",
"=",
"self",
".",
"statement",
"(",
")",
"if",
"isinstance",
"(",
"stmt",
",",
"nodes",
".",
"AugAssign",
")",
":",
"return",
"stmt",
".",
"infer",
"(",
"context",
")"... | infer a AssignName/AssignAttr: need to inspect the RHS part of the
assign node | [
"infer",
"a",
"AssignName",
"/",
"AssignAttr",
":",
"need",
"to",
"inspect",
"the",
"RHS",
"part",
"of",
"the",
"assign",
"node"
] | python | train | 33.3 |
almarklein/pyelastix | pyelastix.py | https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L76-L140 | def _find_executables(name):
""" Try to find an executable.
"""
exe_name = name + '.exe' * sys.platform.startswith('win')
env_path = os.environ.get(name.upper()+ '_PATH', '')
possible_locations = []
def add(*dirs):
for d in dirs:
if d and d not in possible_locations and ... | [
"def",
"_find_executables",
"(",
"name",
")",
":",
"exe_name",
"=",
"name",
"+",
"'.exe'",
"*",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
"env_path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
".",
"upper",
"(",
")",
"+",... | Try to find an executable. | [
"Try",
"to",
"find",
"an",
"executable",
"."
] | python | train | 32.184615 |
gwastro/pycbc | pycbc/distributions/__init__.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/__init__.py#L155-L197 | def read_constraints_from_config(cp, transforms=None,
constraint_section='constraint'):
"""Loads parameter constraints from a configuration file.
Parameters
----------
cp : WorkflowConfigParser
An open config parser to read from.
transforms : list, optional
... | [
"def",
"read_constraints_from_config",
"(",
"cp",
",",
"transforms",
"=",
"None",
",",
"constraint_section",
"=",
"'constraint'",
")",
":",
"cons",
"=",
"[",
"]",
"for",
"subsection",
"in",
"cp",
".",
"get_subsections",
"(",
"constraint_section",
")",
":",
"na... | Loads parameter constraints from a configuration file.
Parameters
----------
cp : WorkflowConfigParser
An open config parser to read from.
transforms : list, optional
List of transforms to apply to parameters before applying constraints.
constraint_section : str, optional
Th... | [
"Loads",
"parameter",
"constraints",
"from",
"a",
"configuration",
"file",
"."
] | python | train | 37.767442 |
cytoscape/py2cytoscape | py2cytoscape/cyrest/cyndex2.py | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/cyndex2.py#L69-L82 | def getAppInfo(self, verbose=None):
"""
App version and other basic information will be provided.
:param verbose: print more
:returns: 200: successful operation
"""
surl=self.___url
sv=surl.split('/')[-1]
surl=surl.rstrip(sv+'/')
response=api(ur... | [
"def",
"getAppInfo",
"(",
"self",
",",
"verbose",
"=",
"None",
")",
":",
"surl",
"=",
"self",
".",
"___url",
"sv",
"=",
"surl",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"surl",
"=",
"surl",
".",
"rstrip",
"(",
"sv",
"+",
"'/'",
")",
... | App version and other basic information will be provided.
:param verbose: print more
:returns: 200: successful operation | [
"App",
"version",
"and",
"other",
"basic",
"information",
"will",
"be",
"provided",
"."
] | python | train | 28.785714 |
wbond/oscrypto | oscrypto/__init__.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/__init__.py#L81-L139 | def use_openssl(libcrypto_path, libssl_path, trust_list_path=None):
"""
Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll),
or using a specific dynamic library on Linux/BSD (.so).
This can also be used to configure oscrypto to use LibreSSL dynamic
libraries.
This method ... | [
"def",
"use_openssl",
"(",
"libcrypto_path",
",",
"libssl_path",
",",
"trust_list_path",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"libcrypto_path",
",",
"str_cls",
")",
":",
"raise",
"ValueError",
"(",
"'libcrypto_path must be a unicode string, not %s'",... | Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll),
or using a specific dynamic library on Linux/BSD (.so).
This can also be used to configure oscrypto to use LibreSSL dynamic
libraries.
This method must be called before any oscrypto submodules are imported.
:param libcrypt... | [
"Forces",
"using",
"OpenSSL",
"dynamic",
"libraries",
"on",
"OS",
"X",
"(",
".",
"dylib",
")",
"or",
"Windows",
"(",
".",
"dll",
")",
"or",
"using",
"a",
"specific",
"dynamic",
"library",
"on",
"Linux",
"/",
"BSD",
"(",
".",
"so",
")",
"."
] | python | valid | 43.491525 |
ratcave/ratcave | ratcave/camera.py | https://github.com/ratcave/ratcave/blob/e3862cdaba100ac2c6c78c08c4b09638e0c88fd4/ratcave/camera.py#L224-L229 | def _get_shift_matrix(self):
"""np.array: The Camera's lens-shift matrix."""
return np.array([[1., 0., self.x_shift, 0.],
[0., 1., self.y_shift, 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]], dtype=np.float32) | [
"def",
"_get_shift_matrix",
"(",
"self",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"1.",
",",
"0.",
",",
"self",
".",
"x_shift",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"1.",
",",
"self",
".",
"y_shift",
",",
"0.",
"]",
",",
"[",
"0... | np.array: The Camera's lens-shift matrix. | [
"np",
".",
"array",
":",
"The",
"Camera",
"s",
"lens",
"-",
"shift",
"matrix",
"."
] | python | train | 51.666667 |
projectshift/shift-schema | shiftschema/filters/bleach.py | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/filters/bleach.py#L86-L97 | def filter(self, value, model=None, context=None):
"""
Filter
Performs value filtering and returns filtered result.
:param value: input value
:param model: parent model being validated
:param context: object, filtering context
... | [
"def",
"filter",
"(",
"self",
",",
"value",
",",
"model",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"return",
"bleach",
".",
"clean",
"(",
"text",
"=",
"value",
",",
"*",
"*",
"self",
".",
"bleach... | Filter
Performs value filtering and returns filtered result.
:param value: input value
:param model: parent model being validated
:param context: object, filtering context
:return: filtered value | [
"Filter",
"Performs",
"value",
"filtering",
"and",
"returns",
"filtered",
"result",
"."
] | python | train | 37.666667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.