repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1811-L1870 | def order_target_percent(self, asset, target,
limit_price=None, stop_price=None, style=None):
"""Place an order to adjust a position to a target percent of the
current portfolio value. If the position doesn't already exist, this is
equivalent to placing a new order. ... | [
"def",
"order_target_percent",
"(",
"self",
",",
"asset",
",",
"target",
",",
"limit_price",
"=",
"None",
",",
"stop_price",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_can_order_asset",
"(",
"asset",
")",
":",
"return",... | Place an order to adjust a position to a target percent of the
current portfolio value. If the position doesn't already exist, this is
equivalent to placing a new order. If the position does exist, this is
equivalent to placing an order for the difference between the target
percent and t... | [
"Place",
"an",
"order",
"to",
"adjust",
"a",
"position",
"to",
"a",
"target",
"percent",
"of",
"the",
"current",
"portfolio",
"value",
".",
"If",
"the",
"position",
"doesn",
"t",
"already",
"exist",
"this",
"is",
"equivalent",
"to",
"placing",
"a",
"new",
... | python | train |
alantygel/ckanext-semantictags | ckanext/semantictags/db.py | https://github.com/alantygel/ckanext-semantictags/blob/10bb31d29f34b2b5a6feae693961842f93007ce1/ckanext/semantictags/db.py#L99-L117 | def get(cls, tag_id_or_URI, label=None):
'''Return the tag with the given id or URI, or None.
:param tag_id_or_name: the id or name of the tag to return
:type tag_id_or_name: string
:returns: the tag object with the given id or name, or None if there is
no tag with that id or name
:rtype: ckan.model.tag.... | [
"def",
"get",
"(",
"cls",
",",
"tag_id_or_URI",
",",
"label",
"=",
"None",
")",
":",
"# First try to get the tag by ID.",
"semantictag",
"=",
"SemanticTag",
".",
"by_id",
"(",
"tag_id_or_URI",
")",
"if",
"semantictag",
":",
"return",
"semantictag",
"else",
":",
... | Return the tag with the given id or URI, or None.
:param tag_id_or_name: the id or name of the tag to return
:type tag_id_or_name: string
:returns: the tag object with the given id or name, or None if there is
no tag with that id or name
:rtype: ckan.model.tag.Tag | [
"Return",
"the",
"tag",
"with",
"the",
"given",
"id",
"or",
"URI",
"or",
"None",
"."
] | python | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/__notebook_support__.py | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/__notebook_support__.py#L796-L877 | def plot_median_freq_evol(time_signal, signal, time_median_freq, median_freq, activations_begin,
activations_end, sample_rate, file_name=None):
"""
-----
Brief
-----
Graphical representation of the EMG median power frequency evolution time series.
-----------
Descr... | [
"def",
"plot_median_freq_evol",
"(",
"time_signal",
",",
"signal",
",",
"time_median_freq",
",",
"median_freq",
",",
"activations_begin",
",",
"activations_end",
",",
"sample_rate",
",",
"file_name",
"=",
"None",
")",
":",
"# Generation of the HTML file where the plot wil... | -----
Brief
-----
Graphical representation of the EMG median power frequency evolution time series.
-----------
Description
-----------
Function intended to generate a Bokeh figure with 2x1 format, where each muscular activation
period is identified through a colored box and the plot th... | [
"-----",
"Brief",
"-----",
"Graphical",
"representation",
"of",
"the",
"EMG",
"median",
"power",
"frequency",
"evolution",
"time",
"series",
"."
] | python | train |
tanghaibao/jcvi | jcvi/formats/posmap.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/posmap.py#L155-L180 | def index(args):
"""
%prog index frgscf.sorted
Compress frgscffile.sorted and index it using `tabix`.
"""
p = OptionParser(index.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
frgscffile, = args
gzfile = frgscffile + ".gz"
cmd = "... | [
"def",
"index",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"index",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"p",... | %prog index frgscf.sorted
Compress frgscffile.sorted and index it using `tabix`. | [
"%prog",
"index",
"frgscf",
".",
"sorted"
] | python | train |
galaxy-genome-annotation/python-apollo | apollo/client.py | https://github.com/galaxy-genome-annotation/python-apollo/blob/2bc9991302abe4402ec2885dcaac35915475b387/apollo/client.py#L29-L65 | def post(self, client_method, data, post_params=None, is_json=True):
"""Make a POST request"""
url = self._wa.apollo_url + self.CLIENT_BASE + client_method
if post_params is None:
post_params = {}
headers = {
'Content-Type': 'application/json'
}
... | [
"def",
"post",
"(",
"self",
",",
"client_method",
",",
"data",
",",
"post_params",
"=",
"None",
",",
"is_json",
"=",
"True",
")",
":",
"url",
"=",
"self",
".",
"_wa",
".",
"apollo_url",
"+",
"self",
".",
"CLIENT_BASE",
"+",
"client_method",
"if",
"post... | Make a POST request | [
"Make",
"a",
"POST",
"request"
] | python | train |
72squared/redpipe | redpipe/keyspaces.py | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L629-L638 | def getbit(self, name, offset):
"""
Returns a boolean indicating the value of ``offset`` in key
:param name: str the name of the redis key
:param offset: int
:return: Future()
"""
with self.pipe as pipe:
return pipe.getbit(self.redis_key(name), of... | [
"def",
"getbit",
"(",
"self",
",",
"name",
",",
"offset",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"getbit",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"offset",
")"
] | Returns a boolean indicating the value of ``offset`` in key
:param name: str the name of the redis key
:param offset: int
:return: Future() | [
"Returns",
"a",
"boolean",
"indicating",
"the",
"value",
"of",
"offset",
"in",
"key"
] | python | train |
saltstack/salt | salt/utils/decorators/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/state.py#L75-L95 | def unify(self, result):
'''
While comments as a list are allowed,
comments needs to be strings for backward compatibility.
See such claim here: https://github.com/saltstack/salt/pull/43070
Rules applied:
- 'comment' is joined into a multi-line string, in case the valu... | [
"def",
"unify",
"(",
"self",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
".",
"get",
"(",
"'comment'",
")",
",",
"list",
")",
":",
"result",
"[",
"'comment'",
"]",
"=",
"u'\\n'",
".",
"join",
"(",
"[",
"salt",
".",
"utils",
".",
"... | While comments as a list are allowed,
comments needs to be strings for backward compatibility.
See such claim here: https://github.com/saltstack/salt/pull/43070
Rules applied:
- 'comment' is joined into a multi-line string, in case the value is a list.
- 'result' should be a... | [
"While",
"comments",
"as",
"a",
"list",
"are",
"allowed",
"comments",
"needs",
"to",
"be",
"strings",
"for",
"backward",
"compatibility",
".",
"See",
"such",
"claim",
"here",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"saltstack",
"/",
"salt",
"... | python | train |
keon/algorithms | algorithms/strings/decode_string.py | https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/decode_string.py#L20-L38 | def decode_string(s):
"""
:type s: str
:rtype: str
"""
stack = []; cur_num = 0; cur_string = ''
for c in s:
if c == '[':
stack.append((cur_string, cur_num))
cur_string = ''
cur_num = 0
elif c == ']':
prev_string, num = stack.pop()
... | [
"def",
"decode_string",
"(",
"s",
")",
":",
"stack",
"=",
"[",
"]",
"cur_num",
"=",
"0",
"cur_string",
"=",
"''",
"for",
"c",
"in",
"s",
":",
"if",
"c",
"==",
"'['",
":",
"stack",
".",
"append",
"(",
"(",
"cur_string",
",",
"cur_num",
")",
")",
... | :type s: str
:rtype: str | [
":",
"type",
"s",
":",
"str",
":",
"rtype",
":",
"str"
] | python | train |
TeamHG-Memex/eli5 | eli5/sklearn/utils.py | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/utils.py#L196-L213 | def get_num_features(estimator):
""" Return size of a feature vector estimator expects as an input. """
if hasattr(estimator, 'coef_'): # linear models
if len(estimator.coef_.shape) == 0:
return 1
return estimator.coef_.shape[-1]
elif hasattr(estimator, 'feature_importances_'): ... | [
"def",
"get_num_features",
"(",
"estimator",
")",
":",
"if",
"hasattr",
"(",
"estimator",
",",
"'coef_'",
")",
":",
"# linear models",
"if",
"len",
"(",
"estimator",
".",
"coef_",
".",
"shape",
")",
"==",
"0",
":",
"return",
"1",
"return",
"estimator",
"... | Return size of a feature vector estimator expects as an input. | [
"Return",
"size",
"of",
"a",
"feature",
"vector",
"estimator",
"expects",
"as",
"an",
"input",
"."
] | python | train |
qacafe/cdrouter.py | cdrouter/system.py | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/system.py#L425-L433 | def space(self):
"""Get system disk space usage.
:return: :class:`system.Space <system.Space>` object
:rtype: system.Space
"""
schema = SpaceSchema()
resp = self.service.get(self.base+'space/')
return self.service.decode(schema, resp) | [
"def",
"space",
"(",
"self",
")",
":",
"schema",
"=",
"SpaceSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"get",
"(",
"self",
".",
"base",
"+",
"'space/'",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"re... | Get system disk space usage.
:return: :class:`system.Space <system.Space>` object
:rtype: system.Space | [
"Get",
"system",
"disk",
"space",
"usage",
"."
] | python | train |
cggh/scikit-allel | allel/model/ndarray.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/model/ndarray.py#L3429-L3470 | def locate_key(self, key):
"""Get index location for the requested key.
Parameters
----------
key : object
Value to locate.
Returns
-------
loc : int or slice
Location of `key` (will be slice if there are duplicate entries).
Exam... | [
"def",
"locate_key",
"(",
"self",
",",
"key",
")",
":",
"left",
"=",
"bisect",
".",
"bisect_left",
"(",
"self",
",",
"key",
")",
"right",
"=",
"bisect",
".",
"bisect_right",
"(",
"self",
",",
"key",
")",
"diff",
"=",
"right",
"-",
"left",
"if",
"di... | Get index location for the requested key.
Parameters
----------
key : object
Value to locate.
Returns
-------
loc : int or slice
Location of `key` (will be slice if there are duplicate entries).
Examples
--------
>>> imp... | [
"Get",
"index",
"location",
"for",
"the",
"requested",
"key",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/transpiler/passes/mapping/dense_layout.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/dense_layout.py#L45-L66 | def run(self, dag):
"""
Pick a convenient layout depending on the best matching
qubit connectivity, and set the property `layout`.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than self.coupling_map
"""
... | [
"def",
"run",
"(",
"self",
",",
"dag",
")",
":",
"num_dag_qubits",
"=",
"sum",
"(",
"[",
"qreg",
".",
"size",
"for",
"qreg",
"in",
"dag",
".",
"qregs",
".",
"values",
"(",
")",
"]",
")",
"if",
"num_dag_qubits",
">",
"self",
".",
"coupling_map",
"."... | Pick a convenient layout depending on the best matching
qubit connectivity, and set the property `layout`.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than self.coupling_map | [
"Pick",
"a",
"convenient",
"layout",
"depending",
"on",
"the",
"best",
"matching",
"qubit",
"connectivity",
"and",
"set",
"the",
"property",
"layout",
"."
] | python | test |
chrisrink10/basilisp | src/basilisp/lang/runtime.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/runtime.py#L567-L570 | def get(cls, name: sym.Symbol) -> "Optional[Namespace]":
"""Get the namespace bound to the symbol `name` in the global namespace
cache. Return the namespace if it exists or None otherwise.."""
return cls._NAMESPACES.deref().entry(name, None) | [
"def",
"get",
"(",
"cls",
",",
"name",
":",
"sym",
".",
"Symbol",
")",
"->",
"\"Optional[Namespace]\"",
":",
"return",
"cls",
".",
"_NAMESPACES",
".",
"deref",
"(",
")",
".",
"entry",
"(",
"name",
",",
"None",
")"
] | Get the namespace bound to the symbol `name` in the global namespace
cache. Return the namespace if it exists or None otherwise.. | [
"Get",
"the",
"namespace",
"bound",
"to",
"the",
"symbol",
"name",
"in",
"the",
"global",
"namespace",
"cache",
".",
"Return",
"the",
"namespace",
"if",
"it",
"exists",
"or",
"None",
"otherwise",
".."
] | python | test |
ttm/participationLegacy | participation/triplification/participaTriplification.py | https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L157-L170 | def triplifyOverallStructures(self):
"""Insert into RDF graph the textual and network structures.
Ideally, one should be able to make bag of words related to
each item (communities, users, posts, comments, tags, etc).
Interaction and friendship networks should be made.
Human net... | [
"def",
"triplifyOverallStructures",
"(",
"self",
")",
":",
"if",
"self",
".",
"compute_networks",
":",
"self",
".",
"computeNetworks",
"(",
")",
"if",
"self",
".",
"compute_bows",
":",
"self",
".",
"computeBows",
"(",
")"
] | Insert into RDF graph the textual and network structures.
Ideally, one should be able to make bag of words related to
each item (communities, users, posts, comments, tags, etc).
Interaction and friendship networks should be made.
Human networks mediated by co-ocurrance (time os posts,
... | [
"Insert",
"into",
"RDF",
"graph",
"the",
"textual",
"and",
"network",
"structures",
"."
] | python | train |
idlesign/django-sitecats | sitecats/utils.py | https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L57-L85 | def _cache_init(self):
"""Initializes local cache from Django cache if required."""
cache_ = cache.get(self.CACHE_ENTRY_NAME)
if cache_ is None:
categories = get_category_model().objects.order_by('sort_order')
ids = {category.id: category for category in categories}
... | [
"def",
"_cache_init",
"(",
"self",
")",
":",
"cache_",
"=",
"cache",
".",
"get",
"(",
"self",
".",
"CACHE_ENTRY_NAME",
")",
"if",
"cache_",
"is",
"None",
":",
"categories",
"=",
"get_category_model",
"(",
")",
".",
"objects",
".",
"order_by",
"(",
"'sort... | Initializes local cache from Django cache if required. | [
"Initializes",
"local",
"cache",
"from",
"Django",
"cache",
"if",
"required",
"."
] | python | train |
waqasbhatti/astrobase | astrobase/checkplot/pkl_io.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/pkl_io.py#L130-L179 | def _read_checkplot_picklefile(checkplotpickle):
'''This reads a checkplot gzipped pickle file back into a dict.
NOTE: the try-except is for Python 2 pickles that have numpy arrays in
them. Apparently, these aren't compatible with Python 3. See here:
http://stackoverflow.com/q/11305790
The workar... | [
"def",
"_read_checkplot_picklefile",
"(",
"checkplotpickle",
")",
":",
"if",
"checkplotpickle",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"try",
":",
"with",
"gzip",
".",
"open",
"(",
"checkplotpickle",
",",
"'rb'",
")",
"as",
"infd",
":",
"cpdict",
"=",
"p... | This reads a checkplot gzipped pickle file back into a dict.
NOTE: the try-except is for Python 2 pickles that have numpy arrays in
them. Apparently, these aren't compatible with Python 3. See here:
http://stackoverflow.com/q/11305790
The workaround is noted in this answer:
http://stackoverflow.... | [
"This",
"reads",
"a",
"checkplot",
"gzipped",
"pickle",
"file",
"back",
"into",
"a",
"dict",
"."
] | python | valid |
acutesoftware/AIKIF | aikif/toolbox/cls_grid.py | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/cls_grid.py#L52-L58 | def save(self, fname):
""" saves a grid to file as ASCII text """
try:
with open(fname, "w") as f:
f.write(str(self))
except Exception as ex:
print('ERROR = cant save grid results to ' + fname + str(ex)) | [
"def",
"save",
"(",
"self",
",",
"fname",
")",
":",
"try",
":",
"with",
"open",
"(",
"fname",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"self",
")",
")",
"except",
"Exception",
"as",
"ex",
":",
"print",
"(",
"'ERROR... | saves a grid to file as ASCII text | [
"saves",
"a",
"grid",
"to",
"file",
"as",
"ASCII",
"text"
] | python | train |
craffel/mir_eval | mir_eval/segment.py | https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/segment.py#L663-L701 | def _mutual_info_score(reference_indices, estimated_indices, contingency=None):
"""Compute the mutual information between two sequence labelings.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices... | [
"def",
"_mutual_info_score",
"(",
"reference_indices",
",",
"estimated_indices",
",",
"contingency",
"=",
"None",
")",
":",
"if",
"contingency",
"is",
"None",
":",
"contingency",
"=",
"_contingency_matrix",
"(",
"reference_indices",
",",
"estimated_indices",
")",
".... | Compute the mutual information between two sequence labelings.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices
contingency : np.ndarray
Pre-computed contingency matrix. If None, one wi... | [
"Compute",
"the",
"mutual",
"information",
"between",
"two",
"sequence",
"labelings",
"."
] | python | train |
KyleJamesWalker/yamlsettings | yamlsettings/extensions/registry.py | https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L39-L45 | def _discover(self):
"""Find and install all extensions"""
for ep in pkg_resources.iter_entry_points('yamlsettings10'):
ext = ep.load()
if callable(ext):
ext = ext()
self.add(ext) | [
"def",
"_discover",
"(",
"self",
")",
":",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'yamlsettings10'",
")",
":",
"ext",
"=",
"ep",
".",
"load",
"(",
")",
"if",
"callable",
"(",
"ext",
")",
":",
"ext",
"=",
"ext",
"(",
")",
... | Find and install all extensions | [
"Find",
"and",
"install",
"all",
"extensions"
] | python | train |
saltstack/salt | salt/states/selinux.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L292-L315 | def module_remove(name):
'''
Removes SELinux module
name
The name of the module to remove
.. versionadded:: 2016.11.6
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
modules = __salt__['selinux.list_semod']()
if name not i... | [
"def",
"module_remove",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"modules",
"=",
"__salt__",
"[",
"'selinux.list_semod'",
"]",
"(",
... | Removes SELinux module
name
The name of the module to remove
.. versionadded:: 2016.11.6 | [
"Removes",
"SELinux",
"module"
] | python | train |
odlgroup/odl | odl/discr/lp_discr.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/discr/lp_discr.py#L697-L714 | def imag(self, newimag):
"""Set the imaginary part of this element to ``newimag``.
This method is invoked by ``x.imag = other``.
Parameters
----------
newimag : array-like or scalar
Values to be assigned to the imaginary part of this element.
Raises
... | [
"def",
"imag",
"(",
"self",
",",
"newimag",
")",
":",
"if",
"self",
".",
"space",
".",
"is_real",
":",
"raise",
"ValueError",
"(",
"'cannot set imaginary part in real spaces'",
")",
"self",
".",
"tensor",
".",
"imag",
"=",
"newimag"
] | Set the imaginary part of this element to ``newimag``.
This method is invoked by ``x.imag = other``.
Parameters
----------
newimag : array-like or scalar
Values to be assigned to the imaginary part of this element.
Raises
------
ValueError
... | [
"Set",
"the",
"imaginary",
"part",
"of",
"this",
"element",
"to",
"newimag",
"."
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1453-L1466 | def stage_tc_create_tag(self, tag, resource):
"""Add a tag to a resource.
Args:
tag (str): The tag to be added to the resource.
resource (obj): An instance of tcex resource class.
"""
tag_resource = resource.tags(self.tcex.safetag(tag))
tag_resource.http_... | [
"def",
"stage_tc_create_tag",
"(",
"self",
",",
"tag",
",",
"resource",
")",
":",
"tag_resource",
"=",
"resource",
".",
"tags",
"(",
"self",
".",
"tcex",
".",
"safetag",
"(",
"tag",
")",
")",
"tag_resource",
".",
"http_method",
"=",
"'POST'",
"t_response",... | Add a tag to a resource.
Args:
tag (str): The tag to be added to the resource.
resource (obj): An instance of tcex resource class. | [
"Add",
"a",
"tag",
"to",
"a",
"resource",
"."
] | python | train |
Julius2342/pyvlx | pyvlx/frames/frame_get_version.py | https://github.com/Julius2342/pyvlx/blob/ee78e1324bcb1be5b8d1a9d05ab5496b72eae848/pyvlx/frames/frame_get_version.py#L56-L61 | def from_payload(self, payload):
"""Init frame from binary data."""
self._software_version = payload[0:6]
self.hardware_version = payload[6]
self.product_group = payload[7]
self.product_type = payload[8] | [
"def",
"from_payload",
"(",
"self",
",",
"payload",
")",
":",
"self",
".",
"_software_version",
"=",
"payload",
"[",
"0",
":",
"6",
"]",
"self",
".",
"hardware_version",
"=",
"payload",
"[",
"6",
"]",
"self",
".",
"product_group",
"=",
"payload",
"[",
... | Init frame from binary data. | [
"Init",
"frame",
"from",
"binary",
"data",
"."
] | python | train |
Kozea/cairocffi | cairocffi/fonts.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/fonts.py#L465-L472 | def set_hint_style(self, hint_style):
"""Changes the :ref:`HINT_STYLE` for the font options object.
This controls whether to fit font outlines to the pixel grid,
and if so, whether to optimize for fidelity or contrast.
"""
cairo.cairo_font_options_set_hint_style(self._pointer, h... | [
"def",
"set_hint_style",
"(",
"self",
",",
"hint_style",
")",
":",
"cairo",
".",
"cairo_font_options_set_hint_style",
"(",
"self",
".",
"_pointer",
",",
"hint_style",
")",
"self",
".",
"_check_status",
"(",
")"
] | Changes the :ref:`HINT_STYLE` for the font options object.
This controls whether to fit font outlines to the pixel grid,
and if so, whether to optimize for fidelity or contrast. | [
"Changes",
"the",
":",
"ref",
":",
"HINT_STYLE",
"for",
"the",
"font",
"options",
"object",
".",
"This",
"controls",
"whether",
"to",
"fit",
"font",
"outlines",
"to",
"the",
"pixel",
"grid",
"and",
"if",
"so",
"whether",
"to",
"optimize",
"for",
"fidelity"... | python | train |
titusjan/argos | argos/config/abstractcti.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L590-L606 | def addSubEditor(self, subEditor, isFocusProxy=False):
""" Adds a sub editor to the layout (at the right but before the reset button)
Will add the necessary event filter to handle tabs and sets the strong focus so
that events will not propagate to the tree view.
If isFocusPr... | [
"def",
"addSubEditor",
"(",
"self",
",",
"subEditor",
",",
"isFocusProxy",
"=",
"False",
")",
":",
"self",
".",
"hBoxLayout",
".",
"insertWidget",
"(",
"len",
"(",
"self",
".",
"_subEditors",
")",
",",
"subEditor",
")",
"self",
".",
"_subEditors",
".",
"... | Adds a sub editor to the layout (at the right but before the reset button)
Will add the necessary event filter to handle tabs and sets the strong focus so
that events will not propagate to the tree view.
If isFocusProxy is True the sub editor will be the focus proxy of the CTI. | [
"Adds",
"a",
"sub",
"editor",
"to",
"the",
"layout",
"(",
"at",
"the",
"right",
"but",
"before",
"the",
"reset",
"button",
")",
"Will",
"add",
"the",
"necessary",
"event",
"filter",
"to",
"handle",
"tabs",
"and",
"sets",
"the",
"strong",
"focus",
"so",
... | python | train |
krukas/Trionyx | trionyx/trionyx/views/core.py | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L304-L320 | def items(self):
"""Get all list items"""
query = self.get_queryset()
fields = self.get_model_config().get_list_fields()
for item in query.iterator():
row = OrderedDict()
for field_name in self.get_current_fields():
field = fields.get(field_name)
... | [
"def",
"items",
"(",
"self",
")",
":",
"query",
"=",
"self",
".",
"get_queryset",
"(",
")",
"fields",
"=",
"self",
".",
"get_model_config",
"(",
")",
".",
"get_list_fields",
"(",
")",
"for",
"item",
"in",
"query",
".",
"iterator",
"(",
")",
":",
"row... | Get all list items | [
"Get",
"all",
"list",
"items"
] | python | train |
eddieantonio/perfection | perfection/forest.py | https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/forest.py#L104-L113 | def edges(self):
"""
Edges of this graph, in canonical order.
"""
canonical_edges = set()
for v1, neighbours in self._vertices.items():
for v2 in neighbours:
edge = self.canonical_order((v1, v2))
canonical_edges.add(edge)
return... | [
"def",
"edges",
"(",
"self",
")",
":",
"canonical_edges",
"=",
"set",
"(",
")",
"for",
"v1",
",",
"neighbours",
"in",
"self",
".",
"_vertices",
".",
"items",
"(",
")",
":",
"for",
"v2",
"in",
"neighbours",
":",
"edge",
"=",
"self",
".",
"canonical_or... | Edges of this graph, in canonical order. | [
"Edges",
"of",
"this",
"graph",
"in",
"canonical",
"order",
"."
] | python | train |
vnmabus/dcor | dcor/_utils.py | https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_utils.py#L66-L78 | def _can_be_double(x):
"""
Return if the array can be safely converted to double.
That happens when the dtype is a float with the same size of
a double or narrower, or when is an integer that can be safely
converted to double (if the roundtrip conversion works).
"""
return ((np.issubdtype(... | [
"def",
"_can_be_double",
"(",
"x",
")",
":",
"return",
"(",
"(",
"np",
".",
"issubdtype",
"(",
"x",
".",
"dtype",
",",
"np",
".",
"floating",
")",
"and",
"x",
".",
"dtype",
".",
"itemsize",
"<=",
"np",
".",
"dtype",
"(",
"float",
")",
".",
"items... | Return if the array can be safely converted to double.
That happens when the dtype is a float with the same size of
a double or narrower, or when is an integer that can be safely
converted to double (if the roundtrip conversion works). | [
"Return",
"if",
"the",
"array",
"can",
"be",
"safely",
"converted",
"to",
"double",
"."
] | python | train |
KelSolaar/Umbra | umbra/ui/widgets/basic_QPlainTextEdit.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/basic_QPlainTextEdit.py#L566-L583 | def set_content(self, content):
"""
Sets document with given content while providing undo capability.
:param content: Content to set.
:type content: list
:return: Method success.
:rtype: bool
"""
cursor = self.textCursor()
cursor.movePosition(QTe... | [
"def",
"set_content",
"(",
"self",
",",
"content",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"Start",
",",
"QTextCursor",
".",
"MoveAnchor",
")",
"cursor",
".",
"movePosition",
"("... | Sets document with given content while providing undo capability.
:param content: Content to set.
:type content: list
:return: Method success.
:rtype: bool | [
"Sets",
"document",
"with",
"given",
"content",
"while",
"providing",
"undo",
"capability",
"."
] | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3540-L3545 | def setContentLen(self, content, len):
"""Replace the content of a node. NOTE: @content is supposed
to be a piece of XML CDATA, so it allows entity references,
but XML special chars need to be escaped first by using
xmlEncodeEntitiesReentrant() resp. xmlEncodeSpecialChars(). """
... | [
"def",
"setContentLen",
"(",
"self",
",",
"content",
",",
"len",
")",
":",
"libxml2mod",
".",
"xmlNodeSetContentLen",
"(",
"self",
".",
"_o",
",",
"content",
",",
"len",
")"
] | Replace the content of a node. NOTE: @content is supposed
to be a piece of XML CDATA, so it allows entity references,
but XML special chars need to be escaped first by using
xmlEncodeEntitiesReentrant() resp. xmlEncodeSpecialChars(). | [
"Replace",
"the",
"content",
"of",
"a",
"node",
".",
"NOTE",
":"
] | python | train |
Becksteinlab/GromacsWrapper | gromacs/fileformats/xvg.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/xvg.py#L997-L1015 | def decimate_rms(self, a, maxpoints, **kwargs):
"""Return data *a* rms-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the root mean square sum in each bin as the decimated data,
using :func:`numkit.timeseries.rms_histogrammed_function`. The coarse
... | [
"def",
"decimate_rms",
"(",
"self",
",",
"a",
",",
"maxpoints",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_decimate",
"(",
"numkit",
".",
"timeseries",
".",
"rms_histogrammed_function",
",",
"a",
",",
"maxpoints",
",",
"*",
"*",
"kwargs"... | Return data *a* rms-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the root mean square sum in each bin as the decimated data,
using :func:`numkit.timeseries.rms_histogrammed_function`. The coarse
grained time in the first column contains the cente... | [
"Return",
"data",
"*",
"a",
"*",
"rms",
"-",
"decimated",
"on",
"*",
"maxpoints",
"*",
"."
] | python | valid |
wummel/linkchecker | linkcheck/url.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/url.py#L558-L572 | def is_duplicate_content_url(url1, url2):
"""Check if both URLs are allowed to point to the same content."""
if url1 == url2:
return True
if url2 in url1:
url1 = shorten_duplicate_content_url(url1)
if not url2.endswith('/') and url1.endswith('/'):
url2 += '/'
retu... | [
"def",
"is_duplicate_content_url",
"(",
"url1",
",",
"url2",
")",
":",
"if",
"url1",
"==",
"url2",
":",
"return",
"True",
"if",
"url2",
"in",
"url1",
":",
"url1",
"=",
"shorten_duplicate_content_url",
"(",
"url1",
")",
"if",
"not",
"url2",
".",
"endswith",... | Check if both URLs are allowed to point to the same content. | [
"Check",
"if",
"both",
"URLs",
"are",
"allowed",
"to",
"point",
"to",
"the",
"same",
"content",
"."
] | python | train |
CartoDB/carto-python | carto/maps.py | https://github.com/CartoDB/carto-python/blob/f6ac3d17ed08e5bc3f99edd2bde4fb7dba3eee16/carto/maps.py#L39-L106 | def get_tile_url(self, x, y, z, layer_id=None, feature_id=None,
filter=None, extension="png"):
"""
Prepares a URL to get data (raster or vector) from a NamedMap or
AnonymousMap
:param x: The x tile
:param y: The y tile
:param z: The zoom level
... | [
"def",
"get_tile_url",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
",",
"layer_id",
"=",
"None",
",",
"feature_id",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"extension",
"=",
"\"png\"",
")",
":",
"base_url",
"=",
"self",
".",
"client",
".",
"ba... | Prepares a URL to get data (raster or vector) from a NamedMap or
AnonymousMap
:param x: The x tile
:param y: The y tile
:param z: The zoom level
:param layer_id: Can be a number (referring to the # layer of your \
map), all layers of your map, or a list ... | [
"Prepares",
"a",
"URL",
"to",
"get",
"data",
"(",
"raster",
"or",
"vector",
")",
"from",
"a",
"NamedMap",
"or",
"AnonymousMap"
] | python | train |
StanfordBioinformatics/loom | server/loomengine_server/api/models/base.py | https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/models/base.py#L126-L147 | def filter_by_name_or_id_or_tag(self, query_string, queryset = None):
"""Find objects that match the identifier of form {name}@{ID}, {name},
or @{ID}, where ID may be truncated
"""
assert self.Model.NAME_FIELD, \
'NAME_FIELD is missing on model %s' % self.Model.__name__
... | [
"def",
"filter_by_name_or_id_or_tag",
"(",
"self",
",",
"query_string",
",",
"queryset",
"=",
"None",
")",
":",
"assert",
"self",
".",
"Model",
".",
"NAME_FIELD",
",",
"'NAME_FIELD is missing on model %s'",
"%",
"self",
".",
"Model",
".",
"__name__",
"assert",
"... | Find objects that match the identifier of form {name}@{ID}, {name},
or @{ID}, where ID may be truncated | [
"Find",
"objects",
"that",
"match",
"the",
"identifier",
"of",
"form",
"{",
"name",
"}"
] | python | train |
proycon/pynlpl | pynlpl/algorithms.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/algorithms.py#L19-L31 | def sum_to_n(n, size, limit=None): #from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number
"""Produce all lists of `size` positive integers in decreasing order
that add up to `n`."""
if size == 1:
yield [n]
return
if limit is None:
limit = ... | [
"def",
"sum_to_n",
"(",
"n",
",",
"size",
",",
"limit",
"=",
"None",
")",
":",
"#from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number",
"if",
"size",
"==",
"1",
":",
"yield",
"[",
"n",
"]",
"return",
"if",
"limit",
"is",
"... | Produce all lists of `size` positive integers in decreasing order
that add up to `n`. | [
"Produce",
"all",
"lists",
"of",
"size",
"positive",
"integers",
"in",
"decreasing",
"order",
"that",
"add",
"up",
"to",
"n",
"."
] | python | train |
pdkit/pdkit | pdkit/utils.py | https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/utils.py#L753-L802 | def separate_walks_turns(data, window=[1, 1, 1]):
""" Will separate peaks into the clusters by following the trend in the clusters array.
This is usedful because scipy's k-mean clustering will give us a continous clusters
array.
:param clusters array: A continous array representing ... | [
"def",
"separate_walks_turns",
"(",
"data",
",",
"window",
"=",
"[",
"1",
",",
"1",
",",
"1",
"]",
")",
":",
"clusters",
",",
"peaks",
",",
"promi",
"=",
"cluster_walk_turn",
"(",
"data",
",",
"window",
"=",
"window",
")",
"group_one",
"=",
"[",
"]",... | Will separate peaks into the clusters by following the trend in the clusters array.
This is usedful because scipy's k-mean clustering will give us a continous clusters
array.
:param clusters array: A continous array representing different classes.
:param peaks array: The peaks t... | [
"Will",
"separate",
"peaks",
"into",
"the",
"clusters",
"by",
"following",
"the",
"trend",
"in",
"the",
"clusters",
"array",
".",
"This",
"is",
"usedful",
"because",
"scipy",
"s",
"k",
"-",
"mean",
"clustering",
"will",
"give",
"us",
"a",
"continous",
"clu... | python | train |
gwastro/pycbc | pycbc/workflow/minifollowups.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/minifollowups.py#L591-L682 | def make_qscan_plot(workflow, ifo, trig_time, out_dir, injection_file=None,
data_segments=None, time_window=100, tags=None):
""" Generate a make_qscan node and add it to workflow.
This function generates a single node of the singles_timefreq executable
and adds it to the current workflo... | [
"def",
"make_qscan_plot",
"(",
"workflow",
",",
"ifo",
",",
"trig_time",
",",
"out_dir",
",",
"injection_file",
"=",
"None",
",",
"data_segments",
"=",
"None",
",",
"time_window",
"=",
"100",
",",
"tags",
"=",
"None",
")",
":",
"tags",
"=",
"[",
"]",
"... | Generate a make_qscan node and add it to workflow.
This function generates a single node of the singles_timefreq executable
and adds it to the current workflow. Parent/child relationships are set by
the input/output files automatically.
Parameters
-----------
workflow: pycbc.workflow.core.Work... | [
"Generate",
"a",
"make_qscan",
"node",
"and",
"add",
"it",
"to",
"workflow",
"."
] | python | train |
wishtack/pysynthetic | synthetic/synthetic_meta_data.py | https://github.com/wishtack/pysynthetic/blob/f37a4a2f1e0313b8c544f60d37c93726bc806ec6/synthetic/synthetic_meta_data.py#L64-L73 | def insertSyntheticMemberAtBegin(self, synthesizedMember):
"""
:type synthesizedMember: SyntheticMember
:raises DuplicateMemberNameError
"""
memberName = synthesizedMember.memberName()
if memberName in [m.memberName() for m in self._syntheticMemberList]:
raise DuplicateMember... | [
"def",
"insertSyntheticMemberAtBegin",
"(",
"self",
",",
"synthesizedMember",
")",
":",
"memberName",
"=",
"synthesizedMember",
".",
"memberName",
"(",
")",
"if",
"memberName",
"in",
"[",
"m",
".",
"memberName",
"(",
")",
"for",
"m",
"in",
"self",
".",
"_syn... | :type synthesizedMember: SyntheticMember
:raises DuplicateMemberNameError | [
":",
"type",
"synthesizedMember",
":",
"SyntheticMember",
":",
"raises",
"DuplicateMemberNameError"
] | python | train |
stephenmcd/django-socketio | django_socketio/example_project/chat/events.py | https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/example_project/chat/events.py#L10-L37 | def message(request, socket, context, message):
"""
Event handler for a room receiving a message. First validates a
joining user's name and sends them the list of users.
"""
room = get_object_or_404(ChatRoom, id=message["room"])
if message["action"] == "start":
name = strip_tags(message[... | [
"def",
"message",
"(",
"request",
",",
"socket",
",",
"context",
",",
"message",
")",
":",
"room",
"=",
"get_object_or_404",
"(",
"ChatRoom",
",",
"id",
"=",
"message",
"[",
"\"room\"",
"]",
")",
"if",
"message",
"[",
"\"action\"",
"]",
"==",
"\"start\""... | Event handler for a room receiving a message. First validates a
joining user's name and sends them the list of users. | [
"Event",
"handler",
"for",
"a",
"room",
"receiving",
"a",
"message",
".",
"First",
"validates",
"a",
"joining",
"user",
"s",
"name",
"and",
"sends",
"them",
"the",
"list",
"of",
"users",
"."
] | python | train |
OCR-D/core | ocrd/ocrd/processor/base.py | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/processor/base.py#L76-L105 | def run_cli(
executable,
mets_url=None,
resolver=None,
workspace=None,
page_id=None,
log_level=None,
input_file_grp=None,
output_file_grp=None,
parameter=None,
working_dir=None,
):
"""
Create a workspace for mets_url and run MP CLI ... | [
"def",
"run_cli",
"(",
"executable",
",",
"mets_url",
"=",
"None",
",",
"resolver",
"=",
"None",
",",
"workspace",
"=",
"None",
",",
"page_id",
"=",
"None",
",",
"log_level",
"=",
"None",
",",
"input_file_grp",
"=",
"None",
",",
"output_file_grp",
"=",
"... | Create a workspace for mets_url and run MP CLI through it | [
"Create",
"a",
"workspace",
"for",
"mets_url",
"and",
"run",
"MP",
"CLI",
"through",
"it"
] | python | train |
GNS3/gns3-server | gns3server/controller/project.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L902-L909 | def start_all(self):
"""
Start all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.start)
yield from pool.join() | [
"def",
"start_all",
"(",
"self",
")",
":",
"pool",
"=",
"Pool",
"(",
"concurrency",
"=",
"3",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
".",
"values",
"(",
")",
":",
"pool",
".",
"append",
"(",
"node",
".",
"start",
")",
"yield",
"from",
"p... | Start all nodes | [
"Start",
"all",
"nodes"
] | python | train |
spyder-ide/spyder | spyder/utils/encoding.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/encoding.py#L63-L77 | def to_unicode_from_fs(string):
"""
Return a unicode version of string decoded using the file system encoding.
"""
if not is_string(string): # string is a QString
string = to_text_string(string.toUtf8(), 'utf-8')
else:
if is_binary_string(string):
try:
... | [
"def",
"to_unicode_from_fs",
"(",
"string",
")",
":",
"if",
"not",
"is_string",
"(",
"string",
")",
":",
"# string is a QString\r",
"string",
"=",
"to_text_string",
"(",
"string",
".",
"toUtf8",
"(",
")",
",",
"'utf-8'",
")",
"else",
":",
"if",
"is_binary_st... | Return a unicode version of string decoded using the file system encoding. | [
"Return",
"a",
"unicode",
"version",
"of",
"string",
"decoded",
"using",
"the",
"file",
"system",
"encoding",
"."
] | python | train |
openstates/billy | billy/importers/names.py | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/names.py#L120-L131 | def _normalize(self, name):
"""
Normalizes a legislator name by stripping titles from the front,
converting to lowercase and removing punctuation.
"""
name = re.sub(
r'^(Senator|Representative|Sen\.?|Rep\.?|'
'Hon\.?|Right Hon\.?|Mr\.?|Mrs\.?|Ms\.?|L\'hon\... | [
"def",
"_normalize",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"r'^(Senator|Representative|Sen\\.?|Rep\\.?|'",
"'Hon\\.?|Right Hon\\.?|Mr\\.?|Mrs\\.?|Ms\\.?|L\\'hon\\.?|'",
"'Assembly(member|man|woman)) '",
",",
"''",
",",
"name",
")",
"retur... | Normalizes a legislator name by stripping titles from the front,
converting to lowercase and removing punctuation. | [
"Normalizes",
"a",
"legislator",
"name",
"by",
"stripping",
"titles",
"from",
"the",
"front",
"converting",
"to",
"lowercase",
"and",
"removing",
"punctuation",
"."
] | python | train |
sorgerlab/indra | indra/sources/geneways/symbols_parser.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/symbols_parser.py#L50-L57 | def symbol_to_id(self, symbol):
"""Returns the list of Entrez IDs for a given Geneways symbol
(there may be more than one)"""
if symbol not in self.symbols_to_ids:
m = 'Could not look up Entrez ID for Geneways symbol ' + symbol
raise Exception(m)
return self.symb... | [
"def",
"symbol_to_id",
"(",
"self",
",",
"symbol",
")",
":",
"if",
"symbol",
"not",
"in",
"self",
".",
"symbols_to_ids",
":",
"m",
"=",
"'Could not look up Entrez ID for Geneways symbol '",
"+",
"symbol",
"raise",
"Exception",
"(",
"m",
")",
"return",
"self",
... | Returns the list of Entrez IDs for a given Geneways symbol
(there may be more than one) | [
"Returns",
"the",
"list",
"of",
"Entrez",
"IDs",
"for",
"a",
"given",
"Geneways",
"symbol",
"(",
"there",
"may",
"be",
"more",
"than",
"one",
")"
] | python | train |
skyfielders/python-skyfield | skyfield/positionlib.py | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L277-L304 | def from_altaz(self, alt=None, az=None, alt_degrees=None, az_degrees=None,
distance=Distance(au=0.1)):
"""Generate an Apparent position from an altitude and azimuth.
The altitude and azimuth can each be provided as an `Angle`
object, or else as a number of degrees provided as... | [
"def",
"from_altaz",
"(",
"self",
",",
"alt",
"=",
"None",
",",
"az",
"=",
"None",
",",
"alt_degrees",
"=",
"None",
",",
"az_degrees",
"=",
"None",
",",
"distance",
"=",
"Distance",
"(",
"au",
"=",
"0.1",
")",
")",
":",
"# TODO: should this method live o... | Generate an Apparent position from an altitude and azimuth.
The altitude and azimuth can each be provided as an `Angle`
object, or else as a number of degrees provided as either a
float or a tuple of degrees, arcminutes, and arcseconds::
alt=Angle(...), az=Angle(...)
al... | [
"Generate",
"an",
"Apparent",
"position",
"from",
"an",
"altitude",
"and",
"azimuth",
"."
] | python | train |
chrislim2888/IP2Location-Python | IP2Location.py | https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L177-L180 | def get_area_code(self, ip):
''' Get area_code '''
rec = self.get_all(ip)
return rec and rec.area_code | [
"def",
"get_area_code",
"(",
"self",
",",
"ip",
")",
":",
"rec",
"=",
"self",
".",
"get_all",
"(",
"ip",
")",
"return",
"rec",
"and",
"rec",
".",
"area_code"
] | Get area_code | [
"Get",
"area_code"
] | python | train |
horazont/aiosasl | aiosasl/__init__.py | https://github.com/horazont/aiosasl/blob/af58bf30f688757e58af6e87892d35a8ce798482/aiosasl/__init__.py#L464-L509 | def response(self, payload):
"""
Send a response to the previously received challenge, with the given
`payload`. The payload is encoded using base64 and transmitted to the
server.
Return the next state of the state machine as tuple (see
:class:`SASLStateMachine` for deta... | [
"def",
"response",
"(",
"self",
",",
"payload",
")",
":",
"if",
"self",
".",
"_state",
"==",
"SASLState",
".",
"SUCCESS_SIMULATE_CHALLENGE",
":",
"if",
"payload",
"!=",
"b\"\"",
":",
"# XXX: either our mechanism is buggy or the server",
"# sent SASLState.SUCCESS before ... | Send a response to the previously received challenge, with the given
`payload`. The payload is encoded using base64 and transmitted to the
server.
Return the next state of the state machine as tuple (see
:class:`SASLStateMachine` for details). | [
"Send",
"a",
"response",
"to",
"the",
"previously",
"received",
"challenge",
"with",
"the",
"given",
"payload",
".",
"The",
"payload",
"is",
"encoded",
"using",
"base64",
"and",
"transmitted",
"to",
"the",
"server",
"."
] | python | test |
wavycloud/pyboto3 | pyboto3/ssm.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/ssm.py#L3774-L3883 | def register_task_with_maintenance_window(WindowId=None, Targets=None, TaskArn=None, ServiceRoleArn=None, TaskType=None, TaskParameters=None, Priority=None, MaxConcurrency=None, MaxErrors=None, LoggingInfo=None, ClientToken=None):
"""
Adds a new task to a Maintenance Window.
See also: AWS API Documentation
... | [
"def",
"register_task_with_maintenance_window",
"(",
"WindowId",
"=",
"None",
",",
"Targets",
"=",
"None",
",",
"TaskArn",
"=",
"None",
",",
"ServiceRoleArn",
"=",
"None",
",",
"TaskType",
"=",
"None",
",",
"TaskParameters",
"=",
"None",
",",
"Priority",
"=",
... | Adds a new task to a Maintenance Window.
See also: AWS API Documentation
:example: response = client.register_task_with_maintenance_window(
WindowId='string',
Targets=[
{
'Key': 'string',
'Values': [
'string',
... | [
"Adds",
"a",
"new",
"task",
"to",
"a",
"Maintenance",
"Window",
".",
"See",
"also",
":",
"AWS",
"API",
"Documentation",
":",
"example",
":",
"response",
"=",
"client",
".",
"register_task_with_maintenance_window",
"(",
"WindowId",
"=",
"string",
"Targets",
"="... | python | train |
Kozea/cairocffi | cairocffi/context.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1754-L1764 | def set_font_face(self, font_face):
"""Replaces the current font face with :obj:`font_face`.
:param font_face:
A :class:`FontFace` object,
or :obj:`None` to restore the default font.
"""
font_face = font_face._pointer if font_face is not None else ffi.NULL
... | [
"def",
"set_font_face",
"(",
"self",
",",
"font_face",
")",
":",
"font_face",
"=",
"font_face",
".",
"_pointer",
"if",
"font_face",
"is",
"not",
"None",
"else",
"ffi",
".",
"NULL",
"cairo",
".",
"cairo_set_font_face",
"(",
"self",
".",
"_pointer",
",",
"fo... | Replaces the current font face with :obj:`font_face`.
:param font_face:
A :class:`FontFace` object,
or :obj:`None` to restore the default font. | [
"Replaces",
"the",
"current",
"font",
"face",
"with",
":",
"obj",
":",
"font_face",
"."
] | python | train |
thriftrw/thriftrw-python | thriftrw/idl/parser.py | https://github.com/thriftrw/thriftrw-python/blob/4f2f71acd7a0ac716c9ea5cdcea2162aa561304a/thriftrw/idl/parser.py#L206-L210 | def p_struct(self, p):
'''struct : STRUCT IDENTIFIER '{' field_seq '}' annotations'''
p[0] = ast.Struct(
name=p[2], fields=p[4], annotations=p[6], lineno=p.lineno(2)
) | [
"def",
"p_struct",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Struct",
"(",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"fields",
"=",
"p",
"[",
"4",
"]",
",",
"annotations",
"=",
"p",
"[",
"6",
"]",
",",
"lineno",
"... | struct : STRUCT IDENTIFIER '{' field_seq '}' annotations | [
"struct",
":",
"STRUCT",
"IDENTIFIER",
"{",
"field_seq",
"}",
"annotations"
] | python | train |
wavycloud/pyboto3 | pyboto3/cloudformation.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/cloudformation.py#L123-L253 | def create_change_set(StackName=None, TemplateBody=None, TemplateURL=None, UsePreviousTemplate=None, Parameters=None, Capabilities=None, ResourceTypes=None, RoleARN=None, NotificationARNs=None, Tags=None, ChangeSetName=None, ClientToken=None, Description=None, ChangeSetType=None):
"""
Creates a list of changes ... | [
"def",
"create_change_set",
"(",
"StackName",
"=",
"None",
",",
"TemplateBody",
"=",
"None",
",",
"TemplateURL",
"=",
"None",
",",
"UsePreviousTemplate",
"=",
"None",
",",
"Parameters",
"=",
"None",
",",
"Capabilities",
"=",
"None",
",",
"ResourceTypes",
"=",
... | Creates a list of changes that will be applied to a stack so that you can review the changes before executing them. You can create a change set for a stack that doesn't exist or an existing stack. If you create a change set for a stack that doesn't exist, the change set shows all of the resources that AWS CloudFormatio... | [
"Creates",
"a",
"list",
"of",
"changes",
"that",
"will",
"be",
"applied",
"to",
"a",
"stack",
"so",
"that",
"you",
"can",
"review",
"the",
"changes",
"before",
"executing",
"them",
".",
"You",
"can",
"create",
"a",
"change",
"set",
"for",
"a",
"stack",
... | python | train |
waleedka/hiddenlayer | hiddenlayer/canvas.py | https://github.com/waleedka/hiddenlayer/blob/294f8732b271cbdd6310c55bdf5ce855cbf61c75/hiddenlayer/canvas.py#L191-L204 | def draw_image(self, metric, limit=5):
"""Display a series of images at different time steps."""
rows = 1
cols = limit
self.ax.axis("off")
# Take the Axes gridspec and divide it into a grid
gs = matplotlib.gridspec.GridSpecFromSubplotSpec(
rows, cols, subplot_... | [
"def",
"draw_image",
"(",
"self",
",",
"metric",
",",
"limit",
"=",
"5",
")",
":",
"rows",
"=",
"1",
"cols",
"=",
"limit",
"self",
".",
"ax",
".",
"axis",
"(",
"\"off\"",
")",
"# Take the Axes gridspec and divide it into a grid",
"gs",
"=",
"matplotlib",
"... | Display a series of images at different time steps. | [
"Display",
"a",
"series",
"of",
"images",
"at",
"different",
"time",
"steps",
"."
] | python | train |
googledatalab/pydatalab | google/datalab/bigquery/_query.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_query.py#L324-L339 | def execute(self, output_options=None, sampling=None, context=None, query_params=None):
""" Initiate the query and return a QueryJob.
Args:
output_options: a QueryOutput object describing how to execute the query
sampling: sampling function to use. No sampling is done if None. See bigquery.Sampling... | [
"def",
"execute",
"(",
"self",
",",
"output_options",
"=",
"None",
",",
"sampling",
"=",
"None",
",",
"context",
"=",
"None",
",",
"query_params",
"=",
"None",
")",
":",
"return",
"self",
".",
"execute_async",
"(",
"output_options",
",",
"sampling",
"=",
... | Initiate the query and return a QueryJob.
Args:
output_options: a QueryOutput object describing how to execute the query
sampling: sampling function to use. No sampling is done if None. See bigquery.Sampling
context: an optional Context object providing project_id and credentials. If a specific
... | [
"Initiate",
"the",
"query",
"and",
"return",
"a",
"QueryJob",
"."
] | python | train |
limix/glimix-core | glimix_core/cov/_free.py | https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/cov/_free.py#L170-L189 | def logdet(self):
"""
Log of |K|.
Returns
-------
float
Log-determinant of K.
"""
from numpy.linalg import slogdet
K = self.value()
sign, logdet = slogdet(K)
if sign != 1.0:
msg = "The estimated determinant of K i... | [
"def",
"logdet",
"(",
"self",
")",
":",
"from",
"numpy",
".",
"linalg",
"import",
"slogdet",
"K",
"=",
"self",
".",
"value",
"(",
")",
"sign",
",",
"logdet",
"=",
"slogdet",
"(",
"K",
")",
"if",
"sign",
"!=",
"1.0",
":",
"msg",
"=",
"\"The estimate... | Log of |K|.
Returns
-------
float
Log-determinant of K. | [
"Log",
"of",
"|K|",
"."
] | python | valid |
oz123/blogit | blogit/blogit.py | https://github.com/oz123/blogit/blob/15b94969fa43aaf8dc677a8184b144ae8c0f7700/blogit/blogit.py#L467-L480 | def preview(): # pragma: no coverage
"""launch an HTTP to preview the website"""
Handler = http.server.SimpleHTTPRequestHandler
socketserver.TCPServer.allow_reuse_address = True
port = CONFIG['http_port']
httpd = socketserver.TCPServer(("", port), Handler)
os.chdir(CONFIG['output_to'])
try:... | [
"def",
"preview",
"(",
")",
":",
"# pragma: no coverage",
"Handler",
"=",
"http",
".",
"server",
".",
"SimpleHTTPRequestHandler",
"socketserver",
".",
"TCPServer",
".",
"allow_reuse_address",
"=",
"True",
"port",
"=",
"CONFIG",
"[",
"'http_port'",
"]",
"httpd",
... | launch an HTTP to preview the website | [
"launch",
"an",
"HTTP",
"to",
"preview",
"the",
"website"
] | python | train |
pypa/pipenv | pipenv/vendor/click/termui.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/termui.py#L232-L258 | def echo_via_pager(text_or_generator, color=None):
"""This function takes a text and shows it via an environment specific
pager on stdout.
.. versionchanged:: 3.0
Added the `color` flag.
:param text_or_generator: the text to page, or alternatively, a
generator emit... | [
"def",
"echo_via_pager",
"(",
"text_or_generator",
",",
"color",
"=",
"None",
")",
":",
"color",
"=",
"resolve_color_default",
"(",
"color",
")",
"if",
"inspect",
".",
"isgeneratorfunction",
"(",
"text_or_generator",
")",
":",
"i",
"=",
"text_or_generator",
"(",... | This function takes a text and shows it via an environment specific
pager on stdout.
.. versionchanged:: 3.0
Added the `color` flag.
:param text_or_generator: the text to page, or alternatively, a
generator emitting the text to page.
:param color: controls if the p... | [
"This",
"function",
"takes",
"a",
"text",
"and",
"shows",
"it",
"via",
"an",
"environment",
"specific",
"pager",
"on",
"stdout",
"."
] | python | train |
studionow/pybrightcove | pybrightcove/playlist.py | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/playlist.py#L171-L177 | def find_all(connection=None, page_size=100, page_number=0,
sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER):
"""
List all playlists.
"""
return pybrightcove.connection.ItemResultSet("find_all_playlists",
Playlist, connection, page_size, page_number, sort_by, s... | [
"def",
"find_all",
"(",
"connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"DEFAULT_SORT_ORDER",
")",
":",
"return",
"pybrightcove",
".",
"connection",
".",
"... | List all playlists. | [
"List",
"all",
"playlists",
"."
] | python | train |
saltstack/salt | salt/states/boto_vpc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L674-L691 | def _verify_subnet_association(route_table_desc, subnet_id):
'''
Helper function verify a subnet's route table association
route_table_desc
the description of a route table, as returned from boto_vpc.describe_route_table
subnet_id
the subnet id to verify
.. versionadded:: 2016.11.... | [
"def",
"_verify_subnet_association",
"(",
"route_table_desc",
",",
"subnet_id",
")",
":",
"if",
"route_table_desc",
":",
"if",
"'associations'",
"in",
"route_table_desc",
":",
"for",
"association",
"in",
"route_table_desc",
"[",
"'associations'",
"]",
":",
"if",
"as... | Helper function verify a subnet's route table association
route_table_desc
the description of a route table, as returned from boto_vpc.describe_route_table
subnet_id
the subnet id to verify
.. versionadded:: 2016.11.0 | [
"Helper",
"function",
"verify",
"a",
"subnet",
"s",
"route",
"table",
"association"
] | python | train |
observermedia/django-wordpress-rest | wordpress/loading.py | https://github.com/observermedia/django-wordpress-rest/blob/f0d96891d8ac5a69c8ba90e044876e756fad1bfe/wordpress/loading.py#L500-L519 | def set_posts_param_modified_after(self, params, post_type, status):
"""
Set modified_after date to "continue where we left off" if appropriate
:param params: the GET params dict, which may be updated to include the "modified_after" key
:param post_type: post, page, attachment, or any c... | [
"def",
"set_posts_param_modified_after",
"(",
"self",
",",
"params",
",",
"post_type",
",",
"status",
")",
":",
"if",
"not",
"self",
".",
"purge_first",
"and",
"not",
"self",
".",
"full",
"and",
"not",
"self",
".",
"modified_after",
":",
"if",
"status",
"=... | Set modified_after date to "continue where we left off" if appropriate
:param params: the GET params dict, which may be updated to include the "modified_after" key
:param post_type: post, page, attachment, or any custom post type set up in the WP API
:param status: publish, private, draft, etc.... | [
"Set",
"modified_after",
"date",
"to",
"continue",
"where",
"we",
"left",
"off",
"if",
"appropriate"
] | python | train |
mdsol/rwslib | rwslib/builders/admindata.py | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/admindata.py#L236-L255 | def build(self, builder):
"""Build XML by appending to builder"""
params = dict(OID=self.oid)
if self.user_type:
params.update(dict(UserType=self.user_type.value))
builder.start(self.__class__.__name__, params)
# build the children
for child in ('login_name', ... | [
"def",
"build",
"(",
"self",
",",
"builder",
")",
":",
"params",
"=",
"dict",
"(",
"OID",
"=",
"self",
".",
"oid",
")",
"if",
"self",
".",
"user_type",
":",
"params",
".",
"update",
"(",
"dict",
"(",
"UserType",
"=",
"self",
".",
"user_type",
".",
... | Build XML by appending to builder | [
"Build",
"XML",
"by",
"appending",
"to",
"builder"
] | python | train |
odlgroup/odl | odl/solvers/nonsmooth/proximal_operators.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/nonsmooth/proximal_operators.py#L1352-L1448 | def proximal_l1_l2(space, lam=1, g=None):
r"""Proximal operator factory of the group-L1-L2 norm/distance.
Implements the proximal operator of the functional ::
F(x) = lam || |x - g|_2 ||_1
with ``x`` and ``g`` elements in ``space``, and scaling factor ``lam``.
Here, ``|.|_2`` is the pointwise... | [
"def",
"proximal_l1_l2",
"(",
"space",
",",
"lam",
"=",
"1",
",",
"g",
"=",
"None",
")",
":",
"lam",
"=",
"float",
"(",
"lam",
")",
"if",
"g",
"is",
"not",
"None",
"and",
"g",
"not",
"in",
"space",
":",
"raise",
"TypeError",
"(",
"'{!r} is not an e... | r"""Proximal operator factory of the group-L1-L2 norm/distance.
Implements the proximal operator of the functional ::
F(x) = lam || |x - g|_2 ||_1
with ``x`` and ``g`` elements in ``space``, and scaling factor ``lam``.
Here, ``|.|_2`` is the pointwise Euclidean norm of a vector-valued
functio... | [
"r",
"Proximal",
"operator",
"factory",
"of",
"the",
"group",
"-",
"L1",
"-",
"L2",
"norm",
"/",
"distance",
"."
] | python | train |
NyashniyVladya/MarkovTextGenerator | MarkovTextGenerator/markov_text_generator.py | https://github.com/NyashniyVladya/MarkovTextGenerator/blob/3d90e02a507939709773ef01c7ff3ec68b2b8d4b/MarkovTextGenerator/markov_text_generator.py#L382-L395 | def _parse_from_file(self, file_path):
"""
см. описание _parse_from_text.
Только на вход подаётся не текст, а путь к файлу.
"""
file_path = abspath(file_path)
if not isfile(file_path):
raise MarkovTextExcept("Передан не файл.")
with open(file_path, "rb... | [
"def",
"_parse_from_file",
"(",
"self",
",",
"file_path",
")",
":",
"file_path",
"=",
"abspath",
"(",
"file_path",
")",
"if",
"not",
"isfile",
"(",
"file_path",
")",
":",
"raise",
"MarkovTextExcept",
"(",
"\"Передан не файл.\")",
"",
"with",
"open",
"(",
"fi... | см. описание _parse_from_text.
Только на вход подаётся не текст, а путь к файлу. | [
"см",
".",
"описание",
"_parse_from_text",
".",
"Только",
"на",
"вход",
"подаётся",
"не",
"текст",
"а",
"путь",
"к",
"файлу",
"."
] | python | valid |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L846-L850 | def arrows(self):
"""Iterate over all my arrows."""
for o in self.arrow.values():
for arro in o.values():
yield arro | [
"def",
"arrows",
"(",
"self",
")",
":",
"for",
"o",
"in",
"self",
".",
"arrow",
".",
"values",
"(",
")",
":",
"for",
"arro",
"in",
"o",
".",
"values",
"(",
")",
":",
"yield",
"arro"
] | Iterate over all my arrows. | [
"Iterate",
"over",
"all",
"my",
"arrows",
"."
] | python | train |
fossasia/AYABInterface | AYABInterface/communication/__init__.py | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/communication/__init__.py#L79-L84 | def _message_received(self, message):
"""Notify the observers about the received message."""
with self.lock:
self._state.receive_message(message)
for callable in chain(self._on_message_received, self._on_message):
callable(message) | [
"def",
"_message_received",
"(",
"self",
",",
"message",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"_state",
".",
"receive_message",
"(",
"message",
")",
"for",
"callable",
"in",
"chain",
"(",
"self",
".",
"_on_message_received",
",",
"self"... | Notify the observers about the received message. | [
"Notify",
"the",
"observers",
"about",
"the",
"received",
"message",
"."
] | python | train |
jsommers/switchyard | switchyard/lib/packet/common.py | https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/packet/common.py#L317-L349 | def checksum (data, start = 0, skip_word = None):
"""
Calculate standard internet checksum over data starting at start'th byte
skip_word: If specified, it's the word offset of a word in data to "skip"
(as if it were zero). The purpose is when data is received
data which contains a comp... | [
"def",
"checksum",
"(",
"data",
",",
"start",
"=",
"0",
",",
"skip_word",
"=",
"None",
")",
":",
"if",
"len",
"(",
"data",
")",
"%",
"2",
"!=",
"0",
":",
"arr",
"=",
"array",
".",
"array",
"(",
"'H'",
",",
"data",
"[",
":",
"-",
"1",
"]",
"... | Calculate standard internet checksum over data starting at start'th byte
skip_word: If specified, it's the word offset of a word in data to "skip"
(as if it were zero). The purpose is when data is received
data which contains a computed checksum that you are trying to
verify -... | [
"Calculate",
"standard",
"internet",
"checksum",
"over",
"data",
"starting",
"at",
"start",
"th",
"byte"
] | python | train |
JarryShaw/PyPCAPKit | src/const/hip/parameter.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/hip/parameter.py#L71-L77 | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Parameter(key)
if key not in Parameter._member_map_:
extend_enum(Parameter, key, default)
return Parameter[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"Parameter",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"Parameter",
".",
"_member_map_",
":",
"extend_enum",
"(",
"P... | Backport support for original codes. | [
"Backport",
"support",
"for",
"original",
"codes",
"."
] | python | train |
paramiko/paramiko | paramiko/server.py | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/server.py#L239-L267 | def check_auth_gssapi_with_mic(
self, username, gss_authenticated=AUTH_FAILED, cc_file=None
):
"""
Authenticate the given user to the server if he is a valid krb5
principal.
:param str username: The username of the authenticating client
:param int gss_authenticated: ... | [
"def",
"check_auth_gssapi_with_mic",
"(",
"self",
",",
"username",
",",
"gss_authenticated",
"=",
"AUTH_FAILED",
",",
"cc_file",
"=",
"None",
")",
":",
"if",
"gss_authenticated",
"==",
"AUTH_SUCCESSFUL",
":",
"return",
"AUTH_SUCCESSFUL",
"return",
"AUTH_FAILED"
] | Authenticate the given user to the server if he is a valid krb5
principal.
:param str username: The username of the authenticating client
:param int gss_authenticated: The result of the krb5 authentication
:param str cc_filename: The krb5 client credentials cache filename
:retur... | [
"Authenticate",
"the",
"given",
"user",
"to",
"the",
"server",
"if",
"he",
"is",
"a",
"valid",
"krb5",
"principal",
"."
] | python | train |
schneiderfelipe/pyrrole | pyrrole/drawing.py | https://github.com/schneiderfelipe/pyrrole/blob/13e26accc9a059f0ab69773648b24292fe1fbfd6/pyrrole/drawing.py#L257-L371 | def draw_diagram_nodes(graph, pos=None, nodelist=None, node_size=.7,
node_color='k', style='solid', alpha=1.0, cmap=None,
vmin=None, vmax=None, ax=None, label=None):
"""
Draw nodes of graph.
This draws only the nodes of graph as horizontal lines at each
``y... | [
"def",
"draw_diagram_nodes",
"(",
"graph",
",",
"pos",
"=",
"None",
",",
"nodelist",
"=",
"None",
",",
"node_size",
"=",
".7",
",",
"node_color",
"=",
"'k'",
",",
"style",
"=",
"'solid'",
",",
"alpha",
"=",
"1.0",
",",
"cmap",
"=",
"None",
",",
"vmin... | Draw nodes of graph.
This draws only the nodes of graph as horizontal lines at each
``y = pos[1]`` from ``x - node_size/2`` to ``x + node_size/2``, where
``x = pos[0]``.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with ... | [
"Draw",
"nodes",
"of",
"graph",
"."
] | python | train |
rigetti/quantumflow | quantumflow/backend/numpybk.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L98-L102 | def astensor(array: TensorLike) -> BKTensor:
"""Converts a numpy array to the backend's tensor object
"""
array = np.asarray(array, dtype=CTYPE)
return array | [
"def",
"astensor",
"(",
"array",
":",
"TensorLike",
")",
"->",
"BKTensor",
":",
"array",
"=",
"np",
".",
"asarray",
"(",
"array",
",",
"dtype",
"=",
"CTYPE",
")",
"return",
"array"
] | Converts a numpy array to the backend's tensor object | [
"Converts",
"a",
"numpy",
"array",
"to",
"the",
"backend",
"s",
"tensor",
"object"
] | python | train |
tobgu/pyrsistent | pyrsistent/_plist.py | https://github.com/tobgu/pyrsistent/blob/c84dab0daaa44973cbe83830d14888827b307632/pyrsistent/_plist.py#L73-L86 | def mcons(self, iterable):
"""
Return a new list with all elements of iterable repeatedly cons:ed to the current list.
NB! The elements will be inserted in the reverse order of the iterable.
Runs in O(len(iterable)).
>>> plist([1, 2]).mcons([3, 4])
plist([4, 3, 1, 2])
... | [
"def",
"mcons",
"(",
"self",
",",
"iterable",
")",
":",
"head",
"=",
"self",
"for",
"elem",
"in",
"iterable",
":",
"head",
"=",
"head",
".",
"cons",
"(",
"elem",
")",
"return",
"head"
] | Return a new list with all elements of iterable repeatedly cons:ed to the current list.
NB! The elements will be inserted in the reverse order of the iterable.
Runs in O(len(iterable)).
>>> plist([1, 2]).mcons([3, 4])
plist([4, 3, 1, 2]) | [
"Return",
"a",
"new",
"list",
"with",
"all",
"elements",
"of",
"iterable",
"repeatedly",
"cons",
":",
"ed",
"to",
"the",
"current",
"list",
".",
"NB!",
"The",
"elements",
"will",
"be",
"inserted",
"in",
"the",
"reverse",
"order",
"of",
"the",
"iterable",
... | python | train |
wbond/oscrypto | oscrypto/_openssl/asymmetric.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/asymmetric.py#L208-L218 | def public_key(self):
"""
:return:
The PublicKey object for the public key this certificate contains
"""
if not self._public_key and self.x509:
evp_pkey = libcrypto.X509_get_pubkey(self.x509)
self._public_key = PublicKey(evp_pkey, self.asn1['tbs_certi... | [
"def",
"public_key",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_public_key",
"and",
"self",
".",
"x509",
":",
"evp_pkey",
"=",
"libcrypto",
".",
"X509_get_pubkey",
"(",
"self",
".",
"x509",
")",
"self",
".",
"_public_key",
"=",
"PublicKey",
"(",
... | :return:
The PublicKey object for the public key this certificate contains | [
":",
"return",
":",
"The",
"PublicKey",
"object",
"for",
"the",
"public",
"key",
"this",
"certificate",
"contains"
] | python | valid |
rameshg87/pyremotevbox | pyremotevbox/ZSI/wstools/XMLSchema.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/XMLSchema.py#L594-L646 | def getSchemaItem(self, collection, namespace, name):
"""returns object instance representing namespace, name,
or if does not exist return None if built-in, else
raise SchemaError.
namespace -- namespace item defined in.
name -- name of item.
co... | [
"def",
"getSchemaItem",
"(",
"self",
",",
"collection",
",",
"namespace",
",",
"name",
")",
":",
"parent",
"=",
"GetSchema",
"(",
"self",
")",
"if",
"parent",
".",
"targetNamespace",
"==",
"namespace",
":",
"try",
":",
"obj",
"=",
"getattr",
"(",
"parent... | returns object instance representing namespace, name,
or if does not exist return None if built-in, else
raise SchemaError.
namespace -- namespace item defined in.
name -- name of item.
collection -- collection in parent Schema instance to search. | [
"returns",
"object",
"instance",
"representing",
"namespace",
"name",
"or",
"if",
"does",
"not",
"exist",
"return",
"None",
"if",
"built",
"-",
"in",
"else",
"raise",
"SchemaError",
".",
"namespace",
"--",
"namespace",
"item",
"defined",
"in",
".",
"name",
"... | python | train |
foxx/peewee-extras | peewee_extras.py | https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/peewee_extras.py#L322-L357 | def list(self, filters, cursor, count):
"""
List items from query
"""
assert isinstance(filters, dict), "expected filters type 'dict'"
assert isinstance(cursor, dict), "expected cursor type 'dict'"
# start with our base query
query = self.get_query()
asse... | [
"def",
"list",
"(",
"self",
",",
"filters",
",",
"cursor",
",",
"count",
")",
":",
"assert",
"isinstance",
"(",
"filters",
",",
"dict",
")",
",",
"\"expected filters type 'dict'\"",
"assert",
"isinstance",
"(",
"cursor",
",",
"dict",
")",
",",
"\"expected cu... | List items from query | [
"List",
"items",
"from",
"query"
] | python | valid |
floydhub/floyd-cli | floyd/client/files.py | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/files.py#L77-L88 | def matches_glob_list(path, glob_list):
"""
Given a list of glob patterns, returns a boolean
indicating if a path matches any glob in the list
"""
for glob in glob_list:
try:
if PurePath(path).match(glob):
return True
except TypeError:
pass
... | [
"def",
"matches_glob_list",
"(",
"path",
",",
"glob_list",
")",
":",
"for",
"glob",
"in",
"glob_list",
":",
"try",
":",
"if",
"PurePath",
"(",
"path",
")",
".",
"match",
"(",
"glob",
")",
":",
"return",
"True",
"except",
"TypeError",
":",
"pass",
"retu... | Given a list of glob patterns, returns a boolean
indicating if a path matches any glob in the list | [
"Given",
"a",
"list",
"of",
"glob",
"patterns",
"returns",
"a",
"boolean",
"indicating",
"if",
"a",
"path",
"matches",
"any",
"glob",
"in",
"the",
"list"
] | python | train |
inveniosoftware/invenio-records-files | invenio_records_files/utils.py | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/utils.py#L54-L101 | def file_download_ui(pid, record, _record_file_factory=None, **kwargs):
"""File download view for a given record.
Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:
.. code-block:: python
RECORDS_UI_ENDPOINTS = dict(
recid=dict(
# ...
ro... | [
"def",
"file_download_ui",
"(",
"pid",
",",
"record",
",",
"_record_file_factory",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_record_file_factory",
"=",
"_record_file_factory",
"or",
"record_file_factory",
"# Extract file from record.",
"fileobj",
"=",
"_record... | File download view for a given record.
Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:
.. code-block:: python
RECORDS_UI_ENDPOINTS = dict(
recid=dict(
# ...
route='/records/<pid_value/files/<filename>',
view_imp='invenio_r... | [
"File",
"download",
"view",
"for",
"a",
"given",
"record",
"."
] | python | train |
tensorflow/datasets | tensorflow_datasets/core/features/image_feature.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/image_feature.py#L135-L144 | def encode_example(self, image_or_path_or_fobj):
"""Convert the given image into a dict convertible to tf example."""
if isinstance(image_or_path_or_fobj, np.ndarray):
encoded_image = self._encode_image(image_or_path_or_fobj)
elif isinstance(image_or_path_or_fobj, six.string_types):
with tf.io.g... | [
"def",
"encode_example",
"(",
"self",
",",
"image_or_path_or_fobj",
")",
":",
"if",
"isinstance",
"(",
"image_or_path_or_fobj",
",",
"np",
".",
"ndarray",
")",
":",
"encoded_image",
"=",
"self",
".",
"_encode_image",
"(",
"image_or_path_or_fobj",
")",
"elif",
"i... | Convert the given image into a dict convertible to tf example. | [
"Convert",
"the",
"given",
"image",
"into",
"a",
"dict",
"convertible",
"to",
"tf",
"example",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_qos.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_qos.py#L135-L151 | def qos_map_dscp_cos_mark_to(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
map = ET.SubElement(qos, "map")
dscp_cos = ET.SubElement(map, "dscp-cos")
dscp_cos_m... | [
"def",
"qos_map_dscp_cos_mark_to",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"qos",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"qos\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:b... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
pylast/pylast | src/pylast/__init__.py | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1855-L1861 | def get_top_tracks(self, limit=None, cacheable=True):
"""Returns a list of the most played Tracks by this artist."""
params = self._get_params()
if limit:
params["limit"] = limit
return self._get_things("getTopTracks", "track", Track, params, cacheable) | [
"def",
"get_top_tracks",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"return",
"self",
".",
"... | Returns a list of the most played Tracks by this artist. | [
"Returns",
"a",
"list",
"of",
"the",
"most",
"played",
"Tracks",
"by",
"this",
"artist",
"."
] | python | train |
Yubico/yubikey-manager | ykman/cli/piv.py | https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L869-L894 | def write_object(ctx, pin, management_key, object_id, data):
"""
Write an arbitrary PIV object.
Write a PIV object by providing the object id.
Yubico writable PIV objects are available in
the range 5f0000 - 5fffff.
\b
OBJECT-ID Id of PIV object in HEX.
DATA File contai... | [
"def",
"write_object",
"(",
"ctx",
",",
"pin",
",",
"management_key",
",",
"object_id",
",",
"data",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"_ensure_authenticated",
"(",
"ctx",
",",
"controller",
",",
"pin",
",",
"managem... | Write an arbitrary PIV object.
Write a PIV object by providing the object id.
Yubico writable PIV objects are available in
the range 5f0000 - 5fffff.
\b
OBJECT-ID Id of PIV object in HEX.
DATA File containing the data to be written. Use '-' to use stdin. | [
"Write",
"an",
"arbitrary",
"PIV",
"object",
"."
] | python | train |
UDST/urbansim | urbansim/models/util.py | https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/models/util.py#L307-L347 | def columns_in_formula(formula):
"""
Returns the names of all the columns used in a patsy formula.
Parameters
----------
formula : str, iterable, or dict
Any formula construction supported by ``str_model_expression``.
Returns
-------
columns : list of str
"""
if formul... | [
"def",
"columns_in_formula",
"(",
"formula",
")",
":",
"if",
"formula",
"is",
"None",
":",
"return",
"[",
"]",
"formula",
"=",
"str_model_expression",
"(",
"formula",
",",
"add_constant",
"=",
"False",
")",
"columns",
"=",
"[",
"]",
"tokens",
"=",
"map",
... | Returns the names of all the columns used in a patsy formula.
Parameters
----------
formula : str, iterable, or dict
Any formula construction supported by ``str_model_expression``.
Returns
-------
columns : list of str | [
"Returns",
"the",
"names",
"of",
"all",
"the",
"columns",
"used",
"in",
"a",
"patsy",
"formula",
"."
] | python | train |
timstaley/voeventdb | voeventdb/server/database/models.py | https://github.com/timstaley/voeventdb/blob/e37b176d65fced4ca4f059109a95d6974bb8a091/voeventdb/server/database/models.py#L62-L70 | def to_odict(self, exclude=None):
"""
Returns an OrderedDict representation of the SQLalchemy table row.
"""
if exclude is None:
exclude = tuple()
colnames = [c.name for c in self.__table__.columns
if c.name not in exclude]
return OrderedDi... | [
"def",
"to_odict",
"(",
"self",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"tuple",
"(",
")",
"colnames",
"=",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"self",
".",
"__table__",
".",
"columns",
"if",
... | Returns an OrderedDict representation of the SQLalchemy table row. | [
"Returns",
"an",
"OrderedDict",
"representation",
"of",
"the",
"SQLalchemy",
"table",
"row",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/quantum_info/operators/channel/kraus.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/kraus.py#L361-L397 | def _evolve(self, state, qargs=None):
"""Evolve a quantum state by the QuantumChannel.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Retu... | [
"def",
"_evolve",
"(",
"self",
",",
"state",
",",
"qargs",
"=",
"None",
")",
":",
"# If subsystem evolution we use the SuperOp representation",
"if",
"qargs",
"is",
"not",
"None",
":",
"return",
"SuperOp",
"(",
"self",
")",
".",
"_evolve",
"(",
"state",
",",
... | Evolve a quantum state by the QuantumChannel.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum... | [
"Evolve",
"a",
"quantum",
"state",
"by",
"the",
"QuantumChannel",
"."
] | python | test |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/external/path/_path.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/path/_path.py#L646-L670 | def lines(self, encoding=None, errors='strict', retain=True):
r""" Open this file, read all lines, return them in a list.
Optional arguments:
encoding - The Unicode encoding (or character set) of
the file. The default is None, meaning the content
of the file... | [
"def",
"lines",
"(",
"self",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"retain",
"=",
"True",
")",
":",
"if",
"encoding",
"is",
"None",
"and",
"retain",
":",
"f",
"=",
"self",
".",
"open",
"(",
"'U'",
")",
"try",
":",
"re... | r""" Open this file, read all lines, return them in a list.
Optional arguments:
encoding - The Unicode encoding (or character set) of
the file. The default is None, meaning the content
of the file is read as 8-bit characters and returned
as a list of... | [
"r",
"Open",
"this",
"file",
"read",
"all",
"lines",
"return",
"them",
"in",
"a",
"list",
"."
] | python | test |
fossasia/knittingpattern | knittingpattern/Parser.py | https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L184-L192 | def new_pattern(self, id_, name, rows=None):
"""Create a new knitting pattern.
If rows is :obj:`None` it is replaced with the
:meth:`new_row_collection`.
"""
if rows is None:
rows = self.new_row_collection()
return self._spec.new_pattern(id_, name, rows, self... | [
"def",
"new_pattern",
"(",
"self",
",",
"id_",
",",
"name",
",",
"rows",
"=",
"None",
")",
":",
"if",
"rows",
"is",
"None",
":",
"rows",
"=",
"self",
".",
"new_row_collection",
"(",
")",
"return",
"self",
".",
"_spec",
".",
"new_pattern",
"(",
"id_",... | Create a new knitting pattern.
If rows is :obj:`None` it is replaced with the
:meth:`new_row_collection`. | [
"Create",
"a",
"new",
"knitting",
"pattern",
"."
] | python | valid |
lepture/flask-oauthlib | flask_oauthlib/utils.py | https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/utils.py#L40-L46 | def to_bytes(text, encoding='utf-8'):
"""Make sure text is bytes type."""
if not text:
return text
if not isinstance(text, bytes_type):
text = text.encode(encoding)
return text | [
"def",
"to_bytes",
"(",
"text",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"not",
"text",
":",
"return",
"text",
"if",
"not",
"isinstance",
"(",
"text",
",",
"bytes_type",
")",
":",
"text",
"=",
"text",
".",
"encode",
"(",
"encoding",
")",
"ret... | Make sure text is bytes type. | [
"Make",
"sure",
"text",
"is",
"bytes",
"type",
"."
] | python | test |
senaite/senaite.core | bika/lims/browser/analysisrequest/add2.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/analysisrequest/add2.py#L1443-L1520 | def ajax_recalculate_prices(self):
"""Recalculate prices for all ARs
"""
# When the option "Include and display pricing information" in
# Bika Setup Accounting tab is not selected
if not self.show_recalculate_prices():
return {}
# The sorted records from the ... | [
"def",
"ajax_recalculate_prices",
"(",
"self",
")",
":",
"# When the option \"Include and display pricing information\" in",
"# Bika Setup Accounting tab is not selected",
"if",
"not",
"self",
".",
"show_recalculate_prices",
"(",
")",
":",
"return",
"{",
"}",
"# The sorted reco... | Recalculate prices for all ARs | [
"Recalculate",
"prices",
"for",
"all",
"ARs"
] | python | train |
RedFantom/ttkwidgets | ttkwidgets/table.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/table.py#L616-L627 | def set_children(self, item, *newchildren):
"""
Replaces item’s children with newchildren.
Children present in item that are not present in newchildren are detached
from tree. No items in newchildren may be an ancestor of item.
:param newchildren: new item's children (list of i... | [
"def",
"set_children",
"(",
"self",
",",
"item",
",",
"*",
"newchildren",
")",
":",
"self",
".",
"_visual_drag",
".",
"set_children",
"(",
"item",
",",
"*",
"newchildren",
")",
"ttk",
".",
"Treeview",
".",
"set_children",
"(",
"self",
",",
"item",
",",
... | Replaces item’s children with newchildren.
Children present in item that are not present in newchildren are detached
from tree. No items in newchildren may be an ancestor of item.
:param newchildren: new item's children (list of item identifiers)
:type newchildren: sequence[str] | [
"Replaces",
"item’s",
"children",
"with",
"newchildren",
"."
] | python | train |
erget/StereoVision | stereovision/calibration.py | https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/calibration.py#L124-L128 | def export(self, output_folder):
"""Export matrices as ``*.npy`` files to an output folder."""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
self._interact_with_folder(output_folder, 'w') | [
"def",
"export",
"(",
"self",
",",
"output_folder",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"output_folder",
")",
":",
"os",
".",
"makedirs",
"(",
"output_folder",
")",
"self",
".",
"_interact_with_folder",
"(",
"output_folder",
",",
... | Export matrices as ``*.npy`` files to an output folder. | [
"Export",
"matrices",
"as",
"*",
".",
"npy",
"files",
"to",
"an",
"output",
"folder",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/pyparsing.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L1300-L1327 | def copy( self ):
"""
Make a copy of this :class:`ParserElement`. Useful for defining
different parse actions for the same parsing pattern, using copies of
the original parse element.
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
... | [
"def",
"copy",
"(",
"self",
")",
":",
"cpy",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"cpy",
".",
"parseAction",
"=",
"self",
".",
"parseAction",
"[",
":",
"]",
"cpy",
".",
"ignoreExprs",
"=",
"self",
".",
"ignoreExprs",
"[",
":",
"]",
"if",
"... | Make a copy of this :class:`ParserElement`. Useful for defining
different parse actions for the same parsing pattern, using copies of
the original parse element.
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
integerK = integer.copy().addParse... | [
"Make",
"a",
"copy",
"of",
"this",
":",
"class",
":",
"ParserElement",
".",
"Useful",
"for",
"defining",
"different",
"parse",
"actions",
"for",
"the",
"same",
"parsing",
"pattern",
"using",
"copies",
"of",
"the",
"original",
"parse",
"element",
"."
] | python | train |
PyCQA/pylint | pylint/checkers/raw_metrics.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/raw_metrics.py#L77-L84 | def process_tokens(self, tokens):
"""update stats"""
i = 0
tokens = list(tokens)
while i < len(tokens):
i, lines_number, line_type = get_type(tokens, i)
self.stats["total_lines"] += lines_number
self.stats[line_type] += lines_number | [
"def",
"process_tokens",
"(",
"self",
",",
"tokens",
")",
":",
"i",
"=",
"0",
"tokens",
"=",
"list",
"(",
"tokens",
")",
"while",
"i",
"<",
"len",
"(",
"tokens",
")",
":",
"i",
",",
"lines_number",
",",
"line_type",
"=",
"get_type",
"(",
"tokens",
... | update stats | [
"update",
"stats"
] | python | test |
aiogram/aiogram | aiogram/dispatcher/filters/filters.py | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L214-L225 | def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]:
"""
If ``cls.key`` is not :obj:`None` and that is in config returns config with that argument.
:param full_config:
:return:
"""
if cls.key is not None:
if cls.key in... | [
"def",
"validate",
"(",
"cls",
",",
"full_config",
":",
"typing",
".",
"Dict",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
")",
"->",
"typing",
".",
"Dict",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
":",
"if",
"cls",
".",
"key",
"is",
"not",
... | If ``cls.key`` is not :obj:`None` and that is in config returns config with that argument.
:param full_config:
:return: | [
"If",
"cls",
".",
"key",
"is",
"not",
":",
"obj",
":",
"None",
"and",
"that",
"is",
"in",
"config",
"returns",
"config",
"with",
"that",
"argument",
"."
] | python | train |
marshallward/f90nml | f90nml/parser.py | https://github.com/marshallward/f90nml/blob/4932cabc5221afc844ee6a5b4a05ceb8bd4a2711/f90nml/parser.py#L127-L131 | def sparse_arrays(self, value):
"""Validate and enable spare arrays."""
if not isinstance(value, bool):
raise TypeError('sparse_arrays attribute must be a logical type.')
self._sparse_arrays = value | [
"def",
"sparse_arrays",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"'sparse_arrays attribute must be a logical type.'",
")",
"self",
".",
"_sparse_arrays",
"=",
"value"
] | Validate and enable spare arrays. | [
"Validate",
"and",
"enable",
"spare",
"arrays",
"."
] | python | train |
IdentityPython/fedoidcmsg | src/fedoidcmsg/entity.py | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L209-L232 | def update_metadata_statement(self, metadata_statement, receiver='',
federation=None, context=''):
"""
Update a metadata statement by:
* adding signed metadata statements or uris pointing to signed
metadata statements.
* adding the entities ... | [
"def",
"update_metadata_statement",
"(",
"self",
",",
"metadata_statement",
",",
"receiver",
"=",
"''",
",",
"federation",
"=",
"None",
",",
"context",
"=",
"''",
")",
":",
"self",
".",
"add_sms_spec_to_request",
"(",
"metadata_statement",
",",
"federation",
"="... | Update a metadata statement by:
* adding signed metadata statements or uris pointing to signed
metadata statements.
* adding the entities signing keys
* create metadata statements one per signed metadata statement or uri
sign these and add them to the metadata statement
... | [
"Update",
"a",
"metadata",
"statement",
"by",
":",
"*",
"adding",
"signed",
"metadata",
"statements",
"or",
"uris",
"pointing",
"to",
"signed",
"metadata",
"statements",
".",
"*",
"adding",
"the",
"entities",
"signing",
"keys",
"*",
"create",
"metadata",
"stat... | python | test |
architv/harvey | harvey/harvey.py | https://github.com/architv/harvey/blob/2b96d57b7a1e0dd706f1f00aba3d92a7ae702960/harvey/harvey.py#L53-L58 | def _get_config_name():
'''Get git config user name'''
p = subprocess.Popen('git config --get user.name', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.stdout.readlines()
return _stripslashes(output[0]) | [
"def",
"_get_config_name",
"(",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"'git config --get user.name'",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"output",
"... | Get git config user name | [
"Get",
"git",
"config",
"user",
"name"
] | python | train |
cthoyt/onto2nx | src/onto2nx/ontospy/core/loader.py | https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/loader.py#L116-L141 | def load_uri(self, uri, verbose):
"""
:param uri:
:param rdf_format_opts:
:param verbose:
:return:
"""
if verbose: printDebug("----------")
if verbose: printDebug("Reading: <%s>" % uri)
success = False
for f in self.rdf_format_opt... | [
"def",
"load_uri",
"(",
"self",
",",
"uri",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"printDebug",
"(",
"\"----------\"",
")",
"if",
"verbose",
":",
"printDebug",
"(",
"\"Reading: <%s>\"",
"%",
"uri",
")",
"success",
"=",
"False",
"for",
"f",
"in"... | :param uri:
:param rdf_format_opts:
:param verbose:
:return: | [
":",
"param",
"uri",
":",
":",
"param",
"rdf_format_opts",
":",
":",
"param",
"verbose",
":",
":",
"return",
":"
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/srtm.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/srtm.py#L305-L313 | def _avg(value1, value2, weight):
"""Returns the weighted average of two values and handles the case where
one value is None. If both values are None, None is returned.
"""
if value1 is None:
return value2
if value2 is None:
return value1
retur... | [
"def",
"_avg",
"(",
"value1",
",",
"value2",
",",
"weight",
")",
":",
"if",
"value1",
"is",
"None",
":",
"return",
"value2",
"if",
"value2",
"is",
"None",
":",
"return",
"value1",
"return",
"value2",
"*",
"weight",
"+",
"value1",
"*",
"(",
"1",
"-",
... | Returns the weighted average of two values and handles the case where
one value is None. If both values are None, None is returned. | [
"Returns",
"the",
"weighted",
"average",
"of",
"two",
"values",
"and",
"handles",
"the",
"case",
"where",
"one",
"value",
"is",
"None",
".",
"If",
"both",
"values",
"are",
"None",
"None",
"is",
"returned",
"."
] | python | train |
pazz/urwidtrees | urwidtrees/lru_cache.py | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/lru_cache.py#L10-L141 | def lru_cache(maxsize=100, typed=False):
"""Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) will be treated... | [
"def",
"lru_cache",
"(",
"maxsize",
"=",
"100",
",",
"typed",
"=",
"False",
")",
":",
"# Users should only access the lru_cache through its public API:",
"# cache_info, cache_clear, and f.__wrapped__",
"# The internals of the lru_cache are encapsulated for thread safety and",
"# ... | Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) will be treated as distinct calls with
distinct results.
... | [
"Least",
"-",
"recently",
"-",
"used",
"cache",
"decorator",
"."
] | python | train |
osrg/ryu | ryu/lib/packet/bgp.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/packet/bgp.py#L3731-L3740 | def has_matching_leftmost(self, remote_as):
"""Check if leftmost AS matches *remote_as*."""
if not self.value or not remote_as:
return False
leftmost_seg = self.path_seg_list[0]
if leftmost_seg and leftmost_seg[0] == remote_as:
return True
return False | [
"def",
"has_matching_leftmost",
"(",
"self",
",",
"remote_as",
")",
":",
"if",
"not",
"self",
".",
"value",
"or",
"not",
"remote_as",
":",
"return",
"False",
"leftmost_seg",
"=",
"self",
".",
"path_seg_list",
"[",
"0",
"]",
"if",
"leftmost_seg",
"and",
"le... | Check if leftmost AS matches *remote_as*. | [
"Check",
"if",
"leftmost",
"AS",
"matches",
"*",
"remote_as",
"*",
"."
] | python | train |
ToucanToco/toucan-data-sdk | toucan_data_sdk/utils/generic/clean.py | https://github.com/ToucanToco/toucan-data-sdk/blob/c3ca874e1b64f4bdcc2edda750a72d45d1561d8a/toucan_data_sdk/utils/generic/clean.py#L14-L33 | def clean_dataframe(df, is_slugify=True, threshold=50, rename_cols=None):
"""
This method is used to:
- slugify the column names (if slugify is set to True)
- convert columns to 'category' (if len(unique) < threshold) or 'int'
- clean the dataframe and rename if necessary
"""
if is_slugify:
... | [
"def",
"clean_dataframe",
"(",
"df",
",",
"is_slugify",
"=",
"True",
",",
"threshold",
"=",
"50",
",",
"rename_cols",
"=",
"None",
")",
":",
"if",
"is_slugify",
":",
"df",
"=",
"df",
".",
"rename",
"(",
"columns",
"=",
"slugify",
")",
"df",
"=",
"df"... | This method is used to:
- slugify the column names (if slugify is set to True)
- convert columns to 'category' (if len(unique) < threshold) or 'int'
- clean the dataframe and rename if necessary | [
"This",
"method",
"is",
"used",
"to",
":",
"-",
"slugify",
"the",
"column",
"names",
"(",
"if",
"slugify",
"is",
"set",
"to",
"True",
")",
"-",
"convert",
"columns",
"to",
"category",
"(",
"if",
"len",
"(",
"unique",
")",
"<",
"threshold",
")",
"or",... | python | test |
bsolomon1124/pyfinance | pyfinance/general.py | https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/general.py#L986-L988 | def opt_weights(self):
"""Optimal weights (period-end)."""
return pd.DataFrame(self._xs, index=self.newidx, columns=self.cols) | [
"def",
"opt_weights",
"(",
"self",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"self",
".",
"_xs",
",",
"index",
"=",
"self",
".",
"newidx",
",",
"columns",
"=",
"self",
".",
"cols",
")"
] | Optimal weights (period-end). | [
"Optimal",
"weights",
"(",
"period",
"-",
"end",
")",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.