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 |
|---|---|---|---|---|---|---|---|---|
riggsd/davies | examples/pockettopo2therion.py | https://github.com/riggsd/davies/blob/8566c626202a875947ad01c087300108c68d80b5/examples/pockettopo2therion.py#L24-L42 | def pockettopo2therion(txtfilename):
"""Main function which converts a PocketTopo .TXT file to a Compass .DAT file"""
print 'Converting PocketTopo data file %s ...' % txtfilename
infile = pockettopo.TxtFile.read(txtfilename, merge_duplicate_shots=True)
outfilename = convert_filename(txtfilename)
with open(outfilename, 'w') as outfile:
print >> outfile, 'encoding utf-8'
for insurvey in infile:
print >> outfile
print >> outfile, 'centreline'
print >> outfile, '\t' 'date ' + insurvey.date.strftime('%Y.%m.%d')
print >> outfile, '\t' 'data normal from to compass clino tape'
for shot in insurvey:
print >> outfile, '\t' '%s\t%s\t%7.2f\t%7.2f\t%6.2f' % \
(shot['FROM'], shot.get('TO', None) or '-',
shot.azm, shot.inc, shot.length)
print >> outfile, 'endcentreline'
print 'Wrote Therion data file %s .' % outfilename | [
"def",
"pockettopo2therion",
"(",
"txtfilename",
")",
":",
"print",
"'Converting PocketTopo data file %s ...'",
"%",
"txtfilename",
"infile",
"=",
"pockettopo",
".",
"TxtFile",
".",
"read",
"(",
"txtfilename",
",",
"merge_duplicate_shots",
"=",
"True",
")",
"outfilena... | Main function which converts a PocketTopo .TXT file to a Compass .DAT file | [
"Main",
"function",
"which",
"converts",
"a",
"PocketTopo",
".",
"TXT",
"file",
"to",
"a",
"Compass",
".",
"DAT",
"file"
] | python | train |
paylogic/pip-accel | pip_accel/__init__.py | https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L612-L616 | def clear_build_directory(self):
"""Clear the build directory where pip unpacks the source distribution archives."""
stat = os.stat(self.build_directory)
shutil.rmtree(self.build_directory)
os.makedirs(self.build_directory, stat.st_mode) | [
"def",
"clear_build_directory",
"(",
"self",
")",
":",
"stat",
"=",
"os",
".",
"stat",
"(",
"self",
".",
"build_directory",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"build_directory",
")",
"os",
".",
"makedirs",
"(",
"self",
".",
"build_directory",
... | Clear the build directory where pip unpacks the source distribution archives. | [
"Clear",
"the",
"build",
"directory",
"where",
"pip",
"unpacks",
"the",
"source",
"distribution",
"archives",
"."
] | python | train |
ml4ai/delphi | delphi/utils/indra.py | https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L91-L93 | def is_grounded_statement(s: Influence) -> bool:
""" Check if an Influence statement is grounded """
return is_grounded_concept(s.subj) and is_grounded_concept(s.obj) | [
"def",
"is_grounded_statement",
"(",
"s",
":",
"Influence",
")",
"->",
"bool",
":",
"return",
"is_grounded_concept",
"(",
"s",
".",
"subj",
")",
"and",
"is_grounded_concept",
"(",
"s",
".",
"obj",
")"
] | Check if an Influence statement is grounded | [
"Check",
"if",
"an",
"Influence",
"statement",
"is",
"grounded"
] | python | train |
openego/eTraGo | etrago/tools/io.py | https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L831-L853 | def distance(x0, x1, y0, y1):
"""
Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of point 1
Returns
------
distance : float
square of distance
"""
# Calculate square of the distance between two points (Pythagoras)
distance = (x1.values- x0.values)*(x1.values- x0.values)\
+ (y1.values- y0.values)*(y1.values- y0.values)
return distance | [
"def",
"distance",
"(",
"x0",
",",
"x1",
",",
"y0",
",",
"y1",
")",
":",
"# Calculate square of the distance between two points (Pythagoras)",
"distance",
"=",
"(",
"x1",
".",
"values",
"-",
"x0",
".",
"values",
")",
"*",
"(",
"x1",
".",
"values",
"-",
"x0... | Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of point 1
Returns
------
distance : float
square of distance | [
"Function",
"that",
"calculates",
"the",
"square",
"of",
"the",
"distance",
"between",
"two",
"points",
"."
] | python | train |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L57-L72 | def _post_tidy(html):
""" This method transforms post tidy. Will go away when tidy goes away. """
tree = etree.fromstring(html)
ems = tree.xpath(
"//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]",
namespaces={'xh': 'http://www.w3.org/1999/xhtml'})
for el in ems:
c = el.attrib.get('class', '').split()
c.remove('underline')
el.tag = '{http://www.w3.org/1999/xhtml}u'
if c:
el.attrib['class'] = ' '.join(c)
elif 'class' in el.attrib:
del(el.attrib['class'])
return tree | [
"def",
"_post_tidy",
"(",
"html",
")",
":",
"tree",
"=",
"etree",
".",
"fromstring",
"(",
"html",
")",
"ems",
"=",
"tree",
".",
"xpath",
"(",
"\"//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]\"",
",",
"namespaces",
"=",
"{",
"'xh'",
":",
"'... | This method transforms post tidy. Will go away when tidy goes away. | [
"This",
"method",
"transforms",
"post",
"tidy",
".",
"Will",
"go",
"away",
"when",
"tidy",
"goes",
"away",
"."
] | python | train |
mongodb/mongo-python-driver | gridfs/__init__.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/gridfs/__init__.py#L77-L94 | def new_file(self, **kwargs):
"""Create a new file in GridFS.
Returns a new :class:`~gridfs.grid_file.GridIn` instance to
which data can be written. Any keyword arguments will be
passed through to :meth:`~gridfs.grid_file.GridIn`.
If the ``"_id"`` of the file is manually specified, it must
not already exist in GridFS. Otherwise
:class:`~gridfs.errors.FileExists` is raised.
:Parameters:
- `**kwargs` (optional): keyword arguments for file creation
"""
# No need for __ensure_index_files_id() here; GridIn ensures
# the (files_id, n) index when needed.
return GridIn(
self.__collection, disable_md5=self.__disable_md5, **kwargs) | [
"def",
"new_file",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# No need for __ensure_index_files_id() here; GridIn ensures",
"# the (files_id, n) index when needed.",
"return",
"GridIn",
"(",
"self",
".",
"__collection",
",",
"disable_md5",
"=",
"self",
".",
"__di... | Create a new file in GridFS.
Returns a new :class:`~gridfs.grid_file.GridIn` instance to
which data can be written. Any keyword arguments will be
passed through to :meth:`~gridfs.grid_file.GridIn`.
If the ``"_id"`` of the file is manually specified, it must
not already exist in GridFS. Otherwise
:class:`~gridfs.errors.FileExists` is raised.
:Parameters:
- `**kwargs` (optional): keyword arguments for file creation | [
"Create",
"a",
"new",
"file",
"in",
"GridFS",
"."
] | python | train |
EpistasisLab/tpot | tpot/gp_deap.py | https://github.com/EpistasisLab/tpot/blob/b626271e6b5896a73fb9d7d29bebc7aa9100772e/tpot/gp_deap.py#L383-L466 | def _wrapped_cross_val_score(sklearn_pipeline, features, target,
cv, scoring_function, sample_weight=None,
groups=None, use_dask=False):
"""Fit estimator and compute scores for a given dataset split.
Parameters
----------
sklearn_pipeline : pipeline object implementing 'fit'
The object to use to fit the data.
features : array-like of shape at least 2D
The data to fit.
target : array-like, optional, default: None
The target variable to try to predict in the case of
supervised learning.
cv: int or cross-validation generator
If CV is a number, then it is the number of folds to evaluate each
pipeline over in k-fold cross-validation during the TPOT optimization
process. If it is an object then it is an object to be used as a
cross-validation generator.
scoring_function : callable
A scorer callable object / function with signature
``scorer(estimator, X, y)``.
sample_weight : array-like, optional
List of sample weights to balance (or un-balanace) the dataset target as needed
groups: array-like {n_samples, }, optional
Group labels for the samples used while splitting the dataset into train/test set
use_dask : bool, default False
Whether to use dask
"""
sample_weight_dict = set_sample_weight(sklearn_pipeline.steps, sample_weight)
features, target, groups = indexable(features, target, groups)
cv = check_cv(cv, target, classifier=is_classifier(sklearn_pipeline))
cv_iter = list(cv.split(features, target, groups))
scorer = check_scoring(sklearn_pipeline, scoring=scoring_function)
if use_dask:
try:
import dask_ml.model_selection # noqa
import dask # noqa
from dask.delayed import Delayed
except ImportError:
msg = "'use_dask' requires the optional dask and dask-ml depedencies."
raise ImportError(msg)
dsk, keys, n_splits = dask_ml.model_selection._search.build_graph(
estimator=sklearn_pipeline,
cv=cv,
scorer=scorer,
candidate_params=[{}],
X=features,
y=target,
groups=groups,
fit_params=sample_weight_dict,
refit=False,
error_score=float('-inf'),
)
cv_results = Delayed(keys[0], dsk)
scores = [cv_results['split{}_test_score'.format(i)]
for i in range(n_splits)]
CV_score = dask.delayed(np.array)(scores)[:, 0]
return dask.delayed(np.nanmean)(CV_score)
else:
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
scores = [_fit_and_score(estimator=clone(sklearn_pipeline),
X=features,
y=target,
scorer=scorer,
train=train,
test=test,
verbose=0,
parameters=None,
fit_params=sample_weight_dict)
for train, test in cv_iter]
CV_score = np.array(scores)[:, 0]
return np.nanmean(CV_score)
except TimeoutException:
return "Timeout"
except Exception as e:
return -float('inf') | [
"def",
"_wrapped_cross_val_score",
"(",
"sklearn_pipeline",
",",
"features",
",",
"target",
",",
"cv",
",",
"scoring_function",
",",
"sample_weight",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"use_dask",
"=",
"False",
")",
":",
"sample_weight_dict",
"=",
"... | Fit estimator and compute scores for a given dataset split.
Parameters
----------
sklearn_pipeline : pipeline object implementing 'fit'
The object to use to fit the data.
features : array-like of shape at least 2D
The data to fit.
target : array-like, optional, default: None
The target variable to try to predict in the case of
supervised learning.
cv: int or cross-validation generator
If CV is a number, then it is the number of folds to evaluate each
pipeline over in k-fold cross-validation during the TPOT optimization
process. If it is an object then it is an object to be used as a
cross-validation generator.
scoring_function : callable
A scorer callable object / function with signature
``scorer(estimator, X, y)``.
sample_weight : array-like, optional
List of sample weights to balance (or un-balanace) the dataset target as needed
groups: array-like {n_samples, }, optional
Group labels for the samples used while splitting the dataset into train/test set
use_dask : bool, default False
Whether to use dask | [
"Fit",
"estimator",
"and",
"compute",
"scores",
"for",
"a",
"given",
"dataset",
"split",
"."
] | python | train |
iskandr/fancyimpute | fancyimpute/iterative_imputer.py | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L865-L950 | def fit_transform(self, X, y=None):
"""Fits the imputer on X and return the transformed X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
y : ignored.
Returns
-------
Xt : array-like, shape (n_samples, n_features)
The imputed input data.
"""
self.random_state_ = getattr(self, "random_state_",
check_random_state(self.random_state))
if self.n_iter < 0:
raise ValueError(
"'n_iter' should be a positive integer. Got {} instead."
.format(self.n_iter))
if self.predictor is None:
if self.sample_posterior:
from sklearn.linear_model import BayesianRidge
self._predictor = BayesianRidge()
else:
from sklearn.linear_model import RidgeCV
# including a very small alpha to approximate OLS
self._predictor = RidgeCV(alphas=np.array([1e-5, 0.1, 1, 10]))
else:
self._predictor = clone(self.predictor)
if hasattr(self._predictor, 'random_state'):
self._predictor.random_state = self.random_state_
self._min_value = np.nan if self.min_value is None else self.min_value
self._max_value = np.nan if self.max_value is None else self.max_value
self.initial_imputer_ = None
X, Xt, mask_missing_values = self._initial_imputation(X)
if self.n_iter == 0:
return Xt
# order in which to impute
# note this is probably too slow for large feature data (d > 100000)
# and a better way would be good.
# see: https://goo.gl/KyCNwj and subsequent comments
ordered_idx = self._get_ordered_idx(mask_missing_values)
self.n_features_with_missing_ = len(ordered_idx)
abs_corr_mat = self._get_abs_corr_mat(Xt)
# impute data
n_samples, n_features = Xt.shape
self.imputation_sequence_ = []
if self.verbose > 0:
print("[IterativeImputer] Completing matrix with shape %s"
% (X.shape,))
start_t = time()
for i_rnd in range(self.n_iter):
if self.imputation_order == 'random':
ordered_idx = self._get_ordered_idx(mask_missing_values)
for feat_idx in ordered_idx:
neighbor_feat_idx = self._get_neighbor_feat_idx(n_features,
feat_idx,
abs_corr_mat)
Xt, predictor = self._impute_one_feature(
Xt, mask_missing_values, feat_idx, neighbor_feat_idx,
predictor=None, fit_mode=True)
predictor_triplet = ImputerTriplet(feat_idx,
neighbor_feat_idx,
predictor)
self.imputation_sequence_.append(predictor_triplet)
if self.verbose > 0:
print('[IterativeImputer] Ending imputation round '
'%d/%d, elapsed time %0.2f'
% (i_rnd + 1, self.n_iter, time() - start_t))
Xt[~mask_missing_values] = X[~mask_missing_values]
return Xt | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"self",
".",
"random_state_",
"=",
"getattr",
"(",
"self",
",",
"\"random_state_\"",
",",
"check_random_state",
"(",
"self",
".",
"random_state",
")",
")",
"if",
"self",
".",... | Fits the imputer on X and return the transformed X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
y : ignored.
Returns
-------
Xt : array-like, shape (n_samples, n_features)
The imputed input data. | [
"Fits",
"the",
"imputer",
"on",
"X",
"and",
"return",
"the",
"transformed",
"X",
"."
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/tunnel/pb/output_stream.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/tunnel/pb/output_stream.py#L65-L72 | def append_varint32(self, value):
"""Appends a signed 32-bit integer to the internal buffer,
encoded as a varint. (Note that a negative varint32 will
always require 10 bytes of space.)
"""
if not wire_format.INT32_MIN <= value <= wire_format.INT32_MAX:
raise errors.EncodeError('Value out of range: %d' % value)
self.append_varint64(value) | [
"def",
"append_varint32",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"wire_format",
".",
"INT32_MIN",
"<=",
"value",
"<=",
"wire_format",
".",
"INT32_MAX",
":",
"raise",
"errors",
".",
"EncodeError",
"(",
"'Value out of range: %d'",
"%",
"value",
")",
... | Appends a signed 32-bit integer to the internal buffer,
encoded as a varint. (Note that a negative varint32 will
always require 10 bytes of space.) | [
"Appends",
"a",
"signed",
"32",
"-",
"bit",
"integer",
"to",
"the",
"internal",
"buffer",
"encoded",
"as",
"a",
"varint",
".",
"(",
"Note",
"that",
"a",
"negative",
"varint32",
"will",
"always",
"require",
"10",
"bytes",
"of",
"space",
".",
")"
] | python | train |
eqcorrscan/EQcorrscan | eqcorrscan/utils/seismo_logs.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/seismo_logs.py#L32-L81 | def rt_time_log(logfile, startdate):
"""
Open and read reftek raw log-file.
Function to open and read a log-file as written by a RefTek RT130
datalogger. The information within is then scanned for timing errors
above the threshold.
:type logfile: str
:param logfile: The logfile to look in
:type startdate: datetime.date
:param startdate: The start of the file as a date - files contain timing \
and the julian day, but not the year.
:returns: List of tuple of (:class:`datetime.datetime`, float) as time \
stamps and phase error.
"""
if os.name == 'nt':
f = io.open(logfile, 'rb')
else:
f = io.open(logfile, 'rb')
phase_err = []
lock = []
# Extract all the phase errors
for line_binary in f:
try:
line = line_binary.decode("utf8", "ignore")
except UnicodeDecodeError:
warnings.warn('Cannot decode line, skipping')
continue
if re.search("INTERNAL CLOCK PHASE ERROR", line):
match = re.search("INTERNAL CLOCK PHASE ERROR", line)
d_start = match.start() - 13
phase_err.append((dt.datetime.strptime(str(startdate.year) +
':' +
line[d_start:d_start + 12],
'%Y:%j:%H:%M:%S'),
float(line.rstrip().split()[-2]) *
0.000001))
elif re.search("EXTERNAL CLOCK POWER IS TURNED OFF", line):
match = re.search("EXTERNAL CLOCK POWER IS TURNED OFF", line)
d_start = match.start() - 13
lock.append((dt.datetime.strptime(str(startdate.year) +
':' + line[d_start:d_start + 12],
'%Y:%j:%H:%M:%S'),
999))
if len(phase_err) == 0 and len(lock) > 0:
phase_err = lock
f.close()
return phase_err | [
"def",
"rt_time_log",
"(",
"logfile",
",",
"startdate",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"f",
"=",
"io",
".",
"open",
"(",
"logfile",
",",
"'rb'",
")",
"else",
":",
"f",
"=",
"io",
".",
"open",
"(",
"logfile",
",",
"'rb'",
... | Open and read reftek raw log-file.
Function to open and read a log-file as written by a RefTek RT130
datalogger. The information within is then scanned for timing errors
above the threshold.
:type logfile: str
:param logfile: The logfile to look in
:type startdate: datetime.date
:param startdate: The start of the file as a date - files contain timing \
and the julian day, but not the year.
:returns: List of tuple of (:class:`datetime.datetime`, float) as time \
stamps and phase error. | [
"Open",
"and",
"read",
"reftek",
"raw",
"log",
"-",
"file",
"."
] | python | train |
senaite/senaite.core | bika/lims/catalog/catalog_utilities.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/catalog/catalog_utilities.py#L250-L301 | def _setup_catalog(portal, catalog_id, catalog_definition):
"""
Given a catalog definition it updates the indexes, columns and content_type
definitions of the catalog.
:portal: the Plone site object
:catalog_id: a string as the catalog id
:catalog_definition: a dictionary like
{
'types': ['ContentType', ...],
'indexes': {
'UID': 'FieldIndex',
...
},
'columns': [
'Title',
...
]
}
"""
reindex = False
catalog = getToolByName(portal, catalog_id, None)
if catalog is None:
logger.warning('Could not find the %s tool.' % (catalog_id))
return False
# Indexes
indexes_ids = catalog_definition.get('indexes', {}).keys()
# Indexing
for idx in indexes_ids:
# The function returns if the index needs to be reindexed
indexed = _addIndex(catalog, idx, catalog_definition['indexes'][idx])
reindex = True if indexed else reindex
# Removing indexes
in_catalog_idxs = catalog.indexes()
to_remove = list(set(in_catalog_idxs)-set(indexes_ids))
for idx in to_remove:
# The function returns if the index has been deleted
desindexed = _delIndex(catalog, idx)
reindex = True if desindexed else reindex
# Columns
columns_ids = catalog_definition.get('columns', [])
for col in columns_ids:
created = _addColumn(catalog, col)
reindex = True if created else reindex
# Removing columns
in_catalog_cols = catalog.schema()
to_remove = list(set(in_catalog_cols)-set(columns_ids))
for col in to_remove:
# The function returns if the index has been deleted
desindexed = _delColumn(catalog, col)
reindex = True if desindexed else reindex
return reindex | [
"def",
"_setup_catalog",
"(",
"portal",
",",
"catalog_id",
",",
"catalog_definition",
")",
":",
"reindex",
"=",
"False",
"catalog",
"=",
"getToolByName",
"(",
"portal",
",",
"catalog_id",
",",
"None",
")",
"if",
"catalog",
"is",
"None",
":",
"logger",
".",
... | Given a catalog definition it updates the indexes, columns and content_type
definitions of the catalog.
:portal: the Plone site object
:catalog_id: a string as the catalog id
:catalog_definition: a dictionary like
{
'types': ['ContentType', ...],
'indexes': {
'UID': 'FieldIndex',
...
},
'columns': [
'Title',
...
]
} | [
"Given",
"a",
"catalog",
"definition",
"it",
"updates",
"the",
"indexes",
"columns",
"and",
"content_type",
"definitions",
"of",
"the",
"catalog",
".",
":",
"portal",
":",
"the",
"Plone",
"site",
"object",
":",
"catalog_id",
":",
"a",
"string",
"as",
"the",
... | python | train |
SBRG/ssbio | ssbio/biopython/Bio/Struct/WWW/WHATIF.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/biopython/Bio/Struct/WWW/WHATIF.py#L58-L76 | def _smcra_to_str(self, smcra, temp_dir='/tmp/'):
"""
WHATIF's input are PDB format files.
Converts a SMCRA object to a PDB formatted string.
"""
temp_path = tempfile.mktemp( '.pdb', dir=temp_dir )
io = PDBIO()
io.set_structure(smcra)
io.save(temp_path)
f = open(temp_path, 'r')
string = f.read()
f.close()
os.remove(temp_path)
return string | [
"def",
"_smcra_to_str",
"(",
"self",
",",
"smcra",
",",
"temp_dir",
"=",
"'/tmp/'",
")",
":",
"temp_path",
"=",
"tempfile",
".",
"mktemp",
"(",
"'.pdb'",
",",
"dir",
"=",
"temp_dir",
")",
"io",
"=",
"PDBIO",
"(",
")",
"io",
".",
"set_structure",
"(",
... | WHATIF's input are PDB format files.
Converts a SMCRA object to a PDB formatted string. | [
"WHATIF",
"s",
"input",
"are",
"PDB",
"format",
"files",
".",
"Converts",
"a",
"SMCRA",
"object",
"to",
"a",
"PDB",
"formatted",
"string",
"."
] | python | train |
pyvisa/pyvisa | pyvisa/ctwrapper/functions.py | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L994-L1015 | def move_in_16(library, session, space, offset, length, extended=False):
"""Moves an 16-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
"""
buffer_16 = (ViUInt16 * length)()
if extended:
ret = library.viMoveIn16Ex(session, space, offset, length, buffer_16)
else:
ret = library.viMoveIn16(session, space, offset, length, buffer_16)
return list(buffer_16), ret | [
"def",
"move_in_16",
"(",
"library",
",",
"session",
",",
"space",
",",
"offset",
",",
"length",
",",
"extended",
"=",
"False",
")",
":",
"buffer_16",
"=",
"(",
"ViUInt16",
"*",
"length",
")",
"(",
")",
"if",
"extended",
":",
"ret",
"=",
"library",
"... | Moves an 16-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode` | [
"Moves",
"an",
"16",
"-",
"bit",
"block",
"of",
"data",
"from",
"the",
"specified",
"address",
"space",
"and",
"offset",
"to",
"local",
"memory",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/dotenv/cli.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L24-L28 | def cli(ctx, file, quote):
'''This script is used to set, get or unset values from a .env file.'''
ctx.obj = {}
ctx.obj['FILE'] = file
ctx.obj['QUOTE'] = quote | [
"def",
"cli",
"(",
"ctx",
",",
"file",
",",
"quote",
")",
":",
"ctx",
".",
"obj",
"=",
"{",
"}",
"ctx",
".",
"obj",
"[",
"'FILE'",
"]",
"=",
"file",
"ctx",
".",
"obj",
"[",
"'QUOTE'",
"]",
"=",
"quote"
] | This script is used to set, get or unset values from a .env file. | [
"This",
"script",
"is",
"used",
"to",
"set",
"get",
"or",
"unset",
"values",
"from",
"a",
".",
"env",
"file",
"."
] | python | train |
sdispater/cachy | cachy/tagged_cache.py | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L225-L243 | def _get_minutes(self, duration):
"""
Calculate the number of minutes with the given duration.
:param duration: The duration
:type duration: int or datetime
:rtype: int or None
"""
if isinstance(duration, datetime.datetime):
from_now = (duration - datetime.datetime.now()).total_seconds()
from_now = math.ceil(from_now / 60)
if from_now > 0:
return from_now
return
return duration | [
"def",
"_get_minutes",
"(",
"self",
",",
"duration",
")",
":",
"if",
"isinstance",
"(",
"duration",
",",
"datetime",
".",
"datetime",
")",
":",
"from_now",
"=",
"(",
"duration",
"-",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
".",
"total_s... | Calculate the number of minutes with the given duration.
:param duration: The duration
:type duration: int or datetime
:rtype: int or None | [
"Calculate",
"the",
"number",
"of",
"minutes",
"with",
"the",
"given",
"duration",
"."
] | python | train |
google/grumpy | third_party/stdlib/csv.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/csv.py#L218-L292 | def _guess_quote_and_delimiter(self, data, delimiters):
"""
Looks for text enclosed between two identical quotes
(the probable quotechar) which are preceded and followed
by the same character (the probable delimiter).
For example:
,'some text',
The quote with the most wins, same with the delimiter.
If there is no quotechar the delimiter can't be determined
this way.
"""
matches = []
for restr in ('(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', # ,".*?",
'(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\w\n"\'])(?P<space> ?)', # ".*?",
'(?P<delim>>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', # ,".*?"
'(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n)'): # ".*?" (no delim, no space)
regexp = re.compile(restr, re.DOTALL | re.MULTILINE)
matches = regexp.findall(data)
if matches:
break
if not matches:
# (quotechar, doublequote, delimiter, skipinitialspace)
return ('', False, None, 0)
quotes = {}
delims = {}
spaces = 0
for m in matches:
n = regexp.groupindex['quote'] - 1
key = m[n]
if key:
quotes[key] = quotes.get(key, 0) + 1
try:
n = regexp.groupindex['delim'] - 1
key = m[n]
except KeyError:
continue
if key and (delimiters is None or key in delimiters):
delims[key] = delims.get(key, 0) + 1
try:
n = regexp.groupindex['space'] - 1
except KeyError:
continue
if m[n]:
spaces += 1
quotechar = reduce(lambda a, b, quotes = quotes:
(quotes[a] > quotes[b]) and a or b, quotes.keys())
if delims:
delim = reduce(lambda a, b, delims = delims:
(delims[a] > delims[b]) and a or b, delims.keys())
skipinitialspace = delims[delim] == spaces
if delim == '\n': # most likely a file with a single column
delim = ''
else:
# there is *no* delimiter, it's a single column of quoted data
delim = ''
skipinitialspace = 0
# if we see an extra quote between delimiters, we've got a
# double quoted format
dq_regexp = re.compile(
r"((%(delim)s)|^)\W*%(quote)s[^%(delim)s\n]*%(quote)s[^%(delim)s\n]*%(quote)s\W*((%(delim)s)|$)" % \
{'delim':re.escape(delim), 'quote':quotechar}, re.MULTILINE)
if dq_regexp.search(data):
doublequote = True
else:
doublequote = False
return (quotechar, doublequote, delim, skipinitialspace) | [
"def",
"_guess_quote_and_delimiter",
"(",
"self",
",",
"data",
",",
"delimiters",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"restr",
"in",
"(",
"'(?P<delim>[^\\w\\n\"\\'])(?P<space> ?)(?P<quote>[\"\\']).*?(?P=quote)(?P=delim)'",
",",
"# ,\".*?\",",
"'(?:^|\\n)(?P<quote>[\"... | Looks for text enclosed between two identical quotes
(the probable quotechar) which are preceded and followed
by the same character (the probable delimiter).
For example:
,'some text',
The quote with the most wins, same with the delimiter.
If there is no quotechar the delimiter can't be determined
this way. | [
"Looks",
"for",
"text",
"enclosed",
"between",
"two",
"identical",
"quotes",
"(",
"the",
"probable",
"quotechar",
")",
"which",
"are",
"preceded",
"and",
"followed",
"by",
"the",
"same",
"character",
"(",
"the",
"probable",
"delimiter",
")",
".",
"For",
"exa... | python | valid |
SoCo/SoCo | soco/snapshot.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/snapshot.py#L161-L253 | def restore(self, fade=False):
"""Restore the state of a device to that which was previously saved.
For coordinator devices restore everything. For slave devices
only restore volume etc., not transport info (transport info
comes from the slave's coordinator).
Args:
fade (bool): Whether volume should be faded up on restore.
"""
if self.is_coordinator:
# Start by ensuring that the speaker is paused as we don't want
# things all rolling back when we are changing them, as this could
# include things like audio
transport_info = self.device.get_current_transport_info()
if transport_info is not None:
if transport_info['current_transport_state'] == 'PLAYING':
self.device.pause()
# Check if the queue should be restored
self._restore_queue()
# Reinstate what was playing
if self.is_playing_queue and self.playlist_position > 0:
# was playing from playlist
if self.playlist_position is not None:
# The position in the playlist returned by
# get_current_track_info starts at 1, but when
# playing from playlist, the index starts at 0
# if position > 0:
self.playlist_position -= 1
self.device.play_from_queue(self.playlist_position, False)
if self.track_position is not None:
if self.track_position != "":
self.device.seek(self.track_position)
# reinstate track, position, play mode, cross fade
# Need to make sure there is a proper track selected first
self.device.play_mode = self.play_mode
self.device.cross_fade = self.cross_fade
elif self.is_playing_cloud_queue:
# was playing a cloud queue started by Alexa
# No way yet to re-start this so prevent it throwing an error!
pass
else:
# was playing a stream (radio station, file, or nothing)
# reinstate uri and meta data
if self.media_uri != "":
self.device.play_uri(
self.media_uri, self.media_metadata, start=False)
# For all devices:
# Reinstate all the properties that are pretty easy to do
self.device.mute = self.mute
self.device.bass = self.bass
self.device.treble = self.treble
self.device.loudness = self.loudness
# Reinstate volume
# Can only change volume on device with fixed volume set to False
# otherwise get uPnP error, so check first. Before issuing a network
# command to check, fixed volume always has volume set to 100.
# So only checked fixed volume if volume is 100.
if self.volume == 100:
fixed_vol = self.device.renderingControl.GetOutputFixed(
[('InstanceID', 0)])['CurrentFixed']
else:
fixed_vol = False
# now set volume if not fixed
if not fixed_vol:
if fade:
# if fade requested in restore
# set volume to 0 then fade up to saved volume (non blocking)
self.device.volume = 0
self.device.ramp_to_volume(self.volume)
else:
# set volume
self.device.volume = self.volume
# Now everything is set, see if we need to be playing, stopped
# or paused ( only for coordinators)
if self.is_coordinator:
if self.transport_state == 'PLAYING':
self.device.play()
elif self.transport_state == 'STOPPED':
self.device.stop() | [
"def",
"restore",
"(",
"self",
",",
"fade",
"=",
"False",
")",
":",
"if",
"self",
".",
"is_coordinator",
":",
"# Start by ensuring that the speaker is paused as we don't want",
"# things all rolling back when we are changing them, as this could",
"# include things like audio",
"t... | Restore the state of a device to that which was previously saved.
For coordinator devices restore everything. For slave devices
only restore volume etc., not transport info (transport info
comes from the slave's coordinator).
Args:
fade (bool): Whether volume should be faded up on restore. | [
"Restore",
"the",
"state",
"of",
"a",
"device",
"to",
"that",
"which",
"was",
"previously",
"saved",
"."
] | python | train |
SeabornGames/Table | seaborn_table/table.py | https://github.com/SeabornGames/Table/blob/0c474ef2fb00db0e7cf47e8af91e3556c2e7485a/seaborn_table/table.py#L1280-L1292 | def pop_empty_columns(self, empty=None):
"""
This will pop columns from the printed columns if they only contain
'' or None
:param empty: list of values to treat as empty
"""
empty = ['', None] if empty is None else empty
if len(self) == 0:
return
for col in list(self.columns):
if self[0][col] in empty:
if not [v for v in self.get_column(col) if v not in empty]:
self.pop_column(col) | [
"def",
"pop_empty_columns",
"(",
"self",
",",
"empty",
"=",
"None",
")",
":",
"empty",
"=",
"[",
"''",
",",
"None",
"]",
"if",
"empty",
"is",
"None",
"else",
"empty",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"for",
"col",
"in",
"l... | This will pop columns from the printed columns if they only contain
'' or None
:param empty: list of values to treat as empty | [
"This",
"will",
"pop",
"columns",
"from",
"the",
"printed",
"columns",
"if",
"they",
"only",
"contain",
"or",
"None",
":",
"param",
"empty",
":",
"list",
"of",
"values",
"to",
"treat",
"as",
"empty"
] | python | train |
IdentityPython/SATOSA | src/satosa/scripts/satosa_saml_metadata.py | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/scripts/satosa_saml_metadata.py#L38-L63 | def create_and_write_saml_metadata(proxy_conf, key, cert, dir, valid, split_frontend_metadata=False,
split_backend_metadata=False):
"""
Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT.
"""
satosa_config = SATOSAConfig(proxy_conf)
secc = _get_security_context(key, cert)
frontend_entities, backend_entities = create_entity_descriptors(satosa_config)
output = []
if frontend_entities:
if split_frontend_metadata:
output.extend(_create_split_entity_descriptors(frontend_entities, secc, valid))
else:
output.extend(_create_merged_entities_descriptors(frontend_entities, secc, valid, "frontend.xml"))
if backend_entities:
if split_backend_metadata:
output.extend(_create_split_entity_descriptors(backend_entities, secc, valid))
else:
output.extend(_create_merged_entities_descriptors(backend_entities, secc, valid, "backend.xml"))
for metadata, filename in output:
path = os.path.join(dir, filename)
print("Writing metadata to '{}'".format(path))
with open(path, "w") as f:
f.write(metadata) | [
"def",
"create_and_write_saml_metadata",
"(",
"proxy_conf",
",",
"key",
",",
"cert",
",",
"dir",
",",
"valid",
",",
"split_frontend_metadata",
"=",
"False",
",",
"split_backend_metadata",
"=",
"False",
")",
":",
"satosa_config",
"=",
"SATOSAConfig",
"(",
"proxy_co... | Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT. | [
"Generates",
"SAML",
"metadata",
"for",
"the",
"given",
"PROXY_CONF",
"signed",
"with",
"the",
"given",
"KEY",
"and",
"associated",
"CERT",
"."
] | python | train |
google/tangent | tangent/cfg.py | https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/cfg.py#L87-L108 | def build_cfg(cls, node):
"""Build a CFG for a function.
Args:
node: A function definition the body of which to analyze.
Returns:
A CFG object.
Raises:
TypeError: If the input is not a function definition.
"""
if not isinstance(node, gast.FunctionDef):
raise TypeError('input must be a function definition')
cfg = cls()
cfg.entry = Node(node.args)
cfg.head = [cfg.entry]
cfg.visit_statements(node.body)
cfg.exit = Node(None)
cfg.set_head(cfg.exit)
cfg.backlink(cfg.entry)
return cfg | [
"def",
"build_cfg",
"(",
"cls",
",",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"gast",
".",
"FunctionDef",
")",
":",
"raise",
"TypeError",
"(",
"'input must be a function definition'",
")",
"cfg",
"=",
"cls",
"(",
")",
"cfg",
".",
"e... | Build a CFG for a function.
Args:
node: A function definition the body of which to analyze.
Returns:
A CFG object.
Raises:
TypeError: If the input is not a function definition. | [
"Build",
"a",
"CFG",
"for",
"a",
"function",
"."
] | python | train |
blockstack/virtualchain | virtualchain/lib/blockchain/bitcoin_blockchain/spv.py | https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/blockchain/bitcoin_blockchain/spv.py#L221-L238 | def run( self ):
"""
Interact with the blockchain peer,
until we get a socket error or we
exit the loop explicitly.
Return True on success
Raise on error
"""
self.handshake()
try:
self.loop()
except socket.error, se:
if self.finished:
return True
else:
raise | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"handshake",
"(",
")",
"try",
":",
"self",
".",
"loop",
"(",
")",
"except",
"socket",
".",
"error",
",",
"se",
":",
"if",
"self",
".",
"finished",
":",
"return",
"True",
"else",
":",
"raise"
] | Interact with the blockchain peer,
until we get a socket error or we
exit the loop explicitly.
Return True on success
Raise on error | [
"Interact",
"with",
"the",
"blockchain",
"peer",
"until",
"we",
"get",
"a",
"socket",
"error",
"or",
"we",
"exit",
"the",
"loop",
"explicitly",
".",
"Return",
"True",
"on",
"success",
"Raise",
"on",
"error"
] | python | train |
boundary/pulse-api-cli | boundary/api_call.py | https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L159-L166 | def _get_url_parameters(self):
"""
Encode URL parameters
"""
url_parameters = ''
if self._url_parameters is not None:
url_parameters = '?' + urllib.urlencode(self._url_parameters)
return url_parameters | [
"def",
"_get_url_parameters",
"(",
"self",
")",
":",
"url_parameters",
"=",
"''",
"if",
"self",
".",
"_url_parameters",
"is",
"not",
"None",
":",
"url_parameters",
"=",
"'?'",
"+",
"urllib",
".",
"urlencode",
"(",
"self",
".",
"_url_parameters",
")",
"return... | Encode URL parameters | [
"Encode",
"URL",
"parameters"
] | python | test |
pyQode/pyqode.core | pyqode/core/widgets/splittable_tab_widget.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L1280-L1297 | def _create_code_edit(self, mimetype, *args, **kwargs):
"""
Create a code edit instance based on the mimetype of the file to
open/create.
:type mimetype: mime type
:param args: Positional arguments that must be forwarded to the editor
widget constructor.
:param kwargs: Keyworded arguments that must be forwarded to the editor
widget constructor.
:return: Code editor widget instance.
"""
if mimetype in self.editors.keys():
return self.editors[mimetype](
*args, parent=self.main_tab_widget, **kwargs)
editor = self.fallback_editor(*args, parent=self.main_tab_widget,
**kwargs)
return editor | [
"def",
"_create_code_edit",
"(",
"self",
",",
"mimetype",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mimetype",
"in",
"self",
".",
"editors",
".",
"keys",
"(",
")",
":",
"return",
"self",
".",
"editors",
"[",
"mimetype",
"]",
"(",
... | Create a code edit instance based on the mimetype of the file to
open/create.
:type mimetype: mime type
:param args: Positional arguments that must be forwarded to the editor
widget constructor.
:param kwargs: Keyworded arguments that must be forwarded to the editor
widget constructor.
:return: Code editor widget instance. | [
"Create",
"a",
"code",
"edit",
"instance",
"based",
"on",
"the",
"mimetype",
"of",
"the",
"file",
"to",
"open",
"/",
"create",
"."
] | python | train |
pytroll/satpy | satpy/composites/__init__.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/composites/__init__.py#L1216-L1223 | def _get_band(self, high_res, low_res, color, ratio):
"""Figure out what data should represent this color."""
if self.high_resolution_band == color:
ret = high_res
else:
ret = low_res * ratio
ret.attrs = low_res.attrs.copy()
return ret | [
"def",
"_get_band",
"(",
"self",
",",
"high_res",
",",
"low_res",
",",
"color",
",",
"ratio",
")",
":",
"if",
"self",
".",
"high_resolution_band",
"==",
"color",
":",
"ret",
"=",
"high_res",
"else",
":",
"ret",
"=",
"low_res",
"*",
"ratio",
"ret",
".",... | Figure out what data should represent this color. | [
"Figure",
"out",
"what",
"data",
"should",
"represent",
"this",
"color",
"."
] | python | train |
VitorRamos/cpufreq | cpufreq/cpufreq.py | https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L101-L120 | def reset(self, rg=None):
'''
Enable all offline cpus, and reset max and min frequencies files
rg: range or list of threads to reset
'''
if type(rg) == int:
rg= [rg]
to_reset= rg if rg else self.__get_ranges("present")
self.enable_cpu(to_reset)
for cpu in to_reset:
fpath = path.join("cpu%i"%cpu,"cpufreq","cpuinfo_max_freq")
max_freq = self.__read_cpu_file(fpath)
fpath = path.join("cpu%i"%cpu,"cpufreq","cpuinfo_min_freq")
min_freq = self.__read_cpu_file(fpath)
fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_max_freq")
self.__write_cpu_file(fpath, max_freq.encode())
fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_min_freq")
self.__write_cpu_file(fpath, min_freq.encode()) | [
"def",
"reset",
"(",
"self",
",",
"rg",
"=",
"None",
")",
":",
"if",
"type",
"(",
"rg",
")",
"==",
"int",
":",
"rg",
"=",
"[",
"rg",
"]",
"to_reset",
"=",
"rg",
"if",
"rg",
"else",
"self",
".",
"__get_ranges",
"(",
"\"present\"",
")",
"self",
"... | Enable all offline cpus, and reset max and min frequencies files
rg: range or list of threads to reset | [
"Enable",
"all",
"offline",
"cpus",
"and",
"reset",
"max",
"and",
"min",
"frequencies",
"files"
] | python | train |
faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L142-L168 | def _inputLoop(self):
""" Loop and copy console->serial until EXIT_CHARCTER character is found. """
try:
while self.alive:
try:
c = console.getkey()
except KeyboardInterrupt:
print('kbint')
c = serial.to_bytes([3])
if c == self.EXIT_CHARACTER:
self.stop()
elif c == '\n':
# Convert newline input into \r
self.serial.write(self.WRITE_TERM)
if self.echo:
# Locally just echo the real newline
sys.stdout.write(c)
sys.stdout.flush()
else:
#print('writing: ', c)
self.serial.write(c)
if self.echo:
sys.stdout.write(c)
sys.stdout.flush()
except:
self.alive = False
raise | [
"def",
"_inputLoop",
"(",
"self",
")",
":",
"try",
":",
"while",
"self",
".",
"alive",
":",
"try",
":",
"c",
"=",
"console",
".",
"getkey",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
"'kbint'",
")",
"c",
"=",
"serial",
".",
"to_bytes... | Loop and copy console->serial until EXIT_CHARCTER character is found. | [
"Loop",
"and",
"copy",
"console",
"-",
">",
"serial",
"until",
"EXIT_CHARCTER",
"character",
"is",
"found",
"."
] | python | train |
IdentityPython/pysaml2 | src/saml2/__init__.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L982-L1013 | def extension_elements_to_elements(extension_elements, schemas):
""" Create a list of elements each one matching one of the
given extension elements. This is of course dependent on the access
to schemas that describe the extension elements.
:param extension_elements: The list of extension elements
:param schemas: Imported Python modules that represent the different
known schemas used for the extension elements
:return: A list of elements, representing the set of extension elements
that was possible to match against a Class in the given schemas.
The elements returned are the native representation of the elements
according to the schemas.
"""
res = []
if isinstance(schemas, list):
pass
elif isinstance(schemas, dict):
schemas = list(schemas.values())
else:
return res
for extension_element in extension_elements:
for schema in schemas:
inst = extension_element_to_element(extension_element,
schema.ELEMENT_FROM_STRING,
schema.NAMESPACE)
if inst:
res.append(inst)
break
return res | [
"def",
"extension_elements_to_elements",
"(",
"extension_elements",
",",
"schemas",
")",
":",
"res",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"schemas",
",",
"list",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"schemas",
",",
"dict",
")",
":",
"schemas",
"... | Create a list of elements each one matching one of the
given extension elements. This is of course dependent on the access
to schemas that describe the extension elements.
:param extension_elements: The list of extension elements
:param schemas: Imported Python modules that represent the different
known schemas used for the extension elements
:return: A list of elements, representing the set of extension elements
that was possible to match against a Class in the given schemas.
The elements returned are the native representation of the elements
according to the schemas. | [
"Create",
"a",
"list",
"of",
"elements",
"each",
"one",
"matching",
"one",
"of",
"the",
"given",
"extension",
"elements",
".",
"This",
"is",
"of",
"course",
"dependent",
"on",
"the",
"access",
"to",
"schemas",
"that",
"describe",
"the",
"extension",
"element... | python | train |
Becksteinlab/GromacsWrapper | gromacs/cbook.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L466-L472 | def glob_parts(prefix, ext):
"""Find files from a continuation run"""
if ext.startswith('.'):
ext = ext[1:]
files = glob.glob(prefix+'.'+ext) + glob.glob(prefix+'.part[0-9][0-9][0-9][0-9].'+ext)
files.sort() # at least some rough sorting...
return files | [
"def",
"glob_parts",
"(",
"prefix",
",",
"ext",
")",
":",
"if",
"ext",
".",
"startswith",
"(",
"'.'",
")",
":",
"ext",
"=",
"ext",
"[",
"1",
":",
"]",
"files",
"=",
"glob",
".",
"glob",
"(",
"prefix",
"+",
"'.'",
"+",
"ext",
")",
"+",
"glob",
... | Find files from a continuation run | [
"Find",
"files",
"from",
"a",
"continuation",
"run"
] | python | valid |
eandersson/amqpstorm | amqpstorm/message.py | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L149-L170 | def publish(self, routing_key, exchange='', mandatory=False,
immediate=False):
"""Publish Message.
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param bool mandatory: Requires the message is published
:param bool immediate: Request immediate delivery
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: bool|None
"""
return self._channel.basic.publish(body=self._body,
routing_key=routing_key,
exchange=exchange,
properties=self._properties,
mandatory=mandatory,
immediate=immediate) | [
"def",
"publish",
"(",
"self",
",",
"routing_key",
",",
"exchange",
"=",
"''",
",",
"mandatory",
"=",
"False",
",",
"immediate",
"=",
"False",
")",
":",
"return",
"self",
".",
"_channel",
".",
"basic",
".",
"publish",
"(",
"body",
"=",
"self",
".",
"... | Publish Message.
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param bool mandatory: Requires the message is published
:param bool immediate: Request immediate delivery
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: bool|None | [
"Publish",
"Message",
"."
] | python | train |
eddiejessup/spatious | spatious/geom.py | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/geom.py#L223-L239 | def spheres_sep(ar, aR, br, bR):
"""Return the separation distance between two spheres.
Parameters
----------
ar, br: array-like, shape (n,) in n dimensions
Coordinates of the centres of the spheres `a` and `b`.
aR, bR: float
Radiuses of the spheres `a` and `b`.
Returns
-------
d: float
Separation distance.
A negative value means the spheres intersect each other.
"""
return vector.vector_mag(ar - br) - (aR + bR) | [
"def",
"spheres_sep",
"(",
"ar",
",",
"aR",
",",
"br",
",",
"bR",
")",
":",
"return",
"vector",
".",
"vector_mag",
"(",
"ar",
"-",
"br",
")",
"-",
"(",
"aR",
"+",
"bR",
")"
] | Return the separation distance between two spheres.
Parameters
----------
ar, br: array-like, shape (n,) in n dimensions
Coordinates of the centres of the spheres `a` and `b`.
aR, bR: float
Radiuses of the spheres `a` and `b`.
Returns
-------
d: float
Separation distance.
A negative value means the spheres intersect each other. | [
"Return",
"the",
"separation",
"distance",
"between",
"two",
"spheres",
"."
] | python | train |
BeyondTheClouds/enoslib | enoslib/infra/utils.py | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/utils.py#L6-L12 | def mk_pools(things, keyfnc=lambda x: x):
"Indexes a thing by the keyfnc to construct pools of things."
pools = {}
sthings = sorted(things, key=keyfnc)
for key, thingz in groupby(sthings, key=keyfnc):
pools.setdefault(key, []).extend(list(thingz))
return pools | [
"def",
"mk_pools",
"(",
"things",
",",
"keyfnc",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"pools",
"=",
"{",
"}",
"sthings",
"=",
"sorted",
"(",
"things",
",",
"key",
"=",
"keyfnc",
")",
"for",
"key",
",",
"thingz",
"in",
"groupby",
"(",
"sthings",
... | Indexes a thing by the keyfnc to construct pools of things. | [
"Indexes",
"a",
"thing",
"by",
"the",
"keyfnc",
"to",
"construct",
"pools",
"of",
"things",
"."
] | python | train |
tgbugs/pyontutils | pyontutils/scigraph_deploy.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/scigraph_deploy.py#L398-L414 | def build(self, mode=None, check=False):
""" Just shuffle the current call off to the build server with --local attached """
kwargs = {}
if not self.build_only: # don't try to deploy twice
kwargs[' --build-only'] = True
if not self.local:
kwargs['--local'] = True
if check:
kwargs['--check-built'] = True
remote_args = self.formatted_args(self.args, mode, **kwargs)
cmds = tuple() if self.check_built or self._updated else self.cmds_pyontutils()
if not self._updated:
self._updated = True
return self.runOnBuild(*cmds,
f'scigraph-deploy {remote_args}',
defer_shell_expansion=True,
oper=AND) | [
"def",
"build",
"(",
"self",
",",
"mode",
"=",
"None",
",",
"check",
"=",
"False",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"build_only",
":",
"# don't try to deploy twice",
"kwargs",
"[",
"' --build-only'",
"]",
"=",
"True",
"if",
... | Just shuffle the current call off to the build server with --local attached | [
"Just",
"shuffle",
"the",
"current",
"call",
"off",
"to",
"the",
"build",
"server",
"with",
"--",
"local",
"attached"
] | python | train |
klahnakoski/pyLibrary | mo_dots/__init__.py | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_dots/__init__.py#L586-L592 | def tuplewrap(value):
"""
INTENDED TO TURN lists INTO tuples FOR USE AS KEYS
"""
if isinstance(value, (list, set, tuple) + generator_types):
return tuple(tuplewrap(v) if is_sequence(v) else v for v in value)
return unwrap(value), | [
"def",
"tuplewrap",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
"+",
"generator_types",
")",
":",
"return",
"tuple",
"(",
"tuplewrap",
"(",
"v",
")",
"if",
"is_sequence",
"(",
"v",
")",
... | INTENDED TO TURN lists INTO tuples FOR USE AS KEYS | [
"INTENDED",
"TO",
"TURN",
"lists",
"INTO",
"tuples",
"FOR",
"USE",
"AS",
"KEYS"
] | python | train |
saltstack/salt | salt/states/smartos.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/smartos.py#L205-L225 | def _write_config(config):
'''
writes /usbkey/config
'''
try:
with salt.utils.atomicfile.atomic_open('/usbkey/config', 'w') as config_file:
config_file.write("#\n# This file was generated by salt\n#\n")
for prop in salt.utils.odict.OrderedDict(sorted(config.items())):
if ' ' in six.text_type(config[prop]):
if not config[prop].startswith('"') or not config[prop].endswith('"'):
config[prop] = '"{0}"'.format(config[prop])
config_file.write(
salt.utils.stringutils.to_str(
"{0}={1}\n".format(prop, config[prop])
)
)
log.debug('smartos.config - wrote /usbkey/config: %s', config)
except IOError:
return False
return True | [
"def",
"_write_config",
"(",
"config",
")",
":",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"atomicfile",
".",
"atomic_open",
"(",
"'/usbkey/config'",
",",
"'w'",
")",
"as",
"config_file",
":",
"config_file",
".",
"write",
"(",
"\"#\\n# This file was gener... | writes /usbkey/config | [
"writes",
"/",
"usbkey",
"/",
"config"
] | python | train |
manns/pyspread | pyspread/src/interfaces/pys.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/interfaces/pys.py#L168-L174 | def _pys2code(self, line):
"""Updates code in pys code_array"""
row, col, tab, code = self._split_tidy(line, maxsplit=3)
key = self._get_key(row, col, tab)
self.code_array.dict_grid[key] = unicode(code, encoding='utf-8') | [
"def",
"_pys2code",
"(",
"self",
",",
"line",
")",
":",
"row",
",",
"col",
",",
"tab",
",",
"code",
"=",
"self",
".",
"_split_tidy",
"(",
"line",
",",
"maxsplit",
"=",
"3",
")",
"key",
"=",
"self",
".",
"_get_key",
"(",
"row",
",",
"col",
",",
... | Updates code in pys code_array | [
"Updates",
"code",
"in",
"pys",
"code_array"
] | python | train |
twisted/axiom | axiom/dependency.py | https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/dependency.py#L150-L172 | def uninstallFrom(self, target):
"""
Remove this object from the target, as well as any dependencies
that it automatically installed which were not explicitly
"pinned" by calling "install", and raising an exception if
anything still depends on this.
"""
#did this class powerup on any interfaces? powerdown if so.
target.powerDown(self)
for dc in self.store.query(_DependencyConnector,
_DependencyConnector.target==target):
if dc.installee is self:
dc.deleteFromStore()
for item in installedUniqueRequirements(self, target):
uninstallFrom(item, target)
callback = getattr(self, "uninstalled", None)
if callback is not None:
callback() | [
"def",
"uninstallFrom",
"(",
"self",
",",
"target",
")",
":",
"#did this class powerup on any interfaces? powerdown if so.",
"target",
".",
"powerDown",
"(",
"self",
")",
"for",
"dc",
"in",
"self",
".",
"store",
".",
"query",
"(",
"_DependencyConnector",
",",
"_De... | Remove this object from the target, as well as any dependencies
that it automatically installed which were not explicitly
"pinned" by calling "install", and raising an exception if
anything still depends on this. | [
"Remove",
"this",
"object",
"from",
"the",
"target",
"as",
"well",
"as",
"any",
"dependencies",
"that",
"it",
"automatically",
"installed",
"which",
"were",
"not",
"explicitly",
"pinned",
"by",
"calling",
"install",
"and",
"raising",
"an",
"exception",
"if",
"... | python | train |
whyscream/dspam-milter | dspam/client.py | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/client.py#L512-L524 | def quit(self):
"""
Send LMTP QUIT command, read the server response and disconnect.
"""
self._send('QUIT\r\n')
resp = self._read()
if not resp.startswith('221'):
logger.warning('Unexpected server response at QUIT: ' + resp)
self._socket.close()
self._socket = None
self._recipients = []
self.results = {} | [
"def",
"quit",
"(",
"self",
")",
":",
"self",
".",
"_send",
"(",
"'QUIT\\r\\n'",
")",
"resp",
"=",
"self",
".",
"_read",
"(",
")",
"if",
"not",
"resp",
".",
"startswith",
"(",
"'221'",
")",
":",
"logger",
".",
"warning",
"(",
"'Unexpected server respon... | Send LMTP QUIT command, read the server response and disconnect. | [
"Send",
"LMTP",
"QUIT",
"command",
"read",
"the",
"server",
"response",
"and",
"disconnect",
"."
] | python | train |
wuher/devil | example/userdb/api/resources.py | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/example/userdb/api/resources.py#L81-L95 | def _dict_to_model(self, data):
""" Create new user model instance based on the received data.
Note that the created user is not saved into database.
"""
try:
# we can do this because we have same fields
# in the representation and in the model:
user = models.User(**data)
except TypeError:
# client sent bad data
raise errors.BadRequest()
else:
return user | [
"def",
"_dict_to_model",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"# we can do this because we have same fields",
"# in the representation and in the model:",
"user",
"=",
"models",
".",
"User",
"(",
"*",
"*",
"data",
")",
"except",
"TypeError",
":",
"# clien... | Create new user model instance based on the received data.
Note that the created user is not saved into database. | [
"Create",
"new",
"user",
"model",
"instance",
"based",
"on",
"the",
"received",
"data",
"."
] | python | train |
arraylabs/pymyq | pymyq/api.py | https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L91-L104 | async def close_websession(self):
"""Close web session if not already closed and created by us."""
# We do not close the web session if it was provided.
if self._supplied_websession or self._websession is None:
return
_LOGGER.debug('Closing connections')
# Need to set _websession to none first to prevent any other task
# from closing it as well.
temp_websession = self._websession
self._websession = None
await temp_websession.close()
await asyncio.sleep(0)
_LOGGER.debug('Connections closed') | [
"async",
"def",
"close_websession",
"(",
"self",
")",
":",
"# We do not close the web session if it was provided.",
"if",
"self",
".",
"_supplied_websession",
"or",
"self",
".",
"_websession",
"is",
"None",
":",
"return",
"_LOGGER",
".",
"debug",
"(",
"'Closing connec... | Close web session if not already closed and created by us. | [
"Close",
"web",
"session",
"if",
"not",
"already",
"closed",
"and",
"created",
"by",
"us",
"."
] | python | train |
influxdata/influxdb-python | influxdb/influxdb08/client.py | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L660-L673 | def alter_database_admin(self, username, is_admin):
"""Alter the database admin."""
url = "db/{0}/users/{1}".format(self._database, username)
data = {'admin': is_admin}
self.request(
url=url,
method='POST',
data=data,
expected_response_code=200
)
return True | [
"def",
"alter_database_admin",
"(",
"self",
",",
"username",
",",
"is_admin",
")",
":",
"url",
"=",
"\"db/{0}/users/{1}\"",
".",
"format",
"(",
"self",
".",
"_database",
",",
"username",
")",
"data",
"=",
"{",
"'admin'",
":",
"is_admin",
"}",
"self",
".",
... | Alter the database admin. | [
"Alter",
"the",
"database",
"admin",
"."
] | python | train |
fishtown-analytics/dbt | core/dbt/adapters/cache.py | https://github.com/fishtown-analytics/dbt/blob/aa4f771df28b307af0cf9fe2fc24432f10a8236b/core/dbt/adapters/cache.py#L360-L390 | def _rename_relation(self, old_key, new_relation):
"""Rename a relation named old_key to new_key, updating references.
Return whether or not there was a key to rename.
:param _ReferenceKey old_key: The existing key, to rename from.
:param _CachedRelation new_key: The new relation, to rename to.
"""
# On the database level, a rename updates all values that were
# previously referenced by old_name to be referenced by new_name.
# basically, the name changes but some underlying ID moves. Kind of
# like an object reference!
relation = self.relations.pop(old_key)
new_key = new_relation.key()
# relaton has to rename its innards, so it needs the _CachedRelation.
relation.rename(new_relation)
# update all the relations that refer to it
for cached in self.relations.values():
if cached.is_referenced_by(old_key):
logger.debug(
'updated reference from {0} -> {2} to {1} -> {2}'
.format(old_key, new_key, cached.key())
)
cached.rename_key(old_key, new_key)
self.relations[new_key] = relation
# also fixup the schemas!
self.remove_schema(old_key.database, old_key.schema)
self.add_schema(new_key.database, new_key.schema)
return True | [
"def",
"_rename_relation",
"(",
"self",
",",
"old_key",
",",
"new_relation",
")",
":",
"# On the database level, a rename updates all values that were",
"# previously referenced by old_name to be referenced by new_name.",
"# basically, the name changes but some underlying ID moves. Kind of",... | Rename a relation named old_key to new_key, updating references.
Return whether or not there was a key to rename.
:param _ReferenceKey old_key: The existing key, to rename from.
:param _CachedRelation new_key: The new relation, to rename to. | [
"Rename",
"a",
"relation",
"named",
"old_key",
"to",
"new_key",
"updating",
"references",
".",
"Return",
"whether",
"or",
"not",
"there",
"was",
"a",
"key",
"to",
"rename",
"."
] | python | train |
jaraco/svg.charts | svg/charts/graph.py | https://github.com/jaraco/svg.charts/blob/23053497b3f1af4e760f355050107ae3bc05909d/svg/charts/graph.py#L482-L491 | def draw_titles(self):
"Draws the graph title and subtitle"
if self.show_graph_title:
self.draw_graph_title()
if self.show_graph_subtitle:
self.draw_graph_subtitle()
if self.show_x_title:
self.draw_x_title()
if self.show_y_title:
self.draw_y_title() | [
"def",
"draw_titles",
"(",
"self",
")",
":",
"if",
"self",
".",
"show_graph_title",
":",
"self",
".",
"draw_graph_title",
"(",
")",
"if",
"self",
".",
"show_graph_subtitle",
":",
"self",
".",
"draw_graph_subtitle",
"(",
")",
"if",
"self",
".",
"show_x_title"... | Draws the graph title and subtitle | [
"Draws",
"the",
"graph",
"title",
"and",
"subtitle"
] | python | test |
mikekatz04/BOWIE | snr_calculator_folder/gwsnrcalc/gw_snr_calculator.py | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/gw_snr_calculator.py#L102-L144 | def parallel_snr_func(num, binary_args, phenomdwave, signal_type,
noise_interpolants, prefactor, verbose):
"""SNR calulation with PhenomDWaveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single process, num=0.
binary_args (tuple): Binary arguments for
:meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__`.
phenomdwave (obj): Initialized class of
:class:`gwsnrcalc.utils.waveforms.PhenomDWaveforms`.
signal_type (list of str): List with types of SNR to calculate.
Options are `all` for full wavefrom,
`ins` for inspiral, `mrg` for merger, and/or `rd` for ringdown.
noise_interpolants (dict): All the noise noise interpolants generated by
:mod:`gwsnrcalc.utils.sensitivity`.
prefactor (float): Prefactor to multiply SNR by (not SNR^2).
verbose (int): Notify each time ``verbose`` processes finish. If -1, then no notification.
Returns:
(dict): Dictionary with the SNR output from the calculation.
"""
wave = phenomdwave(*binary_args)
out_vals = {}
for key in noise_interpolants:
hn_vals = noise_interpolants[key](wave.freqs)
snr_out = csnr(wave.freqs, wave.hc, hn_vals,
wave.fmrg, wave.fpeak, prefactor=prefactor)
if len(signal_type) == 1:
out_vals[key + '_' + signal_type[0]] = snr_out[signal_type[0]]
else:
for phase in signal_type:
out_vals[key + '_' + phase] = snr_out[phase]
if verbose > 0 and (num+1) % verbose == 0:
print('Process ', (num+1), 'is finished.')
return out_vals | [
"def",
"parallel_snr_func",
"(",
"num",
",",
"binary_args",
",",
"phenomdwave",
",",
"signal_type",
",",
"noise_interpolants",
",",
"prefactor",
",",
"verbose",
")",
":",
"wave",
"=",
"phenomdwave",
"(",
"*",
"binary_args",
")",
"out_vals",
"=",
"{",
"}",
"f... | SNR calulation with PhenomDWaveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single process, num=0.
binary_args (tuple): Binary arguments for
:meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__`.
phenomdwave (obj): Initialized class of
:class:`gwsnrcalc.utils.waveforms.PhenomDWaveforms`.
signal_type (list of str): List with types of SNR to calculate.
Options are `all` for full wavefrom,
`ins` for inspiral, `mrg` for merger, and/or `rd` for ringdown.
noise_interpolants (dict): All the noise noise interpolants generated by
:mod:`gwsnrcalc.utils.sensitivity`.
prefactor (float): Prefactor to multiply SNR by (not SNR^2).
verbose (int): Notify each time ``verbose`` processes finish. If -1, then no notification.
Returns:
(dict): Dictionary with the SNR output from the calculation. | [
"SNR",
"calulation",
"with",
"PhenomDWaveforms"
] | python | train |
tBaxter/tango-comments | build/lib/tango_comments/forms.py | https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L55-L60 | def clean_timestamp(self):
"""Make sure the timestamp isn't too far (> 2 hours) in the past."""
ts = self.cleaned_data["timestamp"]
if time.time() - ts > (2 * 60 * 60):
raise forms.ValidationError("Timestamp check failed")
return ts | [
"def",
"clean_timestamp",
"(",
"self",
")",
":",
"ts",
"=",
"self",
".",
"cleaned_data",
"[",
"\"timestamp\"",
"]",
"if",
"time",
".",
"time",
"(",
")",
"-",
"ts",
">",
"(",
"2",
"*",
"60",
"*",
"60",
")",
":",
"raise",
"forms",
".",
"ValidationErr... | Make sure the timestamp isn't too far (> 2 hours) in the past. | [
"Make",
"sure",
"the",
"timestamp",
"isn",
"t",
"too",
"far",
"(",
">",
"2",
"hours",
")",
"in",
"the",
"past",
"."
] | python | train |
jilljenn/tryalgo | tryalgo/knuth_morris_pratt.py | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/knuth_morris_pratt.py#L10-L26 | def maximum_border_length(w):
"""Maximum string borders by Knuth-Morris-Pratt
:param w: string
:returns: table f such that f[i] is the longest border length of w[:i + 1]
:complexity: linear
"""
n = len(w)
f = [0] * n # init f[0] = 0
k = 0 # current longest border length
for i in range(1, n): # compute f[i]
while w[k] != w[i] and k > 0:
k = f[k - 1] # try shorter lengths
if w[k] == w[i]: # last caracters match
k += 1 # we can increment the border length
f[i] = k # we found the maximal border of w[:i + 1]
return f | [
"def",
"maximum_border_length",
"(",
"w",
")",
":",
"n",
"=",
"len",
"(",
"w",
")",
"f",
"=",
"[",
"0",
"]",
"*",
"n",
"# init f[0] = 0",
"k",
"=",
"0",
"# current longest border length",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"# ... | Maximum string borders by Knuth-Morris-Pratt
:param w: string
:returns: table f such that f[i] is the longest border length of w[:i + 1]
:complexity: linear | [
"Maximum",
"string",
"borders",
"by",
"Knuth",
"-",
"Morris",
"-",
"Pratt"
] | python | train |
wandb/client | wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py#L289-L299 | def _nodes_to_values(self):
"""
Returns list of list of (Node, string_value) tuples.
"""
def is_none(slice):
return slice[0] == -1 and slice[1] == -1
def get(slice):
return self.string[slice[0]:slice[1]]
return [(varname, get(slice), slice) for varname, slice in self._nodes_to_regs() if not is_none(slice)] | [
"def",
"_nodes_to_values",
"(",
"self",
")",
":",
"def",
"is_none",
"(",
"slice",
")",
":",
"return",
"slice",
"[",
"0",
"]",
"==",
"-",
"1",
"and",
"slice",
"[",
"1",
"]",
"==",
"-",
"1",
"def",
"get",
"(",
"slice",
")",
":",
"return",
"self",
... | Returns list of list of (Node, string_value) tuples. | [
"Returns",
"list",
"of",
"list",
"of",
"(",
"Node",
"string_value",
")",
"tuples",
"."
] | python | train |
limix/bgen-reader-py | libpath.py | https://github.com/limix/bgen-reader-py/blob/3f66a39e15a71b981e8c5f887a4adc3ad486a45f/libpath.py#L109-L119 | def find_libname(self, name):
"""Try to infer the correct library name."""
names = ["{}.lib", "lib{}.lib", "{}lib.lib"]
names = [n.format(name) for n in names]
dirs = self.get_library_dirs()
for d in dirs:
for n in names:
if exists(join(d, n)):
return n[:-4]
msg = "Could not find the {} library.".format(name)
raise ValueError(msg) | [
"def",
"find_libname",
"(",
"self",
",",
"name",
")",
":",
"names",
"=",
"[",
"\"{}.lib\"",
",",
"\"lib{}.lib\"",
",",
"\"{}lib.lib\"",
"]",
"names",
"=",
"[",
"n",
".",
"format",
"(",
"name",
")",
"for",
"n",
"in",
"names",
"]",
"dirs",
"=",
"self",... | Try to infer the correct library name. | [
"Try",
"to",
"infer",
"the",
"correct",
"library",
"name",
"."
] | python | valid |
pantsbuild/pants | src/python/pants/java/nailgun_protocol.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_protocol.py#L302-L304 | def send_stderr(cls, sock, payload):
"""Send the Stderr chunk over the specified socket."""
cls.write_chunk(sock, ChunkType.STDERR, payload) | [
"def",
"send_stderr",
"(",
"cls",
",",
"sock",
",",
"payload",
")",
":",
"cls",
".",
"write_chunk",
"(",
"sock",
",",
"ChunkType",
".",
"STDERR",
",",
"payload",
")"
] | Send the Stderr chunk over the specified socket. | [
"Send",
"the",
"Stderr",
"chunk",
"over",
"the",
"specified",
"socket",
"."
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/speech_to_text_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/speech_to_text_v1.py#L4858-L4870 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'transcript') and self.transcript is not None:
_dict['transcript'] = self.transcript
if hasattr(self, 'confidence') and self.confidence is not None:
_dict['confidence'] = self.confidence
if hasattr(self, 'timestamps') and self.timestamps is not None:
_dict['timestamps'] = self.timestamps
if hasattr(self,
'word_confidence') and self.word_confidence is not None:
_dict['word_confidence'] = self.word_confidence
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'transcript'",
")",
"and",
"self",
".",
"transcript",
"is",
"not",
"None",
":",
"_dict",
"[",
"'transcript'",
"]",
"=",
"self",
".",
"transcript",
"... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
notifiers/notifiers | notifiers/utils/schema/formats.py | https://github.com/notifiers/notifiers/blob/6dd8aafff86935dbb4763db9c56f9cdd7fc08b65/notifiers/utils/schema/formats.py#L25-L29 | def is_iso8601(instance: str):
"""Validates ISO8601 format"""
if not isinstance(instance, str):
return True
return ISO8601.match(instance) is not None | [
"def",
"is_iso8601",
"(",
"instance",
":",
"str",
")",
":",
"if",
"not",
"isinstance",
"(",
"instance",
",",
"str",
")",
":",
"return",
"True",
"return",
"ISO8601",
".",
"match",
"(",
"instance",
")",
"is",
"not",
"None"
] | Validates ISO8601 format | [
"Validates",
"ISO8601",
"format"
] | python | train |
bspaans/python-mingus | mingus/midi/pyfluidsynth.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L242-L256 | def cc(self, chan, ctrl, val):
"""Send control change value.
The controls that are recognized are dependent on the
SoundFont. Values are always 0 to 127. Typical controls
include:
1: vibrato
7: volume
10: pan (left to right)
11: expression (soft to loud)
64: sustain
91: reverb
93: chorus
"""
return fluid_synth_cc(self.synth, chan, ctrl, val) | [
"def",
"cc",
"(",
"self",
",",
"chan",
",",
"ctrl",
",",
"val",
")",
":",
"return",
"fluid_synth_cc",
"(",
"self",
".",
"synth",
",",
"chan",
",",
"ctrl",
",",
"val",
")"
] | Send control change value.
The controls that are recognized are dependent on the
SoundFont. Values are always 0 to 127. Typical controls
include:
1: vibrato
7: volume
10: pan (left to right)
11: expression (soft to loud)
64: sustain
91: reverb
93: chorus | [
"Send",
"control",
"change",
"value",
"."
] | python | train |
streamlink/streamlink | src/streamlink/plugin/api/validate.py | https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/plugin/api/validate.py#L109-L118 | def length(length):
"""Checks value for minimum length using len()."""
def min_len(value):
if not len(value) >= length:
raise ValueError(
"Minimum length is {0} but value is {1}".format(length, len(value))
)
return True
return min_len | [
"def",
"length",
"(",
"length",
")",
":",
"def",
"min_len",
"(",
"value",
")",
":",
"if",
"not",
"len",
"(",
"value",
")",
">=",
"length",
":",
"raise",
"ValueError",
"(",
"\"Minimum length is {0} but value is {1}\"",
".",
"format",
"(",
"length",
",",
"le... | Checks value for minimum length using len(). | [
"Checks",
"value",
"for",
"minimum",
"length",
"using",
"len",
"()",
"."
] | python | test |
DistrictDataLabs/yellowbrick | yellowbrick/regressor/residuals.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/regressor/residuals.py#L456-L474 | def fit(self, X, y, **kwargs):
"""
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n
An array or series of target values
kwargs: keyword arguments passed to Scikit-Learn API.
Returns
-------
self : visualizer instance
"""
super(ResidualsPlot, self).fit(X, y, **kwargs)
self.score(X, y, train=True)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"ResidualsPlot",
",",
"self",
")",
".",
"fit",
"(",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"score",
"(",
"X",
",",
"y",
",",
... | Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n
An array or series of target values
kwargs: keyword arguments passed to Scikit-Learn API.
Returns
-------
self : visualizer instance | [
"Parameters",
"----------",
"X",
":",
"ndarray",
"or",
"DataFrame",
"of",
"shape",
"n",
"x",
"m",
"A",
"matrix",
"of",
"n",
"instances",
"with",
"m",
"features"
] | python | train |
koenedaele/skosprovider | skosprovider/skos.py | https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/skos.py#L596-L615 | def dict_to_note(dict):
'''
Transform a dict with keys `note`, `type` and `language` into a
:class:`Note`.
Only the `note` key is mandatory. If `type` is not present, it will
default to `note`. If `language` is not present, it will default to `und`.
If `markup` is not present it will default to `None`.
If the argument passed is already a :class:`Note`, this method just returns
the argument.
'''
if isinstance(dict, Note):
return dict
return Note(
dict['note'],
dict.get('type', 'note'),
dict.get('language', 'und'),
dict.get('markup')
) | [
"def",
"dict_to_note",
"(",
"dict",
")",
":",
"if",
"isinstance",
"(",
"dict",
",",
"Note",
")",
":",
"return",
"dict",
"return",
"Note",
"(",
"dict",
"[",
"'note'",
"]",
",",
"dict",
".",
"get",
"(",
"'type'",
",",
"'note'",
")",
",",
"dict",
".",... | Transform a dict with keys `note`, `type` and `language` into a
:class:`Note`.
Only the `note` key is mandatory. If `type` is not present, it will
default to `note`. If `language` is not present, it will default to `und`.
If `markup` is not present it will default to `None`.
If the argument passed is already a :class:`Note`, this method just returns
the argument. | [
"Transform",
"a",
"dict",
"with",
"keys",
"note",
"type",
"and",
"language",
"into",
"a",
":",
"class",
":",
"Note",
"."
] | python | valid |
JukeboxPipeline/jukebox-core | src/jukeboxcore/plugins.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/plugins.py#L94-L104 | def _unload(self, ):
"""Unloads the plugin
:raises: errors.PluginUninitError
"""
try:
self.uninit()
except Exception as e:
log.exception("Unload failed!")
raise errors.PluginUninitError('%s' % e)
self.__status = self.__UNLOADED | [
"def",
"_unload",
"(",
"self",
",",
")",
":",
"try",
":",
"self",
".",
"uninit",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"\"Unload failed!\"",
")",
"raise",
"errors",
".",
"PluginUninitError",
"(",
"'%s'",
"%",
"e... | Unloads the plugin
:raises: errors.PluginUninitError | [
"Unloads",
"the",
"plugin"
] | python | train |
swharden/SWHLab | doc/uses/EPSCs-and-IPSCs/smooth histogram method/01.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/uses/EPSCs-and-IPSCs/smooth histogram method/01.py#L19-L28 | def kernel_gaussian(size=100, sigma=None, forwardOnly=False):
"""
return a 1d gassuan array of a given size and sigma.
If sigma isn't given, it will be 1/10 of the size, which is usually good.
"""
if sigma is None:sigma=size/10
points=np.exp(-np.power(np.arange(size)-size/2,2)/(2*np.power(sigma,2)))
if forwardOnly:
points[:int(len(points)/2)]=0
return points/sum(points) | [
"def",
"kernel_gaussian",
"(",
"size",
"=",
"100",
",",
"sigma",
"=",
"None",
",",
"forwardOnly",
"=",
"False",
")",
":",
"if",
"sigma",
"is",
"None",
":",
"sigma",
"=",
"size",
"/",
"10",
"points",
"=",
"np",
".",
"exp",
"(",
"-",
"np",
".",
"po... | return a 1d gassuan array of a given size and sigma.
If sigma isn't given, it will be 1/10 of the size, which is usually good. | [
"return",
"a",
"1d",
"gassuan",
"array",
"of",
"a",
"given",
"size",
"and",
"sigma",
".",
"If",
"sigma",
"isn",
"t",
"given",
"it",
"will",
"be",
"1",
"/",
"10",
"of",
"the",
"size",
"which",
"is",
"usually",
"good",
"."
] | python | valid |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/state.py#L336-L345 | def show_content(self, with_content=False):
"""Checks if the state is a library with the `show_content` flag set
:param with_content: If this parameter is `True`, the method return only True if the library represents a
ContainerState
:return: Whether the content of a library state is shown
"""
if isinstance(self.model, LibraryStateModel) and self.model.show_content():
return not with_content or isinstance(self.model.state_copy, ContainerStateModel)
return False | [
"def",
"show_content",
"(",
"self",
",",
"with_content",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"model",
",",
"LibraryStateModel",
")",
"and",
"self",
".",
"model",
".",
"show_content",
"(",
")",
":",
"return",
"not",
"with_content",... | Checks if the state is a library with the `show_content` flag set
:param with_content: If this parameter is `True`, the method return only True if the library represents a
ContainerState
:return: Whether the content of a library state is shown | [
"Checks",
"if",
"the",
"state",
"is",
"a",
"library",
"with",
"the",
"show_content",
"flag",
"set"
] | python | train |
optimizely/python-sdk | optimizely/event_builder.py | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/event_builder.py#L109-L138 | def _get_common_params(self, user_id, attributes):
""" Get params which are used same in both conversion and impression events.
Args:
user_id: ID for user.
attributes: Dict representing user attributes and values which need to be recorded.
Returns:
Dict consisting of parameters common to both impression and conversion events.
"""
commonParams = {}
commonParams[self.EventParams.PROJECT_ID] = self._get_project_id()
commonParams[self.EventParams.ACCOUNT_ID] = self._get_account_id()
visitor = {}
visitor[self.EventParams.END_USER_ID] = user_id
visitor[self.EventParams.SNAPSHOTS] = []
commonParams[self.EventParams.USERS] = []
commonParams[self.EventParams.USERS].append(visitor)
commonParams[self.EventParams.USERS][0][self.EventParams.ATTRIBUTES] = self._get_attributes(attributes)
commonParams[self.EventParams.SOURCE_SDK_TYPE] = 'python-sdk'
commonParams[self.EventParams.ENRICH_DECISIONS] = True
commonParams[self.EventParams.SOURCE_SDK_VERSION] = version.__version__
commonParams[self.EventParams.ANONYMIZE_IP] = self._get_anonymize_ip()
commonParams[self.EventParams.REVISION] = self._get_revision()
return commonParams | [
"def",
"_get_common_params",
"(",
"self",
",",
"user_id",
",",
"attributes",
")",
":",
"commonParams",
"=",
"{",
"}",
"commonParams",
"[",
"self",
".",
"EventParams",
".",
"PROJECT_ID",
"]",
"=",
"self",
".",
"_get_project_id",
"(",
")",
"commonParams",
"[",... | Get params which are used same in both conversion and impression events.
Args:
user_id: ID for user.
attributes: Dict representing user attributes and values which need to be recorded.
Returns:
Dict consisting of parameters common to both impression and conversion events. | [
"Get",
"params",
"which",
"are",
"used",
"same",
"in",
"both",
"conversion",
"and",
"impression",
"events",
"."
] | python | train |
photo/openphoto-python | trovebox/http.py | https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/http.py#L196-L202 | def _process_params(self, params):
""" Converts Unicode/lists/booleans inside HTTP parameters """
processed_params = {}
for key, value in params.items():
processed_params[key] = self._process_param_value(value)
return processed_params | [
"def",
"_process_params",
"(",
"self",
",",
"params",
")",
":",
"processed_params",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
":",
"processed_params",
"[",
"key",
"]",
"=",
"self",
".",
"_process_param_value",
"("... | Converts Unicode/lists/booleans inside HTTP parameters | [
"Converts",
"Unicode",
"/",
"lists",
"/",
"booleans",
"inside",
"HTTP",
"parameters"
] | python | train |
WoLpH/python-statsd | statsd/connection.py | https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/connection.py#L47-L81 | def send(self, data, sample_rate=None):
'''Send the data over UDP while taking the sample_rate in account
The sample rate should be a number between `0` and `1` which indicates
the probability that a message will be sent. The sample_rate is also
communicated to `statsd` so it knows what multiplier to use.
:keyword data: The data to send
:type data: dict
:keyword sample_rate: The sample rate, defaults to `1` (meaning always)
:type sample_rate: int
'''
if self._disabled:
self.logger.debug('Connection disabled, not sending data')
return False
if sample_rate is None:
sample_rate = self._sample_rate
sampled_data = {}
if sample_rate < 1:
if random.random() <= sample_rate:
# Modify the data so statsd knows our sample_rate
for stat, value in compat.iter_dict(data):
sampled_data[stat] = '%s|@%s' % (data[stat], sample_rate)
else:
sampled_data = data
try:
for stat, value in compat.iter_dict(sampled_data):
send_data = ('%s:%s' % (stat, value)).encode("utf-8")
self.udp_sock.send(send_data)
return True
except Exception as e:
self.logger.exception('unexpected error %r while sending data', e)
return False | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"sample_rate",
"=",
"None",
")",
":",
"if",
"self",
".",
"_disabled",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Connection disabled, not sending data'",
")",
"return",
"False",
"if",
"sample_rate",
"is",
... | Send the data over UDP while taking the sample_rate in account
The sample rate should be a number between `0` and `1` which indicates
the probability that a message will be sent. The sample_rate is also
communicated to `statsd` so it knows what multiplier to use.
:keyword data: The data to send
:type data: dict
:keyword sample_rate: The sample rate, defaults to `1` (meaning always)
:type sample_rate: int | [
"Send",
"the",
"data",
"over",
"UDP",
"while",
"taking",
"the",
"sample_rate",
"in",
"account"
] | python | train |
log2timeline/plaso | plaso/lib/objectfilter.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/lib/objectfilter.py#L782-L788 | def InsertFloatArg(self, string='', **unused_kwargs):
"""Inserts a Float argument."""
try:
float_value = float(string)
except (TypeError, ValueError):
raise errors.ParseError('{0:s} is not a valid float.'.format(string))
return self.InsertArg(float_value) | [
"def",
"InsertFloatArg",
"(",
"self",
",",
"string",
"=",
"''",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"try",
":",
"float_value",
"=",
"float",
"(",
"string",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"errors",
".",
"Par... | Inserts a Float argument. | [
"Inserts",
"a",
"Float",
"argument",
"."
] | python | train |
ulule/django-linguist | linguist/metaclasses.py | https://github.com/ulule/django-linguist/blob/d2b95a6ab921039d56d5eeb352badfe5be9e8f77/linguist/metaclasses.py#L41-L59 | def default_value_getter(field):
"""
When accessing to the name of the field itself, the value
in the current language will be returned. Unless it's set,
the value in the default language will be returned.
"""
def default_value_func_getter(self):
localized_field = utils.build_localized_field_name(
field, self._linguist.active_language
)
value = getattr(self, localized_field)
if value:
return value
default_field = utils.build_localized_field_name(field, self.default_language)
return getattr(self, default_field)
return default_value_func_getter | [
"def",
"default_value_getter",
"(",
"field",
")",
":",
"def",
"default_value_func_getter",
"(",
"self",
")",
":",
"localized_field",
"=",
"utils",
".",
"build_localized_field_name",
"(",
"field",
",",
"self",
".",
"_linguist",
".",
"active_language",
")",
"value",... | When accessing to the name of the field itself, the value
in the current language will be returned. Unless it's set,
the value in the default language will be returned. | [
"When",
"accessing",
"to",
"the",
"name",
"of",
"the",
"field",
"itself",
"the",
"value",
"in",
"the",
"current",
"language",
"will",
"be",
"returned",
".",
"Unless",
"it",
"s",
"set",
"the",
"value",
"in",
"the",
"default",
"language",
"will",
"be",
"re... | python | train |
django-xxx/django-mobi2 | mobi2/middleware.py | https://github.com/django-xxx/django-mobi2/blob/7ac323faa1a9599f3cd39acd3c49626819ce0538/mobi2/middleware.py#L26-L64 | def process_request(request):
"""Adds a "mobile" attribute to the request which is True or False
depending on whether the request should be considered to come from a
small-screen device such as a phone or a PDA"""
if 'HTTP_X_OPERAMINI_FEATURES' in request.META:
# Then it's running opera mini. 'Nuff said.
# Reference from:
# http://dev.opera.com/articles/view/opera-mini-request-headers/
request.mobile = True
return None
if 'HTTP_ACCEPT' in request.META:
s = request.META['HTTP_ACCEPT'].lower()
if 'application/vnd.wap.xhtml+xml' in s:
# Then it's a wap browser
request.mobile = True
return None
if 'HTTP_USER_AGENT' in request.META:
# This takes the most processing. Surprisingly enough, when I
# Experimented on my own machine, this was the most efficient
# algorithm. Certainly more so than regexes.
# Also, Caching didn't help much, with real-world caches.
s = request.META['HTTP_USER_AGENT'].lower()
for ua in search_strings:
if ua in s:
# check if we are ignoring this user agent: (IPad)
if not ignore_user_agent(s):
request.mobile = True
if MOBI_DETECT_TABLET:
request.tablet = _is_tablet(s)
return None
# Otherwise it's not a mobile
request.mobile = False
request.tablet = False
return None | [
"def",
"process_request",
"(",
"request",
")",
":",
"if",
"'HTTP_X_OPERAMINI_FEATURES'",
"in",
"request",
".",
"META",
":",
"# Then it's running opera mini. 'Nuff said.",
"# Reference from:",
"# http://dev.opera.com/articles/view/opera-mini-request-headers/",
"request",
".",
"mob... | Adds a "mobile" attribute to the request which is True or False
depending on whether the request should be considered to come from a
small-screen device such as a phone or a PDA | [
"Adds",
"a",
"mobile",
"attribute",
"to",
"the",
"request",
"which",
"is",
"True",
"or",
"False",
"depending",
"on",
"whether",
"the",
"request",
"should",
"be",
"considered",
"to",
"come",
"from",
"a",
"small",
"-",
"screen",
"device",
"such",
"as",
"a",
... | python | train |
jakevdp/lpproj | lpproj/lpproj.py | https://github.com/jakevdp/lpproj/blob/9c9042b0c2d16c153b53dcc0a759c7fe8c272176/lpproj/lpproj.py#L105-L173 | def eigh_robust(a, b=None, eigvals=None, eigvals_only=False,
overwrite_a=False, overwrite_b=False,
turbo=True, check_finite=True):
"""Robustly solve the Hermitian generalized eigenvalue problem
This function robustly solves the Hermetian generalized eigenvalue problem
``A v = lambda B v`` in the case that B is not strictly positive definite.
When B is strictly positive-definite, the result is equivalent to
scipy.linalg.eigh() within floating-point accuracy.
Parameters
----------
a : (M, M) array_like
A complex Hermitian or real symmetric matrix whose eigenvalues and
eigenvectors will be computed.
b : (M, M) array_like, optional
A complex Hermitian or real symmetric matrix.
If omitted, identity matrix is assumed.
eigvals : tuple (lo, hi), optional
Indexes of the smallest and largest (in ascending order) eigenvalues
and corresponding eigenvectors to be returned: 0 <= lo <= hi <= M-1.
If omitted, all eigenvalues and eigenvectors are returned.
eigvals_only : bool, optional
Whether to calculate only eigenvalues and no eigenvectors.
(Default: both are calculated)
turbo : bool, optional
Use divide and conquer algorithm (faster but expensive in memory,
only for generalized eigenvalue problem and if eigvals=None)
overwrite_a : bool, optional
Whether to overwrite data in `a` (may improve performance)
overwrite_b : bool, optional
Whether to overwrite data in `b` (may improve performance)
check_finite : bool, optional
Whether to check that the input matrices contain only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Returns
-------
w : (N,) float ndarray
The N (1<=N<=M) selected eigenvalues, in ascending order, each
repeated according to its multiplicity.
v : (M, N) complex ndarray
(if eigvals_only == False)
"""
kwargs = dict(eigvals=eigvals, eigvals_only=eigvals_only,
turbo=turbo, check_finite=check_finite,
overwrite_a=overwrite_a, overwrite_b=overwrite_b)
# Check for easy case first:
if b is None:
return linalg.eigh(a, **kwargs)
# Compute eigendecomposition of b
kwargs_b = dict(turbo=turbo, check_finite=check_finite,
overwrite_a=overwrite_b) # b is a for this operation
S, U = linalg.eigh(b, **kwargs_b)
# Combine a and b on left hand side via decomposition of b
S[S <= 0] = np.inf
Sinv = 1. / np.sqrt(S)
W = Sinv[:, None] * np.dot(U.T, np.dot(a, U)) * Sinv
output = linalg.eigh(W, **kwargs)
if eigvals_only:
return output
else:
evals, evecs = output
return evals, np.dot(U, Sinv[:, None] * evecs) | [
"def",
"eigh_robust",
"(",
"a",
",",
"b",
"=",
"None",
",",
"eigvals",
"=",
"None",
",",
"eigvals_only",
"=",
"False",
",",
"overwrite_a",
"=",
"False",
",",
"overwrite_b",
"=",
"False",
",",
"turbo",
"=",
"True",
",",
"check_finite",
"=",
"True",
")",... | Robustly solve the Hermitian generalized eigenvalue problem
This function robustly solves the Hermetian generalized eigenvalue problem
``A v = lambda B v`` in the case that B is not strictly positive definite.
When B is strictly positive-definite, the result is equivalent to
scipy.linalg.eigh() within floating-point accuracy.
Parameters
----------
a : (M, M) array_like
A complex Hermitian or real symmetric matrix whose eigenvalues and
eigenvectors will be computed.
b : (M, M) array_like, optional
A complex Hermitian or real symmetric matrix.
If omitted, identity matrix is assumed.
eigvals : tuple (lo, hi), optional
Indexes of the smallest and largest (in ascending order) eigenvalues
and corresponding eigenvectors to be returned: 0 <= lo <= hi <= M-1.
If omitted, all eigenvalues and eigenvectors are returned.
eigvals_only : bool, optional
Whether to calculate only eigenvalues and no eigenvectors.
(Default: both are calculated)
turbo : bool, optional
Use divide and conquer algorithm (faster but expensive in memory,
only for generalized eigenvalue problem and if eigvals=None)
overwrite_a : bool, optional
Whether to overwrite data in `a` (may improve performance)
overwrite_b : bool, optional
Whether to overwrite data in `b` (may improve performance)
check_finite : bool, optional
Whether to check that the input matrices contain only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Returns
-------
w : (N,) float ndarray
The N (1<=N<=M) selected eigenvalues, in ascending order, each
repeated according to its multiplicity.
v : (M, N) complex ndarray
(if eigvals_only == False) | [
"Robustly",
"solve",
"the",
"Hermitian",
"generalized",
"eigenvalue",
"problem"
] | python | train |
alevinval/scheduling | scheduling/graph.py | https://github.com/alevinval/scheduling/blob/127239712c0b73b929ca19b4b5c2855eebb7fcf0/scheduling/graph.py#L60-L67 | def depends(self, *nodes):
""" Adds nodes as relatives to this one, and
updates the relatives with self as children.
:param nodes: GraphNode(s)
"""
for node in nodes:
self.add_relative(node)
node.add_children(self) | [
"def",
"depends",
"(",
"self",
",",
"*",
"nodes",
")",
":",
"for",
"node",
"in",
"nodes",
":",
"self",
".",
"add_relative",
"(",
"node",
")",
"node",
".",
"add_children",
"(",
"self",
")"
] | Adds nodes as relatives to this one, and
updates the relatives with self as children.
:param nodes: GraphNode(s) | [
"Adds",
"nodes",
"as",
"relatives",
"to",
"this",
"one",
"and",
"updates",
"the",
"relatives",
"with",
"self",
"as",
"children",
".",
":",
"param",
"nodes",
":",
"GraphNode",
"(",
"s",
")"
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/gloo/gl/_pyopengl2.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/gl/_pyopengl2.py#L22-L30 | def glBufferData(target, data, usage):
""" Data can be numpy array or the size of data to allocate.
"""
if isinstance(data, int):
size = data
data = None
else:
size = data.nbytes
GL.glBufferData(target, size, data, usage) | [
"def",
"glBufferData",
"(",
"target",
",",
"data",
",",
"usage",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"size",
"=",
"data",
"data",
"=",
"None",
"else",
":",
"size",
"=",
"data",
".",
"nbytes",
"GL",
".",
"glBufferData",
... | Data can be numpy array or the size of data to allocate. | [
"Data",
"can",
"be",
"numpy",
"array",
"or",
"the",
"size",
"of",
"data",
"to",
"allocate",
"."
] | python | train |
psd-tools/psd-tools | src/psd_tools/api/pil_io.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L120-L138 | def convert_mask_to_pil(mask, real=True):
"""Convert Mask to PIL Image."""
from PIL import Image
header = mask._layer._psd._record.header
channel_ids = [ci.id for ci in mask._layer._record.channel_info]
if real and mask._has_real():
width = mask._data.real_right - mask._data.real_left
height = mask._data.real_bottom - mask._data.real_top
channel = mask._layer._channels[
channel_ids.index(ChannelID.REAL_USER_LAYER_MASK)
]
else:
width = mask._data.right - mask._data.left
height = mask._data.bottom - mask._data.top
channel = mask._layer._channels[
channel_ids.index(ChannelID.USER_LAYER_MASK)
]
data = channel.get_data(width, height, header.depth, header.version)
return _create_channel((width, height), data, header.depth) | [
"def",
"convert_mask_to_pil",
"(",
"mask",
",",
"real",
"=",
"True",
")",
":",
"from",
"PIL",
"import",
"Image",
"header",
"=",
"mask",
".",
"_layer",
".",
"_psd",
".",
"_record",
".",
"header",
"channel_ids",
"=",
"[",
"ci",
".",
"id",
"for",
"ci",
... | Convert Mask to PIL Image. | [
"Convert",
"Mask",
"to",
"PIL",
"Image",
"."
] | python | train |
lsbardel/python-stdnet | stdnet/backends/redisb/__init__.py | https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/backends/redisb/__init__.py#L346-L363 | def related_lua_args(self):
'''Generator of load_related arguments'''
related = self.queryelem.select_related
if related:
meta = self.meta
for rel in related:
field = meta.dfields[rel]
relmodel = field.relmodel
bk = self.backend.basekey(relmodel._meta) if relmodel else ''
fields = list(related[rel])
if meta.pkname() in fields:
fields.remove(meta.pkname())
if not fields:
fields.append('')
ftype = field.type if field in meta.multifields else ''
data = {'field': field.attname, 'type': ftype,
'bk': bk, 'fields': fields}
yield field.name, data | [
"def",
"related_lua_args",
"(",
"self",
")",
":",
"related",
"=",
"self",
".",
"queryelem",
".",
"select_related",
"if",
"related",
":",
"meta",
"=",
"self",
".",
"meta",
"for",
"rel",
"in",
"related",
":",
"field",
"=",
"meta",
".",
"dfields",
"[",
"r... | Generator of load_related arguments | [
"Generator",
"of",
"load_related",
"arguments"
] | python | train |
jonathf/chaospy | chaospy/bertran/operators.py | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/operators.py#L291-L330 | def olindex(order, dim):
"""
Create an lexiographical sorted basis for a given order.
Examples
--------
>>> chaospy.bertran.olindex(3, 2)
array([[0, 3],
[1, 2],
[2, 1],
[3, 0]])
"""
idxm = [0]*dim
out = []
def _olindex(idx):
"""Recursive backend for olindex."""
if numpy.sum(idxm) == order:
out.append(idxm[:])
return
if idx == dim:
return
idxm_sum = numpy.sum(idxm)
idx_saved = idxm[idx]
for idxi in range(order - numpy.sum(idxm) + 1):
idxm[idx] = idxi
if idxm_sum < order:
_olindex(idx+1)
else:
break
idxm[idx] = idx_saved
_olindex(0)
return numpy.array(out) | [
"def",
"olindex",
"(",
"order",
",",
"dim",
")",
":",
"idxm",
"=",
"[",
"0",
"]",
"*",
"dim",
"out",
"=",
"[",
"]",
"def",
"_olindex",
"(",
"idx",
")",
":",
"\"\"\"Recursive backend for olindex.\"\"\"",
"if",
"numpy",
".",
"sum",
"(",
"idxm",
")",
"=... | Create an lexiographical sorted basis for a given order.
Examples
--------
>>> chaospy.bertran.olindex(3, 2)
array([[0, 3],
[1, 2],
[2, 1],
[3, 0]]) | [
"Create",
"an",
"lexiographical",
"sorted",
"basis",
"for",
"a",
"given",
"order",
"."
] | python | train |
matttproud/python_quantile_estimation | com/matttproud/quantile/__init__.py | https://github.com/matttproud/python_quantile_estimation/blob/698c329077805375d2a5e4191ec4709289150fd6/com/matttproud/quantile/__init__.py#L99-L118 | def _replace_batch(self):
"""Incorporates all pending values into the estimator."""
if not self._head:
self._head, self._buffer = self._record(self._buffer[0], 1, 0, None), self._buffer[1:]
rank = 0.0
current = self._head
for b in self._buffer:
if b < self._head._value:
self._head = self._record(b, 1, 0, self._head)
while current._successor and current._value < b:
rank += current._rank
current = current._successor
if not current._successor:
current._successor = self._record(b, 1, 0, None)
current._successor = self._record(b, 1, self._invariant(rank, self._observations)-1, current._successor) | [
"def",
"_replace_batch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_head",
":",
"self",
".",
"_head",
",",
"self",
".",
"_buffer",
"=",
"self",
".",
"_record",
"(",
"self",
".",
"_buffer",
"[",
"0",
"]",
",",
"1",
",",
"0",
",",
"None",
... | Incorporates all pending values into the estimator. | [
"Incorporates",
"all",
"pending",
"values",
"into",
"the",
"estimator",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/psutil/__init__.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L868-L926 | def cpu_percent(interval=0.1, percpu=False):
"""Return a float representing the current system-wide CPU
utilization as a percentage.
When interval is > 0.0 compares system CPU times elapsed before
and after the interval (blocking).
When interval is 0.0 or None compares system CPU times elapsed
since last call or module import, returning immediately.
In this case is recommended for accuracy that this function be
called with at least 0.1 seconds between calls.
When percpu is True returns a list of floats representing the
utilization as a percentage for each CPU.
First element of the list refers to first CPU, second element
to second CPU and so on.
The order of the list is consistent across calls.
"""
global _last_cpu_times
global _last_per_cpu_times
blocking = interval is not None and interval > 0.0
def calculate(t1, t2):
t1_all = sum(t1)
t1_busy = t1_all - t1.idle
t2_all = sum(t2)
t2_busy = t2_all - t2.idle
# this usually indicates a float precision issue
if t2_busy <= t1_busy:
return 0.0
busy_delta = t2_busy - t1_busy
all_delta = t2_all - t1_all
busy_perc = (busy_delta / all_delta) * 100
return round(busy_perc, 1)
# system-wide usage
if not percpu:
if blocking:
t1 = cpu_times()
time.sleep(interval)
else:
t1 = _last_cpu_times
_last_cpu_times = cpu_times()
return calculate(t1, _last_cpu_times)
# per-cpu usage
else:
ret = []
if blocking:
tot1 = cpu_times(percpu=True)
time.sleep(interval)
else:
tot1 = _last_per_cpu_times
_last_per_cpu_times = cpu_times(percpu=True)
for t1, t2 in zip(tot1, _last_per_cpu_times):
ret.append(calculate(t1, t2))
return ret | [
"def",
"cpu_percent",
"(",
"interval",
"=",
"0.1",
",",
"percpu",
"=",
"False",
")",
":",
"global",
"_last_cpu_times",
"global",
"_last_per_cpu_times",
"blocking",
"=",
"interval",
"is",
"not",
"None",
"and",
"interval",
">",
"0.0",
"def",
"calculate",
"(",
... | Return a float representing the current system-wide CPU
utilization as a percentage.
When interval is > 0.0 compares system CPU times elapsed before
and after the interval (blocking).
When interval is 0.0 or None compares system CPU times elapsed
since last call or module import, returning immediately.
In this case is recommended for accuracy that this function be
called with at least 0.1 seconds between calls.
When percpu is True returns a list of floats representing the
utilization as a percentage for each CPU.
First element of the list refers to first CPU, second element
to second CPU and so on.
The order of the list is consistent across calls. | [
"Return",
"a",
"float",
"representing",
"the",
"current",
"system",
"-",
"wide",
"CPU",
"utilization",
"as",
"a",
"percentage",
"."
] | python | test |
rigetti/pyquil | pyquil/noise.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/noise.py#L202-L217 | def _create_kraus_pragmas(name, qubit_indices, kraus_ops):
"""
Generate the pragmas to define a Kraus map for a specific gate on some qubits.
:param str name: The name of the gate.
:param list|tuple qubit_indices: The qubits
:param list|tuple kraus_ops: The Kraus operators as matrices.
:return: A QUIL string with PRAGMA ADD-KRAUS ... statements.
:rtype: str
"""
pragmas = [Pragma("ADD-KRAUS",
[name] + list(qubit_indices),
"({})".format(" ".join(map(format_parameter, np.ravel(k)))))
for k in kraus_ops]
return pragmas | [
"def",
"_create_kraus_pragmas",
"(",
"name",
",",
"qubit_indices",
",",
"kraus_ops",
")",
":",
"pragmas",
"=",
"[",
"Pragma",
"(",
"\"ADD-KRAUS\"",
",",
"[",
"name",
"]",
"+",
"list",
"(",
"qubit_indices",
")",
",",
"\"({})\"",
".",
"format",
"(",
"\" \"",... | Generate the pragmas to define a Kraus map for a specific gate on some qubits.
:param str name: The name of the gate.
:param list|tuple qubit_indices: The qubits
:param list|tuple kraus_ops: The Kraus operators as matrices.
:return: A QUIL string with PRAGMA ADD-KRAUS ... statements.
:rtype: str | [
"Generate",
"the",
"pragmas",
"to",
"define",
"a",
"Kraus",
"map",
"for",
"a",
"specific",
"gate",
"on",
"some",
"qubits",
"."
] | python | train |
cherrypy/cheroot | cheroot/server.py | https://github.com/cherrypy/cheroot/blob/2af3b1798d66da697957480d3a8b4831a405770b/cheroot/server.py#L1682-L1700 | def bind_addr(self, value):
"""Set the interface on which to listen for connections."""
if isinstance(value, tuple) and value[0] in ('', None):
# Despite the socket module docs, using '' does not
# allow AI_PASSIVE to work. Passing None instead
# returns '0.0.0.0' like we want. In other words:
# host AI_PASSIVE result
# '' Y 192.168.x.y
# '' N 192.168.x.y
# None Y 0.0.0.0
# None N 127.0.0.1
# But since you can get the same effect with an explicit
# '0.0.0.0', we deny both the empty string and None as values.
raise ValueError(
"Host values of '' or None are not allowed. "
"Use '0.0.0.0' (IPv4) or '::' (IPv6) instead "
'to listen on all active interfaces.',
)
self._bind_addr = value | [
"def",
"bind_addr",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"tuple",
")",
"and",
"value",
"[",
"0",
"]",
"in",
"(",
"''",
",",
"None",
")",
":",
"# Despite the socket module docs, using '' does not",
"# allow AI_PASSIVE to w... | Set the interface on which to listen for connections. | [
"Set",
"the",
"interface",
"on",
"which",
"to",
"listen",
"for",
"connections",
"."
] | python | train |
django-userena-ce/django-userena-ce | userena/views.py | https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/userena/views.py#L757-L818 | def profile_list(request, page=1, template_name='userena/profile_list.html',
paginate_by=50, extra_context=None, **kwargs): # pragma: no cover
"""
Returns a list of all profiles that are public.
It's possible to disable this by changing ``USERENA_DISABLE_PROFILE_LIST``
to ``True`` in your settings.
:param page:
Integer of the active page used for pagination. Defaults to the first
page.
:param template_name:
String defining the name of the template that is used to render the
list of all users. Defaults to ``userena/list.html``.
:param paginate_by:
Integer defining the amount of displayed profiles per page. Defaults to
50 profiles per page.
:param extra_context:
Dictionary of variables that are passed on to the ``template_name``
template.
**Context**
``profile_list``
A list of profiles.
``is_paginated``
A boolean representing whether the results are paginated.
If the result is paginated. It will also contain the following variables.
``paginator``
An instance of ``django.core.paginator.Paginator``.
``page_obj``
An instance of ``django.core.paginator.Page``.
"""
warnings.warn("views.profile_list is deprecated. Use ProfileListView instead", DeprecationWarning, stacklevel=2)
try:
page = int(request.GET.get('page', None))
except (TypeError, ValueError):
page = page
if userena_settings.USERENA_DISABLE_PROFILE_LIST \
and not request.user.is_staff:
raise Http404
profile_model = get_profile_model()
queryset = profile_model.objects.get_visible_profiles(request.user)
if not extra_context: extra_context = dict()
return ProfileListView.as_view(queryset=queryset,
paginate_by=paginate_by,
page=page,
template_name=template_name,
extra_context=extra_context,
**kwargs)(request) | [
"def",
"profile_list",
"(",
"request",
",",
"page",
"=",
"1",
",",
"template_name",
"=",
"'userena/profile_list.html'",
",",
"paginate_by",
"=",
"50",
",",
"extra_context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"warnings",
".",
... | Returns a list of all profiles that are public.
It's possible to disable this by changing ``USERENA_DISABLE_PROFILE_LIST``
to ``True`` in your settings.
:param page:
Integer of the active page used for pagination. Defaults to the first
page.
:param template_name:
String defining the name of the template that is used to render the
list of all users. Defaults to ``userena/list.html``.
:param paginate_by:
Integer defining the amount of displayed profiles per page. Defaults to
50 profiles per page.
:param extra_context:
Dictionary of variables that are passed on to the ``template_name``
template.
**Context**
``profile_list``
A list of profiles.
``is_paginated``
A boolean representing whether the results are paginated.
If the result is paginated. It will also contain the following variables.
``paginator``
An instance of ``django.core.paginator.Paginator``.
``page_obj``
An instance of ``django.core.paginator.Page``. | [
"Returns",
"a",
"list",
"of",
"all",
"profiles",
"that",
"are",
"public",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/local_env.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/local_env.py#L1659-L1693 | def get_neighbors_of_site_with_index(struct, n, approach="min_dist", delta=0.1, \
cutoff=10.0):
"""
Returns the neighbors of a given site using a specific neighbor-finding
method.
Args:
struct (Structure): input structure.
n (int): index of site in Structure object for which motif type
is to be determined.
approach (str): type of neighbor-finding approach, where
"min_dist" will use the MinimumDistanceNN class,
"voronoi" the VoronoiNN class, "min_OKeeffe" the
MinimumOKeeffe class, and "min_VIRE" the MinimumVIRENN class.
delta (float): tolerance involved in neighbor finding.
cutoff (float): (large) radius to find tentative neighbors.
Returns: neighbor sites.
"""
if approach == "min_dist":
return MinimumDistanceNN(tol=delta, cutoff=cutoff).get_nn(
struct, n)
elif approach == "voronoi":
return VoronoiNN(tol=delta, cutoff=cutoff).get_nn(
struct, n)
elif approach == "min_OKeeffe":
return MinimumOKeeffeNN(tol=delta, cutoff=cutoff).get_nn(
struct, n)
elif approach == "min_VIRE":
return MinimumVIRENN(tol=delta, cutoff=cutoff).get_nn(
struct, n)
else:
raise RuntimeError("unsupported neighbor-finding method ({}).".format(
approach)) | [
"def",
"get_neighbors_of_site_with_index",
"(",
"struct",
",",
"n",
",",
"approach",
"=",
"\"min_dist\"",
",",
"delta",
"=",
"0.1",
",",
"cutoff",
"=",
"10.0",
")",
":",
"if",
"approach",
"==",
"\"min_dist\"",
":",
"return",
"MinimumDistanceNN",
"(",
"tol",
... | Returns the neighbors of a given site using a specific neighbor-finding
method.
Args:
struct (Structure): input structure.
n (int): index of site in Structure object for which motif type
is to be determined.
approach (str): type of neighbor-finding approach, where
"min_dist" will use the MinimumDistanceNN class,
"voronoi" the VoronoiNN class, "min_OKeeffe" the
MinimumOKeeffe class, and "min_VIRE" the MinimumVIRENN class.
delta (float): tolerance involved in neighbor finding.
cutoff (float): (large) radius to find tentative neighbors.
Returns: neighbor sites. | [
"Returns",
"the",
"neighbors",
"of",
"a",
"given",
"site",
"using",
"a",
"specific",
"neighbor",
"-",
"finding",
"method",
"."
] | python | train |
wavycloud/pyboto3 | pyboto3/dynamodb.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/dynamodb.py#L2186-L2655 | def put_item(TableName=None, Item=None, Expected=None, ReturnValues=None, ReturnConsumedCapacity=None, ReturnItemCollectionMetrics=None, ConditionalOperator=None, ConditionExpression=None, ExpressionAttributeNames=None, ExpressionAttributeValues=None):
"""
Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist), or replace an existing item if it has certain attribute values.
In addition to putting an item, you can also return the item's attribute values in the same operation, using the ReturnValues parameter.
When you add an item, the primary key attribute(s) are the only required attributes. Attribute values cannot be null. String and Binary type attributes must have lengths greater than zero. Set type attributes cannot be empty. Requests with empty values will be rejected with a ValidationException exception.
For more information about PutItem , see Working with Items in the Amazon DynamoDB Developer Guide .
See also: AWS API Documentation
Examples
This example adds a new item to the Music table.
Expected Output:
:example: response = client.put_item(
TableName='string',
Item={
'string': {
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
}
},
Expected={
'string': {
'Value': {
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
},
'Exists': True|False,
'ComparisonOperator': 'EQ'|'NE'|'IN'|'LE'|'LT'|'GE'|'GT'|'BETWEEN'|'NOT_NULL'|'NULL'|'CONTAINS'|'NOT_CONTAINS'|'BEGINS_WITH',
'AttributeValueList': [
{
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
},
]
}
},
ReturnValues='NONE'|'ALL_OLD'|'UPDATED_OLD'|'ALL_NEW'|'UPDATED_NEW',
ReturnConsumedCapacity='INDEXES'|'TOTAL'|'NONE',
ReturnItemCollectionMetrics='SIZE'|'NONE',
ConditionalOperator='AND'|'OR',
ConditionExpression='string',
ExpressionAttributeNames={
'string': 'string'
},
ExpressionAttributeValues={
'string': {
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
}
}
)
:type TableName: string
:param TableName: [REQUIRED]
The name of the table to contain the item.
:type Item: dict
:param Item: [REQUIRED]
A map of attribute name/value pairs, one for each attribute. Only the primary key attributes are required; you can optionally provide other attribute name-value pairs for the item.
You must provide all of the attributes for the primary key. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide both values for both the partition key and the sort key.
If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition.
For more information about primary keys, see Primary Key in the Amazon DynamoDB Developer Guide .
Each element in the Item map is an AttributeValue object.
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
S (string) --An attribute of type String. For example:
'S': 'Hello'
N (string) --An attribute of type Number. For example:
'N': '123.45'
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
B (bytes) --An attribute of type Binary. For example:
'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
SS (list) --An attribute of type String Set. For example:
'SS': ['Giraffe', 'Hippo' ,'Zebra']
(string) --
NS (list) --An attribute of type Number Set. For example:
'NS': ['42.2', '-19', '7.5', '3.14']
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
(string) --
BS (list) --An attribute of type Binary Set. For example:
'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
(bytes) --
M (dict) --An attribute of type Map. For example:
'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
L (list) --An attribute of type List. For example:
'L': ['Cookies', 'Coffee', 3.14159]
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
NULL (boolean) --An attribute of type Null. For example:
'NULL': true
BOOL (boolean) --An attribute of type Boolean. For example:
'BOOL': true
:type Expected: dict
:param Expected: This is a legacy parameter. Use ConditionExpresssion instead. For more information, see Expected in the Amazon DynamoDB Developer Guide .
(string) --
(dict) --Represents a condition to be compared with an attribute value. This condition can be used with DeleteItem , PutItem or UpdateItem operations; if the comparison evaluates to true, the operation succeeds; if not, the operation fails. You can use ExpectedAttributeValue in one of two different ways:
Use AttributeValueList to specify one or more values to compare against an attribute. Use ComparisonOperator to specify how you want to perform the comparison. If the comparison evaluates to true, then the conditional operation succeeds.
Use Value to specify a value that DynamoDB will compare against an attribute. If the values match, then ExpectedAttributeValue evaluates to true and the conditional operation succeeds. Optionally, you can also set Exists to false, indicating that you do not expect to find the attribute value in the table. In this case, the conditional operation succeeds only if the comparison evaluates to false.
Value and Exists are incompatible with AttributeValueList and ComparisonOperator . Note that if you use both sets of parameters at once, DynamoDB will return a ValidationException exception.
Value (dict) --Represents the data for the expected attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
S (string) --An attribute of type String. For example:
'S': 'Hello'
N (string) --An attribute of type Number. For example:
'N': '123.45'
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
B (bytes) --An attribute of type Binary. For example:
'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
SS (list) --An attribute of type String Set. For example:
'SS': ['Giraffe', 'Hippo' ,'Zebra']
(string) --
NS (list) --An attribute of type Number Set. For example:
'NS': ['42.2', '-19', '7.5', '3.14']
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
(string) --
BS (list) --An attribute of type Binary Set. For example:
'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
(bytes) --
M (dict) --An attribute of type Map. For example:
'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
L (list) --An attribute of type List. For example:
'L': ['Cookies', 'Coffee', 3.14159]
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
NULL (boolean) --An attribute of type Null. For example:
'NULL': true
BOOL (boolean) --An attribute of type Boolean. For example:
'BOOL': true
Exists (boolean) --Causes DynamoDB to evaluate the value before attempting a conditional operation:
If Exists is true , DynamoDB will check to see if that attribute value already exists in the table. If it is found, then the operation succeeds. If it is not found, the operation fails with a ConditionalCheckFailedException .
If Exists is false , DynamoDB assumes that the attribute value does not exist in the table. If in fact the value does not exist, then the assumption is valid and the operation succeeds. If the value is found, despite the assumption that it does not exist, the operation fails with a ConditionalCheckFailedException .
The default setting for Exists is true . If you supply a Value all by itself, DynamoDB assumes the attribute exists: You don't have to set Exists to true , because it is implied.
DynamoDB returns a ValidationException if:
Exists is true but there is no Value to check. (You expect a value to exist, but don't specify what that value is.)
Exists is false but you also provide a Value . (You cannot expect an attribute to have a value, while also expecting it not to exist.)
ComparisonOperator (string) --A comparator for evaluating attributes in the AttributeValueList . For example, equals, greater than, less than, etc.
The following comparison operators are available:
EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN
The following are descriptions of each comparison operator.
EQ : Equal. EQ is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} .
NE : Not equal. NE is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} .
LE : Less than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
LT : Less than. AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
GE : Greater than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
GT : Greater than. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
NOT_NULL : The attribute exists. NOT_NULL is supported for all data types, including lists and maps.
Note
This operator tests for the existence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NOT_NULL , the result is a Boolean true . This result is because the attribute 'a ' exists; its data type is not relevant to the NOT_NULL comparison operator.
NULL : The attribute does not exist. NULL is supported for all data types, including lists and maps.
Note
This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NULL , the result is a Boolean false . This is because the attribute 'a ' exists; its data type is not relevant to the NULL comparison operator.
CONTAINS : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating 'a CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list.
NOT_CONTAINS : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating 'a NOT CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list.
BEGINS_WITH : Checks for a prefix. AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type).
IN : Checks for matching elements in a list. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary. These attributes are compared against an existing attribute of an item. If any elements of the input are equal to the item attribute, the expression evaluates to true.
BETWEEN : Greater than or equal to the first value, and less than or equal to the second value. AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not compare to {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']}
AttributeValueList (list) --One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used.
For type Number, value comparisons are numeric.
String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, a is greater than A , and a is greater than B . For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters .
For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values.
For information on specifying data types in JSON, see JSON Data Format in the Amazon DynamoDB Developer Guide .
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
S (string) --An attribute of type String. For example:
'S': 'Hello'
N (string) --An attribute of type Number. For example:
'N': '123.45'
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
B (bytes) --An attribute of type Binary. For example:
'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
SS (list) --An attribute of type String Set. For example:
'SS': ['Giraffe', 'Hippo' ,'Zebra']
(string) --
NS (list) --An attribute of type Number Set. For example:
'NS': ['42.2', '-19', '7.5', '3.14']
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
(string) --
BS (list) --An attribute of type Binary Set. For example:
'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
(bytes) --
M (dict) --An attribute of type Map. For example:
'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
L (list) --An attribute of type List. For example:
'L': ['Cookies', 'Coffee', 3.14159]
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
NULL (boolean) --An attribute of type Null. For example:
'NULL': true
BOOL (boolean) --An attribute of type Boolean. For example:
'BOOL': true
:type ReturnValues: string
:param ReturnValues: Use ReturnValues if you want to get the item attributes as they appeared before they were updated with the PutItem request. For PutItem , the valid values are:
NONE - If ReturnValues is not specified, or if its value is NONE , then nothing is returned. (This setting is the default for ReturnValues .)
ALL_OLD - If PutItem overwrote an attribute name-value pair, then the content of the old item is returned.
Note
The ReturnValues parameter is used by several DynamoDB operations; however, PutItem does not recognize any values other than NONE or ALL_OLD .
:type ReturnConsumedCapacity: string
:param ReturnConsumedCapacity: Determines the level of detail about provisioned throughput consumption that is returned in the response:
INDEXES - The response includes the aggregate ConsumedCapacity for the operation, together with ConsumedCapacity for each table and secondary index that was accessed. Note that some operations, such as GetItem and BatchGetItem , do not access any indexes at all. In these cases, specifying INDEXES will only return ConsumedCapacity information for table(s).
TOTAL - The response includes only the aggregate ConsumedCapacity for the operation.
NONE - No ConsumedCapacity details are included in the response.
:type ReturnItemCollectionMetrics: string
:param ReturnItemCollectionMetrics: Determines whether item collection metrics are returned. If set to SIZE , the response includes statistics about item collections, if any, that were modified during the operation are returned in the response. If set to NONE (the default), no statistics are returned.
:type ConditionalOperator: string
:param ConditionalOperator: This is a legacy parameter. Use ConditionExpression instead. For more information, see ConditionalOperator in the Amazon DynamoDB Developer Guide .
:type ConditionExpression: string
:param ConditionExpression: A condition that must be satisfied in order for a conditional PutItem operation to succeed.
An expression can contain any of the following:
Functions: attribute_exists | attribute_not_exists | attribute_type | contains | begins_with | size These function names are case-sensitive.
Comparison operators: = | | | | = | = | BETWEEN | IN
Logical operators: AND | OR | NOT
For more information on condition expressions, see Specifying Conditions in the Amazon DynamoDB Developer Guide .
:type ExpressionAttributeNames: dict
:param ExpressionAttributeNames: One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames :
To access an attribute whose name conflicts with a DynamoDB reserved word.
To create a placeholder for repeating occurrences of an attribute name in an expression.
To prevent special characters in an attribute name from being misinterpreted in an expression.
Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name:
Percentile
The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide ). To work around this, you could specify the following for ExpressionAttributeNames :
{'#P':'Percentile'}
You could then use this substitution in an expression, as in this example:
#P = :val
Note
Tokens that begin with the : character are expression attribute values , which are placeholders for the actual value at runtime.
For more information on expression attribute names, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide .
(string) --
(string) --
:type ExpressionAttributeValues: dict
:param ExpressionAttributeValues: One or more values that can be substituted in an expression.
Use the : (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following:
Available | Backordered | Discontinued
You would first need to specify ExpressionAttributeValues as follows:
{ ':avail':{'S':'Available'}, ':back':{'S':'Backordered'}, ':disc':{'S':'Discontinued'} }
You could then use these values in an expression, such as this:
ProductStatus IN (:avail, :back, :disc)
For more information on expression attribute values, see Specifying Conditions in the Amazon DynamoDB Developer Guide .
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
S (string) --An attribute of type String. For example:
'S': 'Hello'
N (string) --An attribute of type Number. For example:
'N': '123.45'
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
B (bytes) --An attribute of type Binary. For example:
'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
SS (list) --An attribute of type String Set. For example:
'SS': ['Giraffe', 'Hippo' ,'Zebra']
(string) --
NS (list) --An attribute of type Number Set. For example:
'NS': ['42.2', '-19', '7.5', '3.14']
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
(string) --
BS (list) --An attribute of type Binary Set. For example:
'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
(bytes) --
M (dict) --An attribute of type Map. For example:
'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
L (list) --An attribute of type List. For example:
'L': ['Cookies', 'Coffee', 3.14159]
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
NULL (boolean) --An attribute of type Null. For example:
'NULL': true
BOOL (boolean) --An attribute of type Boolean. For example:
'BOOL': true
:rtype: dict
:return: {
'Attributes': {
'string': {
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
}
},
'ConsumedCapacity': {
'TableName': 'string',
'CapacityUnits': 123.0,
'Table': {
'CapacityUnits': 123.0
},
'LocalSecondaryIndexes': {
'string': {
'CapacityUnits': 123.0
}
},
'GlobalSecondaryIndexes': {
'string': {
'CapacityUnits': 123.0
}
}
},
'ItemCollectionMetrics': {
'ItemCollectionKey': {
'string': {
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
}
},
'SizeEstimateRangeGB': [
123.0,
]
}
}
:returns:
(string) --
"""
pass | [
"def",
"put_item",
"(",
"TableName",
"=",
"None",
",",
"Item",
"=",
"None",
",",
"Expected",
"=",
"None",
",",
"ReturnValues",
"=",
"None",
",",
"ReturnConsumedCapacity",
"=",
"None",
",",
"ReturnItemCollectionMetrics",
"=",
"None",
",",
"ConditionalOperator",
... | Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist), or replace an existing item if it has certain attribute values.
In addition to putting an item, you can also return the item's attribute values in the same operation, using the ReturnValues parameter.
When you add an item, the primary key attribute(s) are the only required attributes. Attribute values cannot be null. String and Binary type attributes must have lengths greater than zero. Set type attributes cannot be empty. Requests with empty values will be rejected with a ValidationException exception.
For more information about PutItem , see Working with Items in the Amazon DynamoDB Developer Guide .
See also: AWS API Documentation
Examples
This example adds a new item to the Music table.
Expected Output:
:example: response = client.put_item(
TableName='string',
Item={
'string': {
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
}
},
Expected={
'string': {
'Value': {
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
},
'Exists': True|False,
'ComparisonOperator': 'EQ'|'NE'|'IN'|'LE'|'LT'|'GE'|'GT'|'BETWEEN'|'NOT_NULL'|'NULL'|'CONTAINS'|'NOT_CONTAINS'|'BEGINS_WITH',
'AttributeValueList': [
{
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
},
]
}
},
ReturnValues='NONE'|'ALL_OLD'|'UPDATED_OLD'|'ALL_NEW'|'UPDATED_NEW',
ReturnConsumedCapacity='INDEXES'|'TOTAL'|'NONE',
ReturnItemCollectionMetrics='SIZE'|'NONE',
ConditionalOperator='AND'|'OR',
ConditionExpression='string',
ExpressionAttributeNames={
'string': 'string'
},
ExpressionAttributeValues={
'string': {
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
}
}
)
:type TableName: string
:param TableName: [REQUIRED]
The name of the table to contain the item.
:type Item: dict
:param Item: [REQUIRED]
A map of attribute name/value pairs, one for each attribute. Only the primary key attributes are required; you can optionally provide other attribute name-value pairs for the item.
You must provide all of the attributes for the primary key. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide both values for both the partition key and the sort key.
If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition.
For more information about primary keys, see Primary Key in the Amazon DynamoDB Developer Guide .
Each element in the Item map is an AttributeValue object.
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
S (string) --An attribute of type String. For example:
'S': 'Hello'
N (string) --An attribute of type Number. For example:
'N': '123.45'
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
B (bytes) --An attribute of type Binary. For example:
'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
SS (list) --An attribute of type String Set. For example:
'SS': ['Giraffe', 'Hippo' ,'Zebra']
(string) --
NS (list) --An attribute of type Number Set. For example:
'NS': ['42.2', '-19', '7.5', '3.14']
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
(string) --
BS (list) --An attribute of type Binary Set. For example:
'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
(bytes) --
M (dict) --An attribute of type Map. For example:
'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
L (list) --An attribute of type List. For example:
'L': ['Cookies', 'Coffee', 3.14159]
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
NULL (boolean) --An attribute of type Null. For example:
'NULL': true
BOOL (boolean) --An attribute of type Boolean. For example:
'BOOL': true
:type Expected: dict
:param Expected: This is a legacy parameter. Use ConditionExpresssion instead. For more information, see Expected in the Amazon DynamoDB Developer Guide .
(string) --
(dict) --Represents a condition to be compared with an attribute value. This condition can be used with DeleteItem , PutItem or UpdateItem operations; if the comparison evaluates to true, the operation succeeds; if not, the operation fails. You can use ExpectedAttributeValue in one of two different ways:
Use AttributeValueList to specify one or more values to compare against an attribute. Use ComparisonOperator to specify how you want to perform the comparison. If the comparison evaluates to true, then the conditional operation succeeds.
Use Value to specify a value that DynamoDB will compare against an attribute. If the values match, then ExpectedAttributeValue evaluates to true and the conditional operation succeeds. Optionally, you can also set Exists to false, indicating that you do not expect to find the attribute value in the table. In this case, the conditional operation succeeds only if the comparison evaluates to false.
Value and Exists are incompatible with AttributeValueList and ComparisonOperator . Note that if you use both sets of parameters at once, DynamoDB will return a ValidationException exception.
Value (dict) --Represents the data for the expected attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
S (string) --An attribute of type String. For example:
'S': 'Hello'
N (string) --An attribute of type Number. For example:
'N': '123.45'
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
B (bytes) --An attribute of type Binary. For example:
'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
SS (list) --An attribute of type String Set. For example:
'SS': ['Giraffe', 'Hippo' ,'Zebra']
(string) --
NS (list) --An attribute of type Number Set. For example:
'NS': ['42.2', '-19', '7.5', '3.14']
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
(string) --
BS (list) --An attribute of type Binary Set. For example:
'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
(bytes) --
M (dict) --An attribute of type Map. For example:
'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
L (list) --An attribute of type List. For example:
'L': ['Cookies', 'Coffee', 3.14159]
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
NULL (boolean) --An attribute of type Null. For example:
'NULL': true
BOOL (boolean) --An attribute of type Boolean. For example:
'BOOL': true
Exists (boolean) --Causes DynamoDB to evaluate the value before attempting a conditional operation:
If Exists is true , DynamoDB will check to see if that attribute value already exists in the table. If it is found, then the operation succeeds. If it is not found, the operation fails with a ConditionalCheckFailedException .
If Exists is false , DynamoDB assumes that the attribute value does not exist in the table. If in fact the value does not exist, then the assumption is valid and the operation succeeds. If the value is found, despite the assumption that it does not exist, the operation fails with a ConditionalCheckFailedException .
The default setting for Exists is true . If you supply a Value all by itself, DynamoDB assumes the attribute exists: You don't have to set Exists to true , because it is implied.
DynamoDB returns a ValidationException if:
Exists is true but there is no Value to check. (You expect a value to exist, but don't specify what that value is.)
Exists is false but you also provide a Value . (You cannot expect an attribute to have a value, while also expecting it not to exist.)
ComparisonOperator (string) --A comparator for evaluating attributes in the AttributeValueList . For example, equals, greater than, less than, etc.
The following comparison operators are available:
EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN
The following are descriptions of each comparison operator.
EQ : Equal. EQ is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} .
NE : Not equal. NE is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} .
LE : Less than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
LT : Less than. AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
GE : Greater than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
GT : Greater than. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
NOT_NULL : The attribute exists. NOT_NULL is supported for all data types, including lists and maps.
Note
This operator tests for the existence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NOT_NULL , the result is a Boolean true . This result is because the attribute 'a ' exists; its data type is not relevant to the NOT_NULL comparison operator.
NULL : The attribute does not exist. NULL is supported for all data types, including lists and maps.
Note
This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NULL , the result is a Boolean false . This is because the attribute 'a ' exists; its data type is not relevant to the NULL comparison operator.
CONTAINS : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating 'a CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list.
NOT_CONTAINS : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating 'a NOT CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list.
BEGINS_WITH : Checks for a prefix. AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type).
IN : Checks for matching elements in a list. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary. These attributes are compared against an existing attribute of an item. If any elements of the input are equal to the item attribute, the expression evaluates to true.
BETWEEN : Greater than or equal to the first value, and less than or equal to the second value. AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not compare to {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']}
AttributeValueList (list) --One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used.
For type Number, value comparisons are numeric.
String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, a is greater than A , and a is greater than B . For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters .
For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values.
For information on specifying data types in JSON, see JSON Data Format in the Amazon DynamoDB Developer Guide .
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
S (string) --An attribute of type String. For example:
'S': 'Hello'
N (string) --An attribute of type Number. For example:
'N': '123.45'
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
B (bytes) --An attribute of type Binary. For example:
'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
SS (list) --An attribute of type String Set. For example:
'SS': ['Giraffe', 'Hippo' ,'Zebra']
(string) --
NS (list) --An attribute of type Number Set. For example:
'NS': ['42.2', '-19', '7.5', '3.14']
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
(string) --
BS (list) --An attribute of type Binary Set. For example:
'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
(bytes) --
M (dict) --An attribute of type Map. For example:
'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
L (list) --An attribute of type List. For example:
'L': ['Cookies', 'Coffee', 3.14159]
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
NULL (boolean) --An attribute of type Null. For example:
'NULL': true
BOOL (boolean) --An attribute of type Boolean. For example:
'BOOL': true
:type ReturnValues: string
:param ReturnValues: Use ReturnValues if you want to get the item attributes as they appeared before they were updated with the PutItem request. For PutItem , the valid values are:
NONE - If ReturnValues is not specified, or if its value is NONE , then nothing is returned. (This setting is the default for ReturnValues .)
ALL_OLD - If PutItem overwrote an attribute name-value pair, then the content of the old item is returned.
Note
The ReturnValues parameter is used by several DynamoDB operations; however, PutItem does not recognize any values other than NONE or ALL_OLD .
:type ReturnConsumedCapacity: string
:param ReturnConsumedCapacity: Determines the level of detail about provisioned throughput consumption that is returned in the response:
INDEXES - The response includes the aggregate ConsumedCapacity for the operation, together with ConsumedCapacity for each table and secondary index that was accessed. Note that some operations, such as GetItem and BatchGetItem , do not access any indexes at all. In these cases, specifying INDEXES will only return ConsumedCapacity information for table(s).
TOTAL - The response includes only the aggregate ConsumedCapacity for the operation.
NONE - No ConsumedCapacity details are included in the response.
:type ReturnItemCollectionMetrics: string
:param ReturnItemCollectionMetrics: Determines whether item collection metrics are returned. If set to SIZE , the response includes statistics about item collections, if any, that were modified during the operation are returned in the response. If set to NONE (the default), no statistics are returned.
:type ConditionalOperator: string
:param ConditionalOperator: This is a legacy parameter. Use ConditionExpression instead. For more information, see ConditionalOperator in the Amazon DynamoDB Developer Guide .
:type ConditionExpression: string
:param ConditionExpression: A condition that must be satisfied in order for a conditional PutItem operation to succeed.
An expression can contain any of the following:
Functions: attribute_exists | attribute_not_exists | attribute_type | contains | begins_with | size These function names are case-sensitive.
Comparison operators: = | | | | = | = | BETWEEN | IN
Logical operators: AND | OR | NOT
For more information on condition expressions, see Specifying Conditions in the Amazon DynamoDB Developer Guide .
:type ExpressionAttributeNames: dict
:param ExpressionAttributeNames: One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames :
To access an attribute whose name conflicts with a DynamoDB reserved word.
To create a placeholder for repeating occurrences of an attribute name in an expression.
To prevent special characters in an attribute name from being misinterpreted in an expression.
Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name:
Percentile
The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide ). To work around this, you could specify the following for ExpressionAttributeNames :
{'#P':'Percentile'}
You could then use this substitution in an expression, as in this example:
#P = :val
Note
Tokens that begin with the : character are expression attribute values , which are placeholders for the actual value at runtime.
For more information on expression attribute names, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide .
(string) --
(string) --
:type ExpressionAttributeValues: dict
:param ExpressionAttributeValues: One or more values that can be substituted in an expression.
Use the : (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following:
Available | Backordered | Discontinued
You would first need to specify ExpressionAttributeValues as follows:
{ ':avail':{'S':'Available'}, ':back':{'S':'Backordered'}, ':disc':{'S':'Discontinued'} }
You could then use these values in an expression, such as this:
ProductStatus IN (:avail, :back, :disc)
For more information on expression attribute values, see Specifying Conditions in the Amazon DynamoDB Developer Guide .
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
S (string) --An attribute of type String. For example:
'S': 'Hello'
N (string) --An attribute of type Number. For example:
'N': '123.45'
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
B (bytes) --An attribute of type Binary. For example:
'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
SS (list) --An attribute of type String Set. For example:
'SS': ['Giraffe', 'Hippo' ,'Zebra']
(string) --
NS (list) --An attribute of type Number Set. For example:
'NS': ['42.2', '-19', '7.5', '3.14']
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
(string) --
BS (list) --An attribute of type Binary Set. For example:
'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
(bytes) --
M (dict) --An attribute of type Map. For example:
'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
(string) --
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
L (list) --An attribute of type List. For example:
'L': ['Cookies', 'Coffee', 3.14159]
(dict) --Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see Data Types in the Amazon DynamoDB Developer Guide .
NULL (boolean) --An attribute of type Null. For example:
'NULL': true
BOOL (boolean) --An attribute of type Boolean. For example:
'BOOL': true
:rtype: dict
:return: {
'Attributes': {
'string': {
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
}
},
'ConsumedCapacity': {
'TableName': 'string',
'CapacityUnits': 123.0,
'Table': {
'CapacityUnits': 123.0
},
'LocalSecondaryIndexes': {
'string': {
'CapacityUnits': 123.0
}
},
'GlobalSecondaryIndexes': {
'string': {
'CapacityUnits': 123.0
}
}
},
'ItemCollectionMetrics': {
'ItemCollectionKey': {
'string': {
'S': 'string',
'N': 'string',
'B': b'bytes',
'SS': [
'string',
],
'NS': [
'string',
],
'BS': [
b'bytes',
],
'M': {
'string': {'... recursive ...'}
},
'L': [
{'... recursive ...'},
],
'NULL': True|False,
'BOOL': True|False
}
},
'SizeEstimateRangeGB': [
123.0,
]
}
}
:returns:
(string) -- | [
"Creates",
"a",
"new",
"item",
"or",
"replaces",
"an",
"old",
"item",
"with",
"a",
"new",
"item",
".",
"If",
"an",
"item",
"that",
"has",
"the",
"same",
"primary",
"key",
"as",
"the",
"new",
"item",
"already",
"exists",
"in",
"the",
"specified",
"table... | python | train |
numenta/nupic | src/nupic/swarming/hypersearch/hs_state.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L106-L229 | def readStateFromDB(self):
"""Set our state to that obtained from the engWorkerState field of the
job record.
Parameters:
---------------------------------------------------------------------
stateJSON: JSON encoded state from job record
"""
self._priorStateJSON = self._hsObj._cjDAO.jobGetFields(self._hsObj._jobID,
['engWorkerState'])[0]
# Init if no prior state yet
if self._priorStateJSON is None:
swarms = dict()
# Fast Swarm, first and only sprint has one swarm for each field
# in fixedFields
if self._hsObj._fixedFields is not None:
print self._hsObj._fixedFields
encoderSet = []
for field in self._hsObj._fixedFields:
if field =='_classifierInput':
continue
encoderName = self.getEncoderKeyFromName(field)
assert encoderName in self._hsObj._encoderNames, "The field '%s' " \
" specified in the fixedFields list is not present in this " \
" model." % (field)
encoderSet.append(encoderName)
encoderSet.sort()
swarms['.'.join(encoderSet)] = {
'status': 'active',
'bestModelId': None,
'bestErrScore': None,
'sprintIdx': 0,
}
# Temporal prediction search, first sprint has N swarms of 1 field each,
# the predicted field may or may not be that one field.
elif self._hsObj._searchType == HsSearchType.temporal:
for encoderName in self._hsObj._encoderNames:
swarms[encoderName] = {
'status': 'active',
'bestModelId': None,
'bestErrScore': None,
'sprintIdx': 0,
}
# Classification prediction search, first sprint has N swarms of 1 field
# each where this field can NOT be the predicted field.
elif self._hsObj._searchType == HsSearchType.classification:
for encoderName in self._hsObj._encoderNames:
if encoderName == self._hsObj._predictedFieldEncoder:
continue
swarms[encoderName] = {
'status': 'active',
'bestModelId': None,
'bestErrScore': None,
'sprintIdx': 0,
}
# Legacy temporal. This is either a model that uses reconstruction or
# an older multi-step model that doesn't have a separate
# 'classifierOnly' encoder for the predicted field. Here, the predicted
# field must ALWAYS be present and the first sprint tries the predicted
# field only
elif self._hsObj._searchType == HsSearchType.legacyTemporal:
swarms[self._hsObj._predictedFieldEncoder] = {
'status': 'active',
'bestModelId': None,
'bestErrScore': None,
'sprintIdx': 0,
}
else:
raise RuntimeError("Unsupported search type: %s" % \
(self._hsObj._searchType))
# Initialize the state.
self._state = dict(
# The last time the state was updated by a worker.
lastUpdateTime = time.time(),
# Set from within setSwarmState() if we detect that the sprint we just
# completed did worse than a prior sprint. This stores the index of
# the last good sprint.
lastGoodSprint = None,
# Set from within setSwarmState() if lastGoodSprint is True and all
# sprints have completed.
searchOver = False,
# This is a summary of the active swarms - this information can also
# be obtained from the swarms entry that follows, but is summarized here
# for easier reference when viewing the state as presented by
# log messages and prints of the hsState data structure (by
# permutations_runner).
activeSwarms = swarms.keys(),
# All the swarms that have been created so far.
swarms = swarms,
# All the sprints that have completed or are in progress.
sprints = [{'status': 'active',
'bestModelId': None,
'bestErrScore': None}],
# The list of encoders we have "blacklisted" because they
# performed so poorly.
blackListedEncoders = [],
)
# This will do nothing if the value of engWorkerState is not still None.
self._hsObj._cjDAO.jobSetFieldIfEqual(
self._hsObj._jobID, 'engWorkerState', json.dumps(self._state), None)
self._priorStateJSON = self._hsObj._cjDAO.jobGetFields(
self._hsObj._jobID, ['engWorkerState'])[0]
assert (self._priorStateJSON is not None)
# Read state from the database
self._state = json.loads(self._priorStateJSON)
self._dirty = False | [
"def",
"readStateFromDB",
"(",
"self",
")",
":",
"self",
".",
"_priorStateJSON",
"=",
"self",
".",
"_hsObj",
".",
"_cjDAO",
".",
"jobGetFields",
"(",
"self",
".",
"_hsObj",
".",
"_jobID",
",",
"[",
"'engWorkerState'",
"]",
")",
"[",
"0",
"]",
"# Init if ... | Set our state to that obtained from the engWorkerState field of the
job record.
Parameters:
---------------------------------------------------------------------
stateJSON: JSON encoded state from job record | [
"Set",
"our",
"state",
"to",
"that",
"obtained",
"from",
"the",
"engWorkerState",
"field",
"of",
"the",
"job",
"record",
"."
] | python | valid |
fstab50/metal | metal/script_utils.py | https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/script_utils.py#L36-L60 | def bool_assignment(arg, patterns=None):
"""
Summary:
Enforces correct bool argment assignment
Arg:
:arg (*): arg which must be interpreted as either bool True or False
Returns:
bool assignment | TYPE: bool
"""
arg = str(arg) # only eval type str
try:
if patterns is None:
patterns = (
(re.compile(r'^(true|false)$', flags=re.IGNORECASE), lambda x: x.lower() == 'true'),
(re.compile(r'^(yes|no)$', flags=re.IGNORECASE), lambda x: x.lower() == 'yes'),
(re.compile(r'^(y|n)$', flags=re.IGNORECASE), lambda x: x.lower() == 'y')
)
if not arg:
return '' # default selected
else:
for pattern, func in patterns:
if pattern.match(arg):
return func(arg)
except Exception as e:
raise e | [
"def",
"bool_assignment",
"(",
"arg",
",",
"patterns",
"=",
"None",
")",
":",
"arg",
"=",
"str",
"(",
"arg",
")",
"# only eval type str",
"try",
":",
"if",
"patterns",
"is",
"None",
":",
"patterns",
"=",
"(",
"(",
"re",
".",
"compile",
"(",
"r'^(true|f... | Summary:
Enforces correct bool argment assignment
Arg:
:arg (*): arg which must be interpreted as either bool True or False
Returns:
bool assignment | TYPE: bool | [
"Summary",
":",
"Enforces",
"correct",
"bool",
"argment",
"assignment",
"Arg",
":",
":",
"arg",
"(",
"*",
")",
":",
"arg",
"which",
"must",
"be",
"interpreted",
"as",
"either",
"bool",
"True",
"or",
"False",
"Returns",
":",
"bool",
"assignment",
"|",
"TY... | python | train |
wonambi-python/wonambi | wonambi/attr/annotations.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1193-L1210 | def time_in_stage(self, name, attr='stage'):
"""Return time (in seconds) in the selected stage.
Parameters
----------
name : str
one of the sleep stages, or qualifiers
attr : str, optional
either 'stage' or 'quality'
Returns
-------
int
time spent in one stage/qualifier, in seconds.
"""
return sum(x['end'] - x['start'] for x in self.epochs
if x[attr] == name) | [
"def",
"time_in_stage",
"(",
"self",
",",
"name",
",",
"attr",
"=",
"'stage'",
")",
":",
"return",
"sum",
"(",
"x",
"[",
"'end'",
"]",
"-",
"x",
"[",
"'start'",
"]",
"for",
"x",
"in",
"self",
".",
"epochs",
"if",
"x",
"[",
"attr",
"]",
"==",
"n... | Return time (in seconds) in the selected stage.
Parameters
----------
name : str
one of the sleep stages, or qualifiers
attr : str, optional
either 'stage' or 'quality'
Returns
-------
int
time spent in one stage/qualifier, in seconds. | [
"Return",
"time",
"(",
"in",
"seconds",
")",
"in",
"the",
"selected",
"stage",
"."
] | python | train |
tijme/not-your-average-web-crawler | nyawc/Queue.py | https://github.com/tijme/not-your-average-web-crawler/blob/d77c14e1616c541bb3980f649a7e6f8ed02761fb/nyawc/Queue.py#L64-L77 | def add_request(self, request):
"""Add a request to the queue.
Args:
request (:class:`nyawc.http.Request`): The request to add.
Returns:
:class:`nyawc.QueueItem`: The created queue item.
"""
queue_item = QueueItem(request, Response(request.url))
self.add(queue_item)
return queue_item | [
"def",
"add_request",
"(",
"self",
",",
"request",
")",
":",
"queue_item",
"=",
"QueueItem",
"(",
"request",
",",
"Response",
"(",
"request",
".",
"url",
")",
")",
"self",
".",
"add",
"(",
"queue_item",
")",
"return",
"queue_item"
] | Add a request to the queue.
Args:
request (:class:`nyawc.http.Request`): The request to add.
Returns:
:class:`nyawc.QueueItem`: The created queue item. | [
"Add",
"a",
"request",
"to",
"the",
"queue",
"."
] | python | train |
tgbugs/pyontutils | pyontutils/utils.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/utils.py#L45-L67 | def sysidpath(ignore_options=False):
""" get a unique identifier for the machine running this function """
# in the event we have to make our own
# this should not be passed in a as a parameter
# since we need these definitions to be more or less static
failover = Path('/tmp/machine-id')
if not ignore_options:
options = (
Path('/etc/machine-id'),
failover, # always read to see if we somehow managed to persist this
)
for option in options:
if (option.exists() and
os.access(option, os.R_OK) and
option.stat().st_size > 0):
return option
uuid = uuid4()
with open(failover, 'wt') as f:
f.write(uuid.hex)
return failover | [
"def",
"sysidpath",
"(",
"ignore_options",
"=",
"False",
")",
":",
"# in the event we have to make our own",
"# this should not be passed in a as a parameter",
"# since we need these definitions to be more or less static",
"failover",
"=",
"Path",
"(",
"'/tmp/machine-id'",
")",
"if... | get a unique identifier for the machine running this function | [
"get",
"a",
"unique",
"identifier",
"for",
"the",
"machine",
"running",
"this",
"function"
] | python | train |
sendgrid/sendgrid-python | examples/helpers/mail_example.py | https://github.com/sendgrid/sendgrid-python/blob/266c2abde7a35dfcce263e06bedc6a0bbdebeac9/examples/helpers/mail_example.py#L105-L309 | def build_kitchen_sink():
"""All settings set"""
from sendgrid.helpers.mail import (
Mail, From, To, Cc, Bcc, Subject, PlainTextContent,
HtmlContent, SendGridException, Substitution,
Header, CustomArg, SendAt, Content, MimeType, Attachment,
FileName, FileContent, FileType, Disposition, ContentId,
TemplateId, Section, ReplyTo, Category, BatchId, Asm,
GroupId, GroupsToDisplay, IpPoolName, MailSettings,
BccSettings, BccSettingsEmail, BypassListManagement,
FooterSettings, FooterText, FooterHtml, SandBoxMode,
SpamCheck, SpamThreshold, SpamUrl, TrackingSettings,
ClickTracking, SubscriptionTracking, SubscriptionText,
SubscriptionHtml, SubscriptionSubstitutionTag,
OpenTracking, OpenTrackingSubstitutionTag, Ganalytics,
UtmSource, UtmMedium, UtmTerm, UtmContent, UtmCampaign)
import time
import datetime
message = Mail()
# Define Personalizations
message.to = To('test1@sendgrid.com', 'Example User1', p=0)
message.to = [
To('test2@sendgrid.com', 'Example User2', p=0),
To('test3@sendgrid.com', 'Example User3', p=0)
]
message.cc = Cc('test4@example.com', 'Example User4', p=0)
message.cc = [
Cc('test5@example.com', 'Example User5', p=0),
Cc('test6@example.com', 'Example User6', p=0)
]
message.bcc = Bcc('test7@example.com', 'Example User7', p=0)
message.bcc = [
Bcc('test8@example.com', 'Example User8', p=0),
Bcc('test9@example.com', 'Example User9', p=0)
]
message.subject = Subject('Sending with SendGrid is Fun 0', p=0)
message.header = Header('X-Test1', 'Test1', p=0)
message.header = Header('X-Test2', 'Test2', p=0)
message.header = [
Header('X-Test3', 'Test3', p=0),
Header('X-Test4', 'Test4', p=0)
]
message.substitution = Substitution('%name1%', 'Example Name 1', p=0)
message.substitution = Substitution('%city1%', 'Example City 1', p=0)
message.substitution = [
Substitution('%name2%', 'Example Name 2', p=0),
Substitution('%city2%', 'Example City 2', p=0)
]
message.custom_arg = CustomArg('marketing1', 'true', p=0)
message.custom_arg = CustomArg('transactional1', 'false', p=0)
message.custom_arg = [
CustomArg('marketing2', 'false', p=0),
CustomArg('transactional2', 'true', p=0)
]
message.send_at = SendAt(1461775051, p=0)
message.to = To('test10@example.com', 'Example User10', p=1)
message.to = [
To('test11@example.com', 'Example User11', p=1),
To('test12@example.com', 'Example User12', p=1)
]
message.cc = Cc('test13@example.com', 'Example User13', p=1)
message.cc = [
Cc('test14@example.com', 'Example User14', p=1),
Cc('test15@example.com', 'Example User15', p=1)
]
message.bcc = Bcc('test16@example.com', 'Example User16', p=1)
message.bcc = [
Bcc('test17@example.com', 'Example User17', p=1),
Bcc('test18@example.com', 'Example User18', p=1)
]
message.header = Header('X-Test5', 'Test5', p=1)
message.header = Header('X-Test6', 'Test6', p=1)
message.header = [
Header('X-Test7', 'Test7', p=1),
Header('X-Test8', 'Test8', p=1)
]
message.substitution = Substitution('%name3%', 'Example Name 3', p=1)
message.substitution = Substitution('%city3%', 'Example City 3', p=1)
message.substitution = [
Substitution('%name4%', 'Example Name 4', p=1),
Substitution('%city4%', 'Example City 4', p=1)
]
message.custom_arg = CustomArg('marketing3', 'true', p=1)
message.custom_arg = CustomArg('transactional3', 'false', p=1)
message.custom_arg = [
CustomArg('marketing4', 'false', p=1),
CustomArg('transactional4', 'true', p=1)
]
message.send_at = SendAt(1461775052, p=1)
message.subject = Subject('Sending with SendGrid is Fun 1', p=1)
# The values below this comment are global to entire message
message.from_email = From('dx@sendgrid.com', 'DX')
message.reply_to = ReplyTo('dx_reply@sendgrid.com', 'DX Reply')
message.subject = Subject('Sending with SendGrid is Fun 2')
message.content = Content(MimeType.text, 'and easy to do anywhere, even with Python')
message.content = Content(MimeType.html, '<strong>and easy to do anywhere, even with Python</strong>')
message.content = [
Content('text/calendar', 'Party Time!!'),
Content('text/custom', 'Party Time 2!!')
]
message.attachment = Attachment(FileContent('base64 encoded content 1'),
FileType('application/pdf'),
FileName('balance_001.pdf'),
Disposition('attachment'),
ContentId('Content ID 1'))
message.attachment = [
Attachment(FileContent('base64 encoded content 2'),
FileType('image/png'),
FileName('banner.png'),
Disposition('inline'),
ContentId('Content ID 2')),
Attachment(FileContent('base64 encoded content 3'),
FileType('image/png'),
FileName('banner2.png'),
Disposition('inline'),
ContentId('Content ID 3'))
]
message.template_id = TemplateId('13b8f94f-bcae-4ec6-b752-70d6cb59f932')
message.section = Section('%section1%', 'Substitution for Section 1 Tag')
message.section = [
Section('%section2%', 'Substitution for Section 2 Tag'),
Section('%section3%', 'Substitution for Section 3 Tag')
]
message.header = Header('X-Test9', 'Test9')
message.header = Header('X-Test10', 'Test10')
message.header = [
Header('X-Test11', 'Test11'),
Header('X-Test12', 'Test12')
]
message.category = Category('Category 1')
message.category = Category('Category 2')
message.category = [
Category('Category 1'),
Category('Category 2')
]
message.custom_arg = CustomArg('marketing5', 'false')
message.custom_arg = CustomArg('transactional5', 'true')
message.custom_arg = [
CustomArg('marketing6', 'true'),
CustomArg('transactional6', 'false')
]
message.send_at = SendAt(1461775053)
message.batch_id = BatchId("HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi")
message.asm = Asm(GroupId(1), GroupsToDisplay([1,2,3,4]))
message.ip_pool_name = IpPoolName("IP Pool Name")
mail_settings = MailSettings()
mail_settings.bcc_settings = BccSettings(False, BccSettingsTo("bcc@twilio.com"))
mail_settings.bypass_list_management = BypassListManagement(False)
mail_settings.footer_settings = FooterSettings(True, FooterText("w00t"), FooterHtml("<string>w00t!<strong>"))
mail_settings.sandbox_mode = SandBoxMode(True)
mail_settings.spam_check = SpamCheck(True, SpamThreshold(5), SpamUrl("https://example.com"))
message.mail_settings = mail_settings
tracking_settings = TrackingSettings()
tracking_settings.click_tracking = ClickTracking(True, False)
tracking_settings.open_tracking = OpenTracking(True, OpenTrackingSubstitutionTag("open_tracking"))
tracking_settings.subscription_tracking = SubscriptionTracking(
True,
SubscriptionText("Goodbye"),
SubscriptionHtml("<strong>Goodbye!</strong>"),
SubscriptionSubstitutionTag("unsubscribe"))
tracking_settings.ganalytics = Ganalytics(
True,
UtmSource("utm_source"),
UtmMedium("utm_medium"),
UtmTerm("utm_term"),
UtmContent("utm_content"),
UtmCampaign("utm_campaign"))
message.tracking_settings = tracking_settings
return message.get() | [
"def",
"build_kitchen_sink",
"(",
")",
":",
"from",
"sendgrid",
".",
"helpers",
".",
"mail",
"import",
"(",
"Mail",
",",
"From",
",",
"To",
",",
"Cc",
",",
"Bcc",
",",
"Subject",
",",
"PlainTextContent",
",",
"HtmlContent",
",",
"SendGridException",
",",
... | All settings set | [
"All",
"settings",
"set"
] | python | train |
okpy/ok-client | client/sources/common/interpreter.py | https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L322-L329 | def output_lines(self):
"""Return a sequence of lines, suitable for printing or comparing
answers.
"""
if self.exception:
return [self.EXCEPTION_HEADERS[0], ' ...'] + self.exception_detail
else:
return self.output | [
"def",
"output_lines",
"(",
"self",
")",
":",
"if",
"self",
".",
"exception",
":",
"return",
"[",
"self",
".",
"EXCEPTION_HEADERS",
"[",
"0",
"]",
",",
"' ...'",
"]",
"+",
"self",
".",
"exception_detail",
"else",
":",
"return",
"self",
".",
"output"
] | Return a sequence of lines, suitable for printing or comparing
answers. | [
"Return",
"a",
"sequence",
"of",
"lines",
"suitable",
"for",
"printing",
"or",
"comparing",
"answers",
"."
] | python | train |
gitpython-developers/GitPython | git/repo/base.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/repo/base.py#L1000-L1012 | def clone_from(cls, url, to_path, progress=None, env=None, **kwargs):
"""Create a clone from the given URL
:param url: valid git url, see http://www.kernel.org/pub/software/scm/git/docs/git-clone.html#URLS
:param to_path: Path to which the repository should be cloned to
:param progress: See 'git.remote.Remote.push'.
:param env: Optional dictionary containing the desired environment variables.
:param kwargs: see the ``clone`` method
:return: Repo instance pointing to the cloned directory"""
git = Git(os.getcwd())
if env is not None:
git.update_environment(**env)
return cls._clone(git, url, to_path, GitCmdObjectDB, progress, **kwargs) | [
"def",
"clone_from",
"(",
"cls",
",",
"url",
",",
"to_path",
",",
"progress",
"=",
"None",
",",
"env",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"git",
"=",
"Git",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"if",
"env",
"is",
"not",
"None",... | Create a clone from the given URL
:param url: valid git url, see http://www.kernel.org/pub/software/scm/git/docs/git-clone.html#URLS
:param to_path: Path to which the repository should be cloned to
:param progress: See 'git.remote.Remote.push'.
:param env: Optional dictionary containing the desired environment variables.
:param kwargs: see the ``clone`` method
:return: Repo instance pointing to the cloned directory | [
"Create",
"a",
"clone",
"from",
"the",
"given",
"URL"
] | python | train |
Parquery/icontract | icontract/_recompute.py | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L55-L60 | def visit_Str(self, node: ast.Str) -> str:
"""Recompute the value as the string at the node."""
result = node.s
self.recomputed_values[node] = result
return result | [
"def",
"visit_Str",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Str",
")",
"->",
"str",
":",
"result",
"=",
"node",
".",
"s",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"return",
"result"
] | Recompute the value as the string at the node. | [
"Recompute",
"the",
"value",
"as",
"the",
"string",
"at",
"the",
"node",
"."
] | python | train |
django-parler/django-parler | parler/views.py | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/views.py#L140-L184 | def get_object(self, queryset=None):
"""
Fetch the object using a translated slug.
"""
if queryset is None:
queryset = self.get_queryset()
slug = self.kwargs[self.slug_url_kwarg]
choices = self.get_language_choices()
obj = None
using_fallback = False
prev_choices = []
for lang_choice in choices:
try:
# Get the single item from the filtered queryset
# NOTE. Explicitly set language to the state the object was fetched in.
filters = self.get_translated_filters(slug=slug)
obj = queryset.translated(lang_choice, **filters).language(lang_choice).get()
except ObjectDoesNotExist:
# Translated object not found, next object is marked as fallback.
using_fallback = True
prev_choices.append(lang_choice)
else:
break
if obj is None:
tried_msg = ", tried languages: {0}".format(", ".join(choices))
error_message = translation.ugettext("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}
raise Http404(error_message + tried_msg)
# Object found!
if using_fallback:
# It could happen that objects are resolved using their fallback language,
# but the actual translation also exists. Either that means this URL should
# raise a 404, or a redirect could be made as service to the users.
# It's possible that the old URL was active before in the language domain/subpath
# when there was no translation yet.
for prev_choice in prev_choices:
if obj.has_translation(prev_choice):
# Only dispatch() and render_to_response() can return a valid response,
# By breaking out here, this functionality can't be broken by users overriding render_to_response()
raise FallbackLanguageResolved(obj, prev_choice)
return obj | [
"def",
"get_object",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"if",
"queryset",
"is",
"None",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"slug",
"=",
"self",
".",
"kwargs",
"[",
"self",
".",
"slug_url_kwarg",
"]",
"choices... | Fetch the object using a translated slug. | [
"Fetch",
"the",
"object",
"using",
"a",
"translated",
"slug",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/logging_/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/logging_/sessions.py#L2252-L2266 | def get_log_hierarchy(self):
"""Gets the hierarchy associated with this session.
return: (osid.hierarchy.Hierarchy) - the hierarchy associated
with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinHierarchySession.get_bin_hierarchy
if self._catalog_session is not None:
return self._catalog_session.get_catalog_hierarchy()
return self._hierarchy_session.get_hierarchy() | [
"def",
"get_log_hierarchy",
"(",
"self",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.get_bin_hierarchy",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
".",
"get_catalog_hiera... | Gets the hierarchy associated with this session.
return: (osid.hierarchy.Hierarchy) - the hierarchy associated
with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"hierarchy",
"associated",
"with",
"this",
"session",
"."
] | python | train |
jvamvas/rhymediscovery | rhymediscovery/find_schemes.py | https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L228-L254 | def iterate(t_table, wordlist, stanzas, schemes, rprobs, maxsteps):
"""
Iterate EM and return final probabilities
"""
data_probs = numpy.zeros(len(stanzas))
old_data_probs = None
probs = None
num_words = len(wordlist)
ctr = 0
for ctr in range(maxsteps):
logging.info("Iteration {}".format(ctr))
old_data_probs = data_probs
logging.info("Expectation step")
probs = expectation_step(t_table, stanzas, schemes, rprobs)
logging.info("Maximization step")
t_table, rprobs = maximization_step(num_words, stanzas, schemes, probs)
# Warn if it did not converge
data_probs = numpy.logaddexp.reduce(probs, axis=1)
if ctr == maxsteps - 1 and not numpy.allclose(data_probs, old_data_probs):
logging.warning("Warning: EM did not converge")
logging.info("Stopped after {} interations".format(ctr))
return probs | [
"def",
"iterate",
"(",
"t_table",
",",
"wordlist",
",",
"stanzas",
",",
"schemes",
",",
"rprobs",
",",
"maxsteps",
")",
":",
"data_probs",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"stanzas",
")",
")",
"old_data_probs",
"=",
"None",
"probs",
"=",
"N... | Iterate EM and return final probabilities | [
"Iterate",
"EM",
"and",
"return",
"final",
"probabilities"
] | python | train |
pazz/alot | alot/settings/manager.py | https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L314-L376 | def get_tagstring_representation(self, tag, onebelow_normal=None,
onebelow_focus=None):
"""
looks up user's preferred way to represent a given tagstring.
:param tag: tagstring
:type tag: str
:param onebelow_normal: attribute that shines through if unfocussed
:type onebelow_normal: urwid.AttrSpec
:param onebelow_focus: attribute that shines through if focussed
:type onebelow_focus: urwid.AttrSpec
If `onebelow_normal` or `onebelow_focus` is given these attributes will
be used as fallbacks for fg/bg values '' and 'default'.
This returns a dictionary mapping
:normal: to :class:`urwid.AttrSpec` used if unfocussed
:focussed: to :class:`urwid.AttrSpec` used if focussed
:translated: to an alternative string representation
"""
colourmode = int(self._config.get('colourmode'))
theme = self._theme
cfg = self._config
colours = [1, 16, 256]
def colourpick(triple):
""" pick attribute from triple (mono,16c,256c) according to current
colourmode"""
if triple is None:
return None
return triple[colours.index(colourmode)]
# global default attributes for tagstrings.
# These could contain values '' and 'default' which we interpret as
# "use the values from the widget below"
default_normal = theme.get_attribute(colourmode, 'global', 'tag')
default_focus = theme.get_attribute(colourmode, 'global', 'tag_focus')
# local defaults for tagstring attributes. depend on next lower widget
fallback_normal = resolve_att(onebelow_normal, default_normal)
fallback_focus = resolve_att(onebelow_focus, default_focus)
for sec in cfg['tags'].sections:
if re.match('^{}$'.format(sec), tag):
normal = resolve_att(colourpick(cfg['tags'][sec]['normal']),
fallback_normal)
focus = resolve_att(colourpick(cfg['tags'][sec]['focus']),
fallback_focus)
translated = cfg['tags'][sec]['translated']
translated = string_decode(translated, 'UTF-8')
if translated is None:
translated = tag
translation = cfg['tags'][sec]['translation']
if translation:
translated = re.sub(translation[0], translation[1], tag)
break
else:
normal = fallback_normal
focus = fallback_focus
translated = tag
return {'normal': normal, 'focussed': focus, 'translated': translated} | [
"def",
"get_tagstring_representation",
"(",
"self",
",",
"tag",
",",
"onebelow_normal",
"=",
"None",
",",
"onebelow_focus",
"=",
"None",
")",
":",
"colourmode",
"=",
"int",
"(",
"self",
".",
"_config",
".",
"get",
"(",
"'colourmode'",
")",
")",
"theme",
"=... | looks up user's preferred way to represent a given tagstring.
:param tag: tagstring
:type tag: str
:param onebelow_normal: attribute that shines through if unfocussed
:type onebelow_normal: urwid.AttrSpec
:param onebelow_focus: attribute that shines through if focussed
:type onebelow_focus: urwid.AttrSpec
If `onebelow_normal` or `onebelow_focus` is given these attributes will
be used as fallbacks for fg/bg values '' and 'default'.
This returns a dictionary mapping
:normal: to :class:`urwid.AttrSpec` used if unfocussed
:focussed: to :class:`urwid.AttrSpec` used if focussed
:translated: to an alternative string representation | [
"looks",
"up",
"user",
"s",
"preferred",
"way",
"to",
"represent",
"a",
"given",
"tagstring",
"."
] | python | train |
tensorflow/datasets | tensorflow_datasets/core/utils/tf_utils.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/tf_utils.py#L94-L111 | def _build_graph_run(self, run_args):
"""Create a new graph for the given args."""
# Could try to use tfe.py_func(fct) but this would require knowing
# information about the signature of the function.
# Create a new graph:
with tf.Graph().as_default() as g:
# Create placeholder
input_ = run_args.input
placeholder = tf.compat.v1.placeholder(
dtype=input_.dtype, shape=input_.shape)
output = run_args.fct(placeholder)
return GraphRun(
session=raw_nogpu_session(g),
graph=g,
placeholder=placeholder,
output=output,
) | [
"def",
"_build_graph_run",
"(",
"self",
",",
"run_args",
")",
":",
"# Could try to use tfe.py_func(fct) but this would require knowing",
"# information about the signature of the function.",
"# Create a new graph:",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
... | Create a new graph for the given args. | [
"Create",
"a",
"new",
"graph",
"for",
"the",
"given",
"args",
"."
] | python | train |
saltstack/salt | salt/modules/dnsutil.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L363-L401 | def serial(zone='', update=False):
'''
Return, store and update a dns serial for your zone files.
zone: a keyword for a specific zone
update: store an updated version of the serial in a grain
If ``update`` is False, the function will retrieve an existing serial or
return the current date if no serial is stored. Nothing will be stored
If ``update`` is True, the function will set the serial to the current date
if none exist or if the existing serial is for a previous date. If a serial
for greater than the current date is already stored, the function will
increment it.
This module stores the serial in a grain, you can explicitly set the
stored value as a grain named ``dnsserial_<zone_name>``.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.serial example.com
'''
grains = {}
key = 'dnsserial'
if zone:
key += '_{0}'.format(zone)
stored = __salt__['grains.get'](key=key)
present = time.strftime('%Y%m%d01')
if not update:
return stored or present
if stored and stored >= present:
current = six.text_type(int(stored) + 1)
else:
current = present
__salt__['grains.setval'](key=key, val=current)
return current | [
"def",
"serial",
"(",
"zone",
"=",
"''",
",",
"update",
"=",
"False",
")",
":",
"grains",
"=",
"{",
"}",
"key",
"=",
"'dnsserial'",
"if",
"zone",
":",
"key",
"+=",
"'_{0}'",
".",
"format",
"(",
"zone",
")",
"stored",
"=",
"__salt__",
"[",
"'grains.... | Return, store and update a dns serial for your zone files.
zone: a keyword for a specific zone
update: store an updated version of the serial in a grain
If ``update`` is False, the function will retrieve an existing serial or
return the current date if no serial is stored. Nothing will be stored
If ``update`` is True, the function will set the serial to the current date
if none exist or if the existing serial is for a previous date. If a serial
for greater than the current date is already stored, the function will
increment it.
This module stores the serial in a grain, you can explicitly set the
stored value as a grain named ``dnsserial_<zone_name>``.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.serial example.com | [
"Return",
"store",
"and",
"update",
"a",
"dns",
"serial",
"for",
"your",
"zone",
"files",
"."
] | python | train |
google/grr | grr/client/grr_response_client/client_actions/osquery.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_actions/osquery.py#L198-L214 | def ParseRow(header,
row):
"""Parses a single row of osquery output.
Args:
header: A parsed header describing the row format.
row: A row in a "parsed JSON" representation.
Returns:
A parsed `rdf_osquery.OsqueryRow` instance.
"""
precondition.AssertDictType(row, Text, Text)
result = rdf_osquery.OsqueryRow()
for column in header.columns:
result.values.append(row[column.name])
return result | [
"def",
"ParseRow",
"(",
"header",
",",
"row",
")",
":",
"precondition",
".",
"AssertDictType",
"(",
"row",
",",
"Text",
",",
"Text",
")",
"result",
"=",
"rdf_osquery",
".",
"OsqueryRow",
"(",
")",
"for",
"column",
"in",
"header",
".",
"columns",
":",
"... | Parses a single row of osquery output.
Args:
header: A parsed header describing the row format.
row: A row in a "parsed JSON" representation.
Returns:
A parsed `rdf_osquery.OsqueryRow` instance. | [
"Parses",
"a",
"single",
"row",
"of",
"osquery",
"output",
"."
] | python | train |
YeoLab/anchor | anchor/infotheory.py | https://github.com/YeoLab/anchor/blob/1f9c9d6d30235b1e77b945e6ef01db5a0e55d53a/anchor/infotheory.py#L190-L215 | def binify_and_jsd(df1, df2, bins, pair=None):
"""Binify and calculate jensen-shannon divergence between two dataframes
Parameters
----------
df1, df2 : pandas.DataFrames
Dataframes to calculate JSD between columns of. Must have overlapping
column names
bins : array-like
Bins to use for transforming df{1,2} into probability distributions
pair : str, optional
Name of the pair to save as the name of the series
Returns
-------
divergence : pandas.Series
The Jensen-Shannon divergence between columns of df1, df2
"""
binned1 = binify(df1, bins=bins).dropna(how='all', axis=1)
binned2 = binify(df2, bins=bins).dropna(how='all', axis=1)
binned1, binned2 = binned1.align(binned2, axis=1, join='inner')
series = np.sqrt(jsd(binned1, binned2))
series.name = pair
return series | [
"def",
"binify_and_jsd",
"(",
"df1",
",",
"df2",
",",
"bins",
",",
"pair",
"=",
"None",
")",
":",
"binned1",
"=",
"binify",
"(",
"df1",
",",
"bins",
"=",
"bins",
")",
".",
"dropna",
"(",
"how",
"=",
"'all'",
",",
"axis",
"=",
"1",
")",
"binned2",... | Binify and calculate jensen-shannon divergence between two dataframes
Parameters
----------
df1, df2 : pandas.DataFrames
Dataframes to calculate JSD between columns of. Must have overlapping
column names
bins : array-like
Bins to use for transforming df{1,2} into probability distributions
pair : str, optional
Name of the pair to save as the name of the series
Returns
-------
divergence : pandas.Series
The Jensen-Shannon divergence between columns of df1, df2 | [
"Binify",
"and",
"calculate",
"jensen",
"-",
"shannon",
"divergence",
"between",
"two",
"dataframes"
] | python | train |
TeamHG-Memex/eli5 | eli5/formatters/text_helpers.py | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/text_helpers.py#L58-L90 | def prepare_weighted_spans(targets, # type: List[TargetExplanation]
preserve_density=None, # type: Optional[bool]
):
# type: (...) -> List[Optional[List[PreparedWeightedSpans]]]
""" Return weighted spans prepared for rendering.
Calculate a separate weight range for each different weighted
span (for each different index): each target has the same number
of weighted spans.
"""
targets_char_weights = [
[get_char_weights(ws, preserve_density=preserve_density)
for ws in t.weighted_spans.docs_weighted_spans]
if t.weighted_spans else None
for t in targets] # type: List[Optional[List[np.ndarray]]]
max_idx = max_or_0(len(ch_w or []) for ch_w in targets_char_weights)
targets_char_weights_not_None = [
cw for cw in targets_char_weights
if cw is not None] # type: List[List[np.ndarray]]
spans_weight_ranges = [
max_or_0(
abs(x) for char_weights in targets_char_weights_not_None
for x in char_weights[idx])
for idx in range(max_idx)]
return [
[PreparedWeightedSpans(ws, char_weights, weight_range)
for ws, char_weights, weight_range in zip(
t.weighted_spans.docs_weighted_spans, # type: ignore
t_char_weights,
spans_weight_ranges)]
if t_char_weights is not None else None
for t, t_char_weights in zip(targets, targets_char_weights)] | [
"def",
"prepare_weighted_spans",
"(",
"targets",
",",
"# type: List[TargetExplanation]",
"preserve_density",
"=",
"None",
",",
"# type: Optional[bool]",
")",
":",
"# type: (...) -> List[Optional[List[PreparedWeightedSpans]]]",
"targets_char_weights",
"=",
"[",
"[",
"get_char_weig... | Return weighted spans prepared for rendering.
Calculate a separate weight range for each different weighted
span (for each different index): each target has the same number
of weighted spans. | [
"Return",
"weighted",
"spans",
"prepared",
"for",
"rendering",
".",
"Calculate",
"a",
"separate",
"weight",
"range",
"for",
"each",
"different",
"weighted",
"span",
"(",
"for",
"each",
"different",
"index",
")",
":",
"each",
"target",
"has",
"the",
"same",
"... | python | train |
HttpRunner/HttpRunner | httprunner/report.py | https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/report.py#L248-L260 | def __get_total_response_time(meta_datas_expanded):
""" caculate total response time of all meta_datas
"""
try:
response_time = 0
for meta_data in meta_datas_expanded:
response_time += meta_data["stat"]["response_time_ms"]
return "{:.2f}".format(response_time)
except TypeError:
# failure exists
return "N/A" | [
"def",
"__get_total_response_time",
"(",
"meta_datas_expanded",
")",
":",
"try",
":",
"response_time",
"=",
"0",
"for",
"meta_data",
"in",
"meta_datas_expanded",
":",
"response_time",
"+=",
"meta_data",
"[",
"\"stat\"",
"]",
"[",
"\"response_time_ms\"",
"]",
"return... | caculate total response time of all meta_datas | [
"caculate",
"total",
"response",
"time",
"of",
"all",
"meta_datas"
] | python | train |
brycedrennan/eulerian-magnification | eulerian_magnification/io.py | https://github.com/brycedrennan/eulerian-magnification/blob/9ae0651fe3334176300d183f8240ad36d77759a9/eulerian_magnification/io.py#L74-L83 | def save_video(video, fps, save_filename='media/output.avi'):
"""Save a video to disk"""
# fourcc = cv2.CAP_PROP_FOURCC('M', 'J', 'P', 'G')
print(save_filename)
video = float_to_uint8(video)
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
writer = cv2.VideoWriter(save_filename, fourcc, fps, (video.shape[2], video.shape[1]), 1)
for x in range(0, video.shape[0]):
res = cv2.convertScaleAbs(video[x])
writer.write(res) | [
"def",
"save_video",
"(",
"video",
",",
"fps",
",",
"save_filename",
"=",
"'media/output.avi'",
")",
":",
"# fourcc = cv2.CAP_PROP_FOURCC('M', 'J', 'P', 'G')",
"print",
"(",
"save_filename",
")",
"video",
"=",
"float_to_uint8",
"(",
"video",
")",
"fourcc",
"=",
"cv2... | Save a video to disk | [
"Save",
"a",
"video",
"to",
"disk"
] | python | train |
jobovy/galpy | galpy/potential/KuzminDiskPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/KuzminDiskPotential.py#L62-L78 | def _evaluate(self,R,z,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
potential at (R,z)
HISTORY:
2016-05-09 - Written - Aladdin
"""
return -self._denom(R, z)**-0.5 | [
"def",
"_evaluate",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"return",
"-",
"self",
".",
"_denom",
"(",
"R",
",",
"z",
")",
"**",
"-",
"0.5"
] | NAME:
_evaluate
PURPOSE:
evaluate the potential at (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
potential at (R,z)
HISTORY:
2016-05-09 - Written - Aladdin | [
"NAME",
":",
"_evaluate",
"PURPOSE",
":",
"evaluate",
"the",
"potential",
"at",
"(",
"R",
"z",
")",
"INPUT",
":",
"R",
"-",
"Cylindrical",
"Galactocentric",
"radius",
"z",
"-",
"vertical",
"height",
"phi",
"-",
"azimuth",
"t",
"-",
"time",
"OUTPUT",
":",... | python | train |
UpCloudLtd/upcloud-python-api | upcloud_api/server.py | https://github.com/UpCloudLtd/upcloud-python-api/blob/954b0ad7c4b932b2be31a95d88975f6b0eeac8ed/upcloud_api/server.py#L137-L155 | def shutdown(self, hard=False, timeout=30):
"""
Shutdown/stop the server. By default, issue a soft shutdown with a timeout of 30s.
After the a timeout a hard shutdown is performed if the server has not stopped.
Note: API responds immediately (unlike in start), with state: started.
This client will, however, set state as 'maintenance' to signal that the server is neither
started nor stopped.
"""
body = dict()
body['stop_server'] = {
'stop_type': 'hard' if hard else 'soft',
'timeout': '{0}'.format(timeout)
}
path = '/server/{0}/stop'.format(self.uuid)
self.cloud_manager.post_request(path, body)
object.__setattr__(self, 'state', 'maintenance') | [
"def",
"shutdown",
"(",
"self",
",",
"hard",
"=",
"False",
",",
"timeout",
"=",
"30",
")",
":",
"body",
"=",
"dict",
"(",
")",
"body",
"[",
"'stop_server'",
"]",
"=",
"{",
"'stop_type'",
":",
"'hard'",
"if",
"hard",
"else",
"'soft'",
",",
"'timeout'"... | Shutdown/stop the server. By default, issue a soft shutdown with a timeout of 30s.
After the a timeout a hard shutdown is performed if the server has not stopped.
Note: API responds immediately (unlike in start), with state: started.
This client will, however, set state as 'maintenance' to signal that the server is neither
started nor stopped. | [
"Shutdown",
"/",
"stop",
"the",
"server",
".",
"By",
"default",
"issue",
"a",
"soft",
"shutdown",
"with",
"a",
"timeout",
"of",
"30s",
"."
] | python | train |
h2oai/h2o-3 | h2o-bindings/bin/gen_java.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-bindings/bin/gen_java.py#L42-L69 | def translate_name(name):
"""
Convert names with underscores into camelcase.
For example:
"num_rows" => "numRows"
"very_long_json_name" => "veryLongJsonName"
"build_GBM_model" => "buildGbmModel"
"KEY" => "key"
"middle___underscores" => "middleUnderscores"
"_exclude_fields" => "_excludeFields" (retain initial/trailing underscores)
"__http_status__" => "__httpStatus__"
:param name: name to be converted
"""
parts = name.split("_")
i = 0
while parts[i] == "":
parts[i] = "_"
i += 1
parts[i] = parts[i].lower()
for j in range(i + 1, len(parts)):
parts[j] = parts[j].capitalize()
i = len(parts) - 1
while parts[i] == "":
parts[i] = "_"
i -= 1
return "".join(parts) | [
"def",
"translate_name",
"(",
"name",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"\"_\"",
")",
"i",
"=",
"0",
"while",
"parts",
"[",
"i",
"]",
"==",
"\"\"",
":",
"parts",
"[",
"i",
"]",
"=",
"\"_\"",
"i",
"+=",
"1",
"parts",
"[",
"i",
... | Convert names with underscores into camelcase.
For example:
"num_rows" => "numRows"
"very_long_json_name" => "veryLongJsonName"
"build_GBM_model" => "buildGbmModel"
"KEY" => "key"
"middle___underscores" => "middleUnderscores"
"_exclude_fields" => "_excludeFields" (retain initial/trailing underscores)
"__http_status__" => "__httpStatus__"
:param name: name to be converted | [
"Convert",
"names",
"with",
"underscores",
"into",
"camelcase",
"."
] | python | test |
estnltk/estnltk | estnltk/taggers/adjective_phrase_tagger/adj_phrase_tagger.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/taggers/adjective_phrase_tagger/adj_phrase_tagger.py#L23-L58 | def __extract_lemmas(self, doc, m, phrase):
"""
:param sent: sentence from which the match was found
:param m: the found match
:phrase: name of the phrase
:return: tuple of the lemmas in the match
"""
ph_start = m['start']
ph_end = m['end']
start_index = None
for ind, word in enumerate(doc['words']):
if word['start'] == ph_start:
start_index = ind
break
end_index = None
for ind, word in enumerate(doc['words']):
if word['end'] == ph_end:
end_index = ind
break
if start_index is not None and end_index is not None:
lem = []
for i in doc['words'][start_index:end_index + 1]:
word_lem = []
for idx, j in enumerate(i['analysis']):
if i['analysis'][idx]['partofspeech'] in ['A', 'D', 'C', 'J']:
if i['analysis'][idx]['lemma'] not in word_lem:
word_lem.append(i['analysis'][idx]['lemma'])
word_lem_str = '|'.join(word_lem)
lem.append(word_lem_str)
else:
raise Exception('Something went really wrong')
return lem | [
"def",
"__extract_lemmas",
"(",
"self",
",",
"doc",
",",
"m",
",",
"phrase",
")",
":",
"ph_start",
"=",
"m",
"[",
"'start'",
"]",
"ph_end",
"=",
"m",
"[",
"'end'",
"]",
"start_index",
"=",
"None",
"for",
"ind",
",",
"word",
"in",
"enumerate",
"(",
... | :param sent: sentence from which the match was found
:param m: the found match
:phrase: name of the phrase
:return: tuple of the lemmas in the match | [
":",
"param",
"sent",
":",
"sentence",
"from",
"which",
"the",
"match",
"was",
"found",
":",
"param",
"m",
":",
"the",
"found",
"match",
":",
"phrase",
":",
"name",
"of",
"the",
"phrase",
":",
"return",
":",
"tuple",
"of",
"the",
"lemmas",
"in",
"the... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.