nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
h0x91b/redis-v8 | ac8b9d49701d75bcee3719892a2a6a50b437e47a | redis/deps/v8/tools/grokdump.py | python | InspectionShell.do_kd | (self, address) | Teach V8 heap layout information to the inspector. Set the first
data-space page by passing any pointer into that page. | Teach V8 heap layout information to the inspector. Set the first
data-space page by passing any pointer into that page. | [
"Teach",
"V8",
"heap",
"layout",
"information",
"to",
"the",
"inspector",
".",
"Set",
"the",
"first",
"data",
"-",
"space",
"page",
"by",
"passing",
"any",
"pointer",
"into",
"that",
"page",
"."
] | def do_kd(self, address):
"""
Teach V8 heap layout information to the inspector. Set the first
data-space page by passing any pointer into that page.
"""
address = int(address, 16)
page_address = address & ~self.heap.PageAlignmentMask()
self.padawan.known_first_data_page = page_address | [
"def",
"do_kd",
"(",
"self",
",",
"address",
")",
":",
"address",
"=",
"int",
"(",
"address",
",",
"16",
")",
"page_address",
"=",
"address",
"&",
"~",
"self",
".",
"heap",
".",
"PageAlignmentMask",
"(",
")",
"self",
".",
"padawan",
".",
"known_first_d... | https://github.com/h0x91b/redis-v8/blob/ac8b9d49701d75bcee3719892a2a6a50b437e47a/redis/deps/v8/tools/grokdump.py#L1753-L1760 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py | python | DNNLinearCombinedRegressor.__init__ | (self, # _joint_linear_weights pylint: disable=invalid-name
model_dir=None,
weight_column_name=None,
linear_feature_columns=None,
linear_optimizer=None,
_joint_linear_weights=False,
dnn_feature_columns=None,
dnn_optimizer=None,
dnn_hidden_units=None,
dnn_activation_fn=nn.relu,
dnn_dropout=None,
gradient_clip_norm=None,
enable_centered_bias=None,
target_dimension=1,
config=None,
feature_engineering_fn=None) | Initializes a DNNLinearCombinedRegressor instance.
Args:
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator
to continue training a previously saved model.
weight_column_name: A string defining feature column name representing
weights. It is used to down weight or boost examples during training. It
will be multiplied by the loss of the example.
linear_feature_columns: An iterable containing all the feature columns
used by linear part of the model. All items in the set must be
instances of classes derived from `FeatureColumn`.
linear_optimizer: An instance of `tf.Optimizer` used to apply gradients to
the linear part of the model. If `None`, will use a FTRL optimizer.
_joint_linear_weights: If True a single (possibly partitioned) variable
will be used to store the linear model weights. It's faster, but
requires that all columns are sparse and have the 'sum' combiner.
dnn_feature_columns: An iterable containing all the feature columns used
by deep part of the model. All items in the set must be instances of
classes derived from `FeatureColumn`.
dnn_optimizer: An instance of `tf.Optimizer` used to apply gradients to
the deep part of the model. If `None`, will use an Adagrad optimizer.
dnn_hidden_units: List of hidden units per layer. All layers are fully
connected.
dnn_activation_fn: Activation function applied to each layer. If None,
will use `tf.nn.relu`.
dnn_dropout: When not None, the probability we will drop out
a given coordinate.
gradient_clip_norm: A float > 0. If provided, gradients are clipped
to their global norm with this clipping ratio. See
tf.clip_by_global_norm for more details.
enable_centered_bias: A bool. If True, estimator will learn a centered
bias variable for each class. Rest of the model structure learns the
residual after centered bias.
target_dimension: TODO(zakaria): dimension of the target for multilabels.
config: RunConfig object to configure the runtime settings.
feature_engineering_fn: Feature engineering function. Takes features and
targets which are the output of `input_fn` and
returns features and targets which will be fed
into the model.
Raises:
ValueError: If both linear_feature_columns and dnn_features_columns are
empty at the same time. | Initializes a DNNLinearCombinedRegressor instance. | [
"Initializes",
"a",
"DNNLinearCombinedRegressor",
"instance",
"."
] | def __init__(self, # _joint_linear_weights pylint: disable=invalid-name
model_dir=None,
weight_column_name=None,
linear_feature_columns=None,
linear_optimizer=None,
_joint_linear_weights=False,
dnn_feature_columns=None,
dnn_optimizer=None,
dnn_hidden_units=None,
dnn_activation_fn=nn.relu,
dnn_dropout=None,
gradient_clip_norm=None,
enable_centered_bias=None,
target_dimension=1,
config=None,
feature_engineering_fn=None):
"""Initializes a DNNLinearCombinedRegressor instance.
Args:
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator
to continue training a previously saved model.
weight_column_name: A string defining feature column name representing
weights. It is used to down weight or boost examples during training. It
will be multiplied by the loss of the example.
linear_feature_columns: An iterable containing all the feature columns
used by linear part of the model. All items in the set must be
instances of classes derived from `FeatureColumn`.
linear_optimizer: An instance of `tf.Optimizer` used to apply gradients to
the linear part of the model. If `None`, will use a FTRL optimizer.
_joint_linear_weights: If True a single (possibly partitioned) variable
will be used to store the linear model weights. It's faster, but
requires that all columns are sparse and have the 'sum' combiner.
dnn_feature_columns: An iterable containing all the feature columns used
by deep part of the model. All items in the set must be instances of
classes derived from `FeatureColumn`.
dnn_optimizer: An instance of `tf.Optimizer` used to apply gradients to
the deep part of the model. If `None`, will use an Adagrad optimizer.
dnn_hidden_units: List of hidden units per layer. All layers are fully
connected.
dnn_activation_fn: Activation function applied to each layer. If None,
will use `tf.nn.relu`.
dnn_dropout: When not None, the probability we will drop out
a given coordinate.
gradient_clip_norm: A float > 0. If provided, gradients are clipped
to their global norm with this clipping ratio. See
tf.clip_by_global_norm for more details.
enable_centered_bias: A bool. If True, estimator will learn a centered
bias variable for each class. Rest of the model structure learns the
residual after centered bias.
target_dimension: TODO(zakaria): dimension of the target for multilabels.
config: RunConfig object to configure the runtime settings.
feature_engineering_fn: Feature engineering function. Takes features and
targets which are the output of `input_fn` and
returns features and targets which will be fed
into the model.
Raises:
ValueError: If both linear_feature_columns and dnn_features_columns are
empty at the same time.
"""
if enable_centered_bias is None:
enable_centered_bias = True
_changing_default_center_bias()
target_column = layers.regression_target(
weight_column_name=weight_column_name,
target_dimension=target_dimension)
super(DNNLinearCombinedRegressor, self).__init__(
model_dir=model_dir,
linear_feature_columns=linear_feature_columns,
linear_optimizer=linear_optimizer,
_joint_linear_weights=_joint_linear_weights,
dnn_feature_columns=dnn_feature_columns,
dnn_optimizer=dnn_optimizer,
dnn_hidden_units=dnn_hidden_units,
dnn_activation_fn=dnn_activation_fn,
dnn_dropout=dnn_dropout,
gradient_clip_norm=gradient_clip_norm,
enable_centered_bias=enable_centered_bias,
target_column=target_column,
config=config,
feature_engineering_fn=feature_engineering_fn) | [
"def",
"__init__",
"(",
"self",
",",
"# _joint_linear_weights pylint: disable=invalid-name",
"model_dir",
"=",
"None",
",",
"weight_column_name",
"=",
"None",
",",
"linear_feature_columns",
"=",
"None",
",",
"linear_optimizer",
"=",
"None",
",",
"_joint_linear_weights",
... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py#L581-L662 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_vim.py | python | EditraCommander.SelectLines | (self, repeat) | Select specified number of lines starting with current line
and going down
@param repeat: int | Select specified number of lines starting with current line
and going down
@param repeat: int | [
"Select",
"specified",
"number",
"of",
"lines",
"starting",
"with",
"current",
"line",
"and",
"going",
"down",
"@param",
"repeat",
":",
"int"
] | def SelectLines(self, repeat):
"""Select specified number of lines starting with current line
and going down
@param repeat: int
"""
cline = self.stc.GetCurrentLine()
lline = self.stc.GetLineCount() - 1
self.GotoLineStart()
if cline == lline:
cpos = self.stc.GetCurrentPos() - len(self.stc.GetEOLChar())
cpos = max(0, cpos)
self.stc.GotoPos(cpos)
self.PushCaret()
self.MoveDown(repeat)
self.StartSelection()
self.PopCaret()
self.EndSelection() | [
"def",
"SelectLines",
"(",
"self",
",",
"repeat",
")",
":",
"cline",
"=",
"self",
".",
"stc",
".",
"GetCurrentLine",
"(",
")",
"lline",
"=",
"self",
".",
"stc",
".",
"GetLineCount",
"(",
")",
"-",
"1",
"self",
".",
"GotoLineStart",
"(",
")",
"if",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_vim.py#L163-L180 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/frame.py | python | Frame.interleave_columns | (self) | return result | Interleave Series columns of a table into a single column.
Converts the column major table `cols` into a row major column.
Parameters
----------
cols : input Table containing columns to interleave.
Examples
--------
>>> df = DataFrame([['A1', 'A2', 'A3'], ['B1', 'B2', 'B3']])
>>> df
0 [A1, A2, A3]
1 [B1, B2, B3]
>>> df.interleave_columns()
0 A1
1 B1
2 A2
3 B2
4 A3
5 B3
Returns
-------
The interleaved columns as a single column | Interleave Series columns of a table into a single column. | [
"Interleave",
"Series",
"columns",
"of",
"a",
"table",
"into",
"a",
"single",
"column",
"."
] | def interleave_columns(self):
"""
Interleave Series columns of a table into a single column.
Converts the column major table `cols` into a row major column.
Parameters
----------
cols : input Table containing columns to interleave.
Examples
--------
>>> df = DataFrame([['A1', 'A2', 'A3'], ['B1', 'B2', 'B3']])
>>> df
0 [A1, A2, A3]
1 [B1, B2, B3]
>>> df.interleave_columns()
0 A1
1 B1
2 A2
3 B2
4 A3
5 B3
Returns
-------
The interleaved columns as a single column
"""
if ("category" == self.dtypes).any():
raise ValueError(
"interleave_columns does not support 'category' dtype."
)
result = self._constructor_sliced(
libcudf.reshape.interleave_columns(self)
)
return result | [
"def",
"interleave_columns",
"(",
"self",
")",
":",
"if",
"(",
"\"category\"",
"==",
"self",
".",
"dtypes",
")",
".",
"any",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"interleave_columns does not support 'category' dtype.\"",
")",
"result",
"=",
"self",
".",
... | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/frame.py#L2402-L2439 | |
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/app/internal/amber_file_parser.py | python | PrmtopLoader.get14Interactions | (self) | return returnList | Return list of atom pairs, chargeProduct, rMin and epsilon for each 1-4 interaction | Return list of atom pairs, chargeProduct, rMin and epsilon for each 1-4 interaction | [
"Return",
"list",
"of",
"atom",
"pairs",
"chargeProduct",
"rMin",
"and",
"epsilon",
"for",
"each",
"1",
"-",
"4",
"interaction"
] | def get14Interactions(self):
"""Return list of atom pairs, chargeProduct, rMin and epsilon for each 1-4 interaction"""
dihedralPointers = self._raw_data["DIHEDRALS_INC_HYDROGEN"] \
+self._raw_data["DIHEDRALS_WITHOUT_HYDROGEN"]
returnList=[]
charges=self.getCharges()
length_conv = units.angstrom.conversion_factor_to(units.nanometers)
ene_conv = units.kilocalories_per_mole.conversion_factor_to(
units.kilojoules_per_mole)
if self.chamber:
parm_acoef = [float(x) for x in self._raw_data['LENNARD_JONES_14_ACOEF']]
parm_bcoef = [float(x) for x in self._raw_data['LENNARD_JONES_14_BCOEF']]
else:
parm_acoef = [float(x) for x in self._raw_data['LENNARD_JONES_ACOEF']]
parm_bcoef = [float(x) for x in self._raw_data['LENNARD_JONES_BCOEF']]
nbidx = [int(x) for x in self._raw_data['NONBONDED_PARM_INDEX']]
numTypes = self.getNumTypes()
atomTypeIndexes=self._getAtomTypeIndexes()
for ii in range(0, len(dihedralPointers), 5):
if int(dihedralPointers[ii+2])>0 and int(dihedralPointers[ii+3])>0:
iAtom = int(dihedralPointers[ii])//3
lAtom = int(dihedralPointers[ii+3])//3
iidx = int(dihedralPointers[ii+4]) - 1
chargeProd = charges[iAtom]*charges[lAtom]
typ1 = atomTypeIndexes[iAtom] - 1
typ2 = atomTypeIndexes[lAtom] - 1
idx = nbidx[numTypes*typ1+typ2] - 1
if idx < 0: continue
a = parm_acoef[idx]
b = parm_bcoef[idx]
try:
epsilon = b * b / (4 * a) * ene_conv
rMin = (2 * a / b) ** (1/6.0) * length_conv
except ZeroDivisionError:
rMin = 1
epsilon = 0
try:
iScee = float(self._raw_data['SCEE_SCALE_FACTOR'][iidx])
except KeyError:
iScee = 1.0 if self.chamber else 1.2
try:
iScnb = float(self._raw_data['SCNB_SCALE_FACTOR'][iidx])
except KeyError:
iScnb = 1.0 if self.chamber else 2.0
returnList.append((iAtom, lAtom, chargeProd, rMin, epsilon, iScee, iScnb))
return returnList | [
"def",
"get14Interactions",
"(",
"self",
")",
":",
"dihedralPointers",
"=",
"self",
".",
"_raw_data",
"[",
"\"DIHEDRALS_INC_HYDROGEN\"",
"]",
"+",
"self",
".",
"_raw_data",
"[",
"\"DIHEDRALS_WITHOUT_HYDROGEN\"",
"]",
"returnList",
"=",
"[",
"]",
"charges",
"=",
... | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/internal/amber_file_parser.py#L581-L626 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xpathParserContext.xpathDivValues | (self) | Implement the div operation on XPath objects @arg1 / @arg2:
The numeric operators convert their operands to numbers as
if by calling the number function. | Implement the div operation on XPath objects | [
"Implement",
"the",
"div",
"operation",
"on",
"XPath",
"objects"
] | def xpathDivValues(self):
"""Implement the div operation on XPath objects @arg1 / @arg2:
The numeric operators convert their operands to numbers as
if by calling the number function. """
libxml2mod.xmlXPathDivValues(self._o) | [
"def",
"xpathDivValues",
"(",
"self",
")",
":",
"libxml2mod",
".",
"xmlXPathDivValues",
"(",
"self",
".",
"_o",
")"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L7434-L7438 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/symbol/symbol.py | python | zeros | (shape, dtype=None, **kwargs) | return _internal._zeros(shape=shape, dtype=dtype, **kwargs) | Returns a new symbol of given shape and type, filled with zeros.
Parameters
----------
shape : int or sequence of ints
Shape of the new array.
dtype : str or numpy.dtype, optional
The value type of the inner value, default to ``np.float32``.
Returns
-------
out : Symbol
The created Symbol. | Returns a new symbol of given shape and type, filled with zeros. | [
"Returns",
"a",
"new",
"symbol",
"of",
"given",
"shape",
"and",
"type",
"filled",
"with",
"zeros",
"."
] | def zeros(shape, dtype=None, **kwargs):
"""Returns a new symbol of given shape and type, filled with zeros.
Parameters
----------
shape : int or sequence of ints
Shape of the new array.
dtype : str or numpy.dtype, optional
The value type of the inner value, default to ``np.float32``.
Returns
-------
out : Symbol
The created Symbol.
"""
if dtype is None:
dtype = _numpy.float32
return _internal._zeros(shape=shape, dtype=dtype, **kwargs) | [
"def",
"zeros",
"(",
"shape",
",",
"dtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"_numpy",
".",
"float32",
"return",
"_internal",
".",
"_zeros",
"(",
"shape",
"=",
"shape",
",",
"dtype",
"=... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/symbol/symbol.py#L2703-L2720 | |
anestisb/oatdump_plus | ba858c1596598f0d9ae79c14d08c708cecc50af3 | tools/cpplint.py | python | FileInfo.Extension | (self) | return self.Split()[2] | File extension - text following the final period. | File extension - text following the final period. | [
"File",
"extension",
"-",
"text",
"following",
"the",
"final",
"period",
"."
] | def Extension(self):
"""File extension - text following the final period."""
return self.Split()[2] | [
"def",
"Extension",
"(",
"self",
")",
":",
"return",
"self",
".",
"Split",
"(",
")",
"[",
"2",
"]"
] | https://github.com/anestisb/oatdump_plus/blob/ba858c1596598f0d9ae79c14d08c708cecc50af3/tools/cpplint.py#L845-L847 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/policy.py | python | python_policies_to_pyspiel_policies | (policies) | return [python_policy_to_pyspiel_policy(p) for p in policies] | Same conversion as above (list version).
Args:
policies: a list of python.TabularPolicy
Returns:
a list of pyspiel.TabularPolicy. | Same conversion as above (list version). | [
"Same",
"conversion",
"as",
"above",
"(",
"list",
"version",
")",
"."
] | def python_policies_to_pyspiel_policies(policies):
"""Same conversion as above (list version).
Args:
policies: a list of python.TabularPolicy
Returns:
a list of pyspiel.TabularPolicy.
"""
return [python_policy_to_pyspiel_policy(p) for p in policies] | [
"def",
"python_policies_to_pyspiel_policies",
"(",
"policies",
")",
":",
"return",
"[",
"python_policy_to_pyspiel_policy",
"(",
"p",
")",
"for",
"p",
"in",
"policies",
"]"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/policy.py#L533-L542 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/blocks.py | python | InitBlock.__init__ | (self, config) | Initialization.
Args:
config: tf.contrib.training.HParams object; specifies hyperparameters | Initialization. | [
"Initialization",
"."
] | def __init__(self, config):
"""Initialization.
Args:
config: tf.contrib.training.HParams object; specifies hyperparameters
"""
super(InitBlock, self).__init__(config.dtype)
self.config = config
self.axis = 1 if self.config.data_format == "channels_first" else 3
self.conv2d = tf.keras.layers.Conv2D(
filters=self.config.init_filters,
kernel_size=self.config.init_kernel,
strides=(self.config.init_stride, self.config.init_stride),
data_format=self.config.data_format,
use_bias=False,
padding="SAME",
input_shape=self.config.input_shape,
dtype=self.config.dtype)
self.batch_norm = tf.keras.layers.BatchNormalization(
axis=self.axis, fused=self.config.fused, dtype=self.config.dtype)
self.activation = tf.keras.layers.Activation("relu",
dtype=self.config.dtype)
if self.config.init_max_pool:
self.max_pool = tf.keras.layers.MaxPooling2D(
pool_size=(3, 3),
strides=(2, 2),
padding="SAME",
data_format=self.config.data_format,
dtype=self.config.dtype) | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"super",
"(",
"InitBlock",
",",
"self",
")",
".",
"__init__",
"(",
"config",
".",
"dtype",
")",
"self",
".",
"config",
"=",
"config",
"self",
".",
"axis",
"=",
"1",
"if",
"self",
".",
"config... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/blocks.py#L413-L442 | ||
sfzhang15/FaceBoxes | b52cc92f9362d3adc08d54666aeb9ebb62fdb7da | tools/extra/parse_log.py | python | write_csv | (output_filename, dict_list, delimiter, verbose=False) | Write a CSV file | Write a CSV file | [
"Write",
"a",
"CSV",
"file"
] | def write_csv(output_filename, dict_list, delimiter, verbose=False):
"""Write a CSV file
"""
if not dict_list:
if verbose:
print('Not writing %s; no lines to write' % output_filename)
return
dialect = csv.excel
dialect.delimiter = delimiter
with open(output_filename, 'w') as f:
dict_writer = csv.DictWriter(f, fieldnames=dict_list[0].keys(),
dialect=dialect)
dict_writer.writeheader()
dict_writer.writerows(dict_list)
if verbose:
print 'Wrote %s' % output_filename | [
"def",
"write_csv",
"(",
"output_filename",
",",
"dict_list",
",",
"delimiter",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"not",
"dict_list",
":",
"if",
"verbose",
":",
"print",
"(",
"'Not writing %s; no lines to write'",
"%",
"output_filename",
")",
"return... | https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/tools/extra/parse_log.py#L150-L168 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/motionplanning.py | python | CSpaceInterface.setDistance | (self, pyDist) | return _motionplanning.CSpaceInterface_setDistance(self, pyDist) | setDistance(CSpaceInterface self, PyObject * pyDist) | setDistance(CSpaceInterface self, PyObject * pyDist) | [
"setDistance",
"(",
"CSpaceInterface",
"self",
"PyObject",
"*",
"pyDist",
")"
] | def setDistance(self, pyDist):
"""
setDistance(CSpaceInterface self, PyObject * pyDist)
"""
return _motionplanning.CSpaceInterface_setDistance(self, pyDist) | [
"def",
"setDistance",
"(",
"self",
",",
"pyDist",
")",
":",
"return",
"_motionplanning",
".",
"CSpaceInterface_setDistance",
"(",
"self",
",",
"pyDist",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/motionplanning.py#L406-L413 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py | python | MH.get_string | (self, key) | Return a string representation or raise a KeyError. | Return a string representation or raise a KeyError. | [
"Return",
"a",
"string",
"representation",
"or",
"raise",
"a",
"KeyError",
"."
] | def get_string(self, key):
"""Return a string representation or raise a KeyError."""
try:
if self._locked:
f = open(os.path.join(self._path, str(key)), 'r+')
else:
f = open(os.path.join(self._path, str(key)), 'r')
except IOError, e:
if e.errno == errno.ENOENT:
raise KeyError('No message with key: %s' % key)
else:
raise
try:
if self._locked:
_lock_file(f)
try:
return f.read()
finally:
if self._locked:
_unlock_file(f)
finally:
f.close() | [
"def",
"get_string",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"if",
"self",
".",
"_locked",
":",
"f",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"str",
"(",
"key",
")",
")",
",",
"'r+'",
")",
"else... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py#L1021-L1042 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/pgen2/grammar.py | python | Grammar.report | (self) | Dump the grammar tables to standard output, for debugging. | Dump the grammar tables to standard output, for debugging. | [
"Dump",
"the",
"grammar",
"tables",
"to",
"standard",
"output",
"for",
"debugging",
"."
] | def report(self):
"""Dump the grammar tables to standard output, for debugging."""
from pprint import pprint
print "s2n"
pprint(self.symbol2number)
print "n2s"
pprint(self.number2symbol)
print "states"
pprint(self.states)
print "dfas"
pprint(self.dfas)
print "labels"
pprint(self.labels)
print "start", self.start | [
"def",
"report",
"(",
"self",
")",
":",
"from",
"pprint",
"import",
"pprint",
"print",
"\"s2n\"",
"pprint",
"(",
"self",
".",
"symbol2number",
")",
"print",
"\"n2s\"",
"pprint",
"(",
"self",
".",
"number2symbol",
")",
"print",
"\"states\"",
"pprint",
"(",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/pgen2/grammar.py#L113-L126 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/minimum-cost-tree-from-leaf-values.py | python | Solution.mctFromLeafValues | (self, arr) | return result | :type arr: List[int]
:rtype: int | :type arr: List[int]
:rtype: int | [
":",
"type",
"arr",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def mctFromLeafValues(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
result = 0
stk = [float("inf")]
for x in arr:
while stk[-1] <= x:
result += stk.pop() * min(stk[-1], x)
stk.append(x)
while len(stk) > 2:
result += stk.pop() * stk[-1]
return result | [
"def",
"mctFromLeafValues",
"(",
"self",
",",
"arr",
")",
":",
"result",
"=",
"0",
"stk",
"=",
"[",
"float",
"(",
"\"inf\"",
")",
"]",
"for",
"x",
"in",
"arr",
":",
"while",
"stk",
"[",
"-",
"1",
"]",
"<=",
"x",
":",
"result",
"+=",
"stk",
".",... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/minimum-cost-tree-from-leaf-values.py#L5-L18 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGrid.IsFrozen | (*args, **kwargs) | return _propgrid.PropertyGrid_IsFrozen(*args, **kwargs) | IsFrozen(self) -> bool
Returns ``True`` if the window has been frozen and not thawed yet.
:see: `Freeze` and `Thaw` | IsFrozen(self) -> bool | [
"IsFrozen",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsFrozen(*args, **kwargs):
"""
IsFrozen(self) -> bool
Returns ``True`` if the window has been frozen and not thawed yet.
:see: `Freeze` and `Thaw`
"""
return _propgrid.PropertyGrid_IsFrozen(*args, **kwargs) | [
"def",
"IsFrozen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_IsFrozen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2173-L2181 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/external/eigen_archive/debug/gdb/printers.py | python | EigenMatrixPrinter.__init__ | (self, variety, val) | Extract all the necessary information | Extract all the necessary information | [
"Extract",
"all",
"the",
"necessary",
"information"
] | def __init__(self, variety, val):
"Extract all the necessary information"
# Save the variety (presumably "Matrix" or "Array") for later usage
self.variety = variety
# The gdb extension does not support value template arguments - need to extract them by hand
type = val.type
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
self.type = type.unqualified().strip_typedefs()
tag = self.type.tag
regex = re.compile('\<.*\>')
m = regex.findall(tag)[0][1:-1]
template_params = m.split(',')
template_params = [x.replace(" ", "") for x in template_params]
if template_params[1] == '-0x00000000000000001' or template_params[1] == '-0x000000001' or template_params[1] == '-1':
self.rows = val['m_storage']['m_rows']
else:
self.rows = int(template_params[1])
if template_params[2] == '-0x00000000000000001' or template_params[2] == '-0x000000001' or template_params[2] == '-1':
self.cols = val['m_storage']['m_cols']
else:
self.cols = int(template_params[2])
self.options = 0 # default value
if len(template_params) > 3:
self.options = template_params[3];
self.rowMajor = (int(self.options) & 0x1)
self.innerType = self.type.template_argument(0)
self.val = val
# Fixed size matrices have a struct as their storage, so we need to walk through this
self.data = self.val['m_storage']['m_data']
if self.data.type.code == gdb.TYPE_CODE_STRUCT:
self.data = self.data['array']
self.data = self.data.cast(self.innerType.pointer()) | [
"def",
"__init__",
"(",
"self",
",",
"variety",
",",
"val",
")",
":",
"# Save the variety (presumably \"Matrix\" or \"Array\") for later usage",
"self",
".",
"variety",
"=",
"variety",
"# The gdb extension does not support value template arguments - need to extract them by hand",
"... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/eigen_archive/debug/gdb/printers.py#L37-L78 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_vehicle.py | python | VehicleDomain.setEmissionClass | (self, vehID, clazz) | setEmissionClass(string, string) -> None
Sets the emission class for this vehicle. | setEmissionClass(string, string) -> None | [
"setEmissionClass",
"(",
"string",
"string",
")",
"-",
">",
"None"
] | def setEmissionClass(self, vehID, clazz):
"""setEmissionClass(string, string) -> None
Sets the emission class for this vehicle.
"""
self._setCmd(tc.VAR_EMISSIONCLASS, vehID, "s", clazz) | [
"def",
"setEmissionClass",
"(",
"self",
",",
"vehID",
",",
"clazz",
")",
":",
"self",
".",
"_setCmd",
"(",
"tc",
".",
"VAR_EMISSIONCLASS",
",",
"vehID",
",",
"\"s\"",
",",
"clazz",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L1394-L1399 | ||
unrealcv/unrealcv | 19305da8554c3a0e683a5e27a1e487cc2cf42776 | examples/WIP/ipynb_util.py | python | generate_objectcatetory_json | (scene_objects) | Get object category from object name, with some manual editing | Get object category from object name, with some manual editing | [
"Get",
"object",
"category",
"from",
"object",
"name",
"with",
"some",
"manual",
"editing"
] | def generate_objectcatetory_json(scene_objects):
# Use http://www.jsoneditoronline.org/ to clean the json
# http://jsonformat.com/#jsondataurllabel
''' Get object category from object name, with some manual editing '''
print '{'
for obj in scene_objects:
objtype = obj.replace('SM_', '').split('_')[0].replace('BookLP', 'Book').replace('Wire1', 'Wire')
print ' ', repr(obj), ':', repr(objtype), ','
print '}' | [
"def",
"generate_objectcatetory_json",
"(",
"scene_objects",
")",
":",
"# Use http://www.jsoneditoronline.org/ to clean the json",
"# http://jsonformat.com/#jsondataurllabel",
"print",
"'{'",
"for",
"obj",
"in",
"scene_objects",
":",
"objtype",
"=",
"obj",
".",
"replace",
"("... | https://github.com/unrealcv/unrealcv/blob/19305da8554c3a0e683a5e27a1e487cc2cf42776/examples/WIP/ipynb_util.py#L26-L34 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/json/decoder.py | python | JSONDecoder.__init__ | (self, encoding=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, strict=True,
object_pairs_hook=None) | ``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``.
``object_hook``, if specified, will be called with the result
of every JSON object decoded and its return value will be used in
place of the given ``dict``. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
``object_pairs_hook``, if specified will be called with the result of
every JSON object decoded with an ordered list of pairs. The return
value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders that rely on the
order that the key and value pairs are decoded (for example,
collections.OrderedDict will remember the order of insertion). If
``object_hook`` is also defined, the ``object_pairs_hook`` takes
priority.
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN.
This can be used to raise an exception if invalid JSON numbers
are encountered.
If ``strict`` is false (true is the default), then control
characters will be allowed inside strings. Control characters in
this context are those with character codes in the 0-31 range,
including ``'\\t'`` (tab), ``'\\n'``, ``'\\r'`` and ``'\\0'``. | ``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects. | [
"encoding",
"determines",
"the",
"encoding",
"used",
"to",
"interpret",
"any",
"str",
"objects",
"decoded",
"by",
"this",
"instance",
"(",
"utf",
"-",
"8",
"by",
"default",
")",
".",
"It",
"has",
"no",
"effect",
"when",
"decoding",
"unicode",
"objects",
".... | def __init__(self, encoding=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, strict=True,
object_pairs_hook=None):
"""``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``.
``object_hook``, if specified, will be called with the result
of every JSON object decoded and its return value will be used in
place of the given ``dict``. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
``object_pairs_hook``, if specified will be called with the result of
every JSON object decoded with an ordered list of pairs. The return
value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders that rely on the
order that the key and value pairs are decoded (for example,
collections.OrderedDict will remember the order of insertion). If
``object_hook`` is also defined, the ``object_pairs_hook`` takes
priority.
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN.
This can be used to raise an exception if invalid JSON numbers
are encountered.
If ``strict`` is false (true is the default), then control
characters will be allowed inside strings. Control characters in
this context are those with character codes in the 0-31 range,
including ``'\\t'`` (tab), ``'\\n'``, ``'\\r'`` and ``'\\0'``.
"""
self.encoding = encoding
self.object_hook = object_hook
self.object_pairs_hook = object_pairs_hook
self.parse_float = parse_float or float
self.parse_int = parse_int or int
self.parse_constant = parse_constant or _CONSTANTS.__getitem__
self.strict = strict
self.parse_object = JSONObject
self.parse_array = JSONArray
self.parse_string = scanstring
self.scan_once = scanner.make_scanner(self) | [
"def",
"__init__",
"(",
"self",
",",
"encoding",
"=",
"None",
",",
"object_hook",
"=",
"None",
",",
"parse_float",
"=",
"None",
",",
"parse_int",
"=",
"None",
",",
"parse_constant",
"=",
"None",
",",
"strict",
"=",
"True",
",",
"object_pairs_hook",
"=",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/json/decoder.py#L303-L358 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/pyserial/serial/serialwin32.py | python | Serial.set_output_flow_control | (self, enable=True) | \
Manually control flow - when software flow control is enabled.
This will do the same as if XON (true) or XOFF (false) are received
from the other device and control the transmission accordingly.
WARNING: this function is not portable to different platforms! | \
Manually control flow - when software flow control is enabled.
This will do the same as if XON (true) or XOFF (false) are received
from the other device and control the transmission accordingly.
WARNING: this function is not portable to different platforms! | [
"\\",
"Manually",
"control",
"flow",
"-",
"when",
"software",
"flow",
"control",
"is",
"enabled",
".",
"This",
"will",
"do",
"the",
"same",
"as",
"if",
"XON",
"(",
"true",
")",
"or",
"XOFF",
"(",
"false",
")",
"are",
"received",
"from",
"the",
"other",... | def set_output_flow_control(self, enable=True):
"""\
Manually control flow - when software flow control is enabled.
This will do the same as if XON (true) or XOFF (false) are received
from the other device and control the transmission accordingly.
WARNING: this function is not portable to different platforms!
"""
if not self.is_open:
raise portNotOpenError
if enable:
win32.EscapeCommFunction(self._port_handle, win32.SETXON)
else:
win32.EscapeCommFunction(self._port_handle, win32.SETXOFF) | [
"def",
"set_output_flow_control",
"(",
"self",
",",
"enable",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"portNotOpenError",
"if",
"enable",
":",
"win32",
".",
"EscapeCommFunction",
"(",
"self",
".",
"_port_handle",
",",
"win32... | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialwin32.py#L425-L437 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/deviceufunc.py | python | _broadcast_axis | (a, b) | Raises
------
ValueError if broadcast fails | Raises
------
ValueError if broadcast fails | [
"Raises",
"------",
"ValueError",
"if",
"broadcast",
"fails"
] | def _broadcast_axis(a, b):
"""
Raises
------
ValueError if broadcast fails
"""
if a == b:
return a
elif a == 1:
return b
elif b == 1:
return a
else:
raise ValueError("failed to broadcast {0} and {1}".format(a, b)) | [
"def",
"_broadcast_axis",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
"==",
"b",
":",
"return",
"a",
"elif",
"a",
"==",
"1",
":",
"return",
"b",
"elif",
"b",
"==",
"1",
":",
"return",
"a",
"else",
":",
"raise",
"ValueError",
"(",
"\"failed to broadcas... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/deviceufunc.py#L22-L35 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/imputils.py | python | _IternextResult.is_valid | (self) | return self._context.get_argument_value(self._builder,
types.boolean,
self._pairobj.second) | Return whether the iterator is marked valid. | Return whether the iterator is marked valid. | [
"Return",
"whether",
"the",
"iterator",
"is",
"marked",
"valid",
"."
] | def is_valid(self):
"""
Return whether the iterator is marked valid.
"""
return self._context.get_argument_value(self._builder,
types.boolean,
self._pairobj.second) | [
"def",
"is_valid",
"(",
"self",
")",
":",
"return",
"self",
".",
"_context",
".",
"get_argument_value",
"(",
"self",
".",
"_builder",
",",
"types",
".",
"boolean",
",",
"self",
".",
"_pairobj",
".",
"second",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/imputils.py#L283-L289 | |
dmlc/treelite | df56babb6a4a2d7c29d719c28ce53acfa7dbab3c | python/setup.py | python | BuildExt.build_extension | (self, ext) | Override the method for dispatching. | Override the method for dispatching. | [
"Override",
"the",
"method",
"for",
"dispatching",
"."
] | def build_extension(self, ext):
"""Override the method for dispatching."""
if isinstance(ext, CMakeExtension):
self.build_cmake_extension()
else:
super().build_extension(ext) | [
"def",
"build_extension",
"(",
"self",
",",
"ext",
")",
":",
"if",
"isinstance",
"(",
"ext",
",",
"CMakeExtension",
")",
":",
"self",
".",
"build_cmake_extension",
"(",
")",
"else",
":",
"super",
"(",
")",
".",
"build_extension",
"(",
"ext",
")"
] | https://github.com/dmlc/treelite/blob/df56babb6a4a2d7c29d719c28ce53acfa7dbab3c/python/setup.py#L161-L166 | ||
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/generator/msvs.py | python | _RuleExpandPath | (path, input_file) | return path | Given the input file to which a rule applied, string substitute a path.
Arguments:
path: a path to string expand
input_file: the file to which the rule applied.
Returns:
The string substituted path. | Given the input file to which a rule applied, string substitute a path. | [
"Given",
"the",
"input",
"file",
"to",
"which",
"a",
"rule",
"applied",
"string",
"substitute",
"a",
"path",
"."
] | def _RuleExpandPath(path, input_file):
"""Given the input file to which a rule applied, string substitute a path.
Arguments:
path: a path to string expand
input_file: the file to which the rule applied.
Returns:
The string substituted path.
"""
path = path.replace('$(InputName)',
os.path.splitext(os.path.split(input_file)[1])[0])
path = path.replace('$(InputDir)', os.path.dirname(input_file))
path = path.replace('$(InputExt)',
os.path.splitext(os.path.split(input_file)[1])[1])
path = path.replace('$(InputFileName)', os.path.split(input_file)[1])
path = path.replace('$(InputPath)', input_file)
return path | [
"def",
"_RuleExpandPath",
"(",
"path",
",",
"input_file",
")",
":",
"path",
"=",
"path",
".",
"replace",
"(",
"'$(InputName)'",
",",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"split",
"(",
"input_file",
")",
"[",
"1",
"]",
")",... | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/msvs.py#L468-L484 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/runtime.py | python | LoopContext.revindex | (self) | return self.length - self.index0 | Number of iterations from the end of the loop, ending at 1.
Requires calculating :attr:`length`. | Number of iterations from the end of the loop, ending at 1. | [
"Number",
"of",
"iterations",
"from",
"the",
"end",
"of",
"the",
"loop",
"ending",
"at",
"1",
"."
] | def revindex(self) -> int:
"""Number of iterations from the end of the loop, ending at 1.
Requires calculating :attr:`length`.
"""
return self.length - self.index0 | [
"def",
"revindex",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"length",
"-",
"self",
".",
"index0"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/runtime.py#L519-L524 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/utils/ipstruct.py | python | Struct.hasattr | (self, key) | return key in self | hasattr function available as a method.
Implemented like has_key.
Examples
--------
>>> s = Struct(a=10)
>>> s.hasattr('a')
True
>>> s.hasattr('b')
False
>>> s.hasattr('get')
False | hasattr function available as a method. | [
"hasattr",
"function",
"available",
"as",
"a",
"method",
"."
] | def hasattr(self, key):
"""hasattr function available as a method.
Implemented like has_key.
Examples
--------
>>> s = Struct(a=10)
>>> s.hasattr('a')
True
>>> s.hasattr('b')
False
>>> s.hasattr('get')
False
"""
return key in self | [
"def",
"hasattr",
"(",
"self",
",",
"key",
")",
":",
"return",
"key",
"in",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/utils/ipstruct.py#L247-L263 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/client/timeline.py | python | Timeline._show_memory_counters | (self) | Produce a counter series for each memory allocator. | Produce a counter series for each memory allocator. | [
"Produce",
"a",
"counter",
"series",
"for",
"each",
"memory",
"allocator",
"."
] | def _show_memory_counters(self):
"""Produce a counter series for each memory allocator."""
# Iterate over all tensor trackers to build a list of allocations and
# frees for each allocator. Then sort the lists and emit a cumulative
# counter series for each allocator.
allocations = {}
for name in self._tensors:
tensor = self._tensors[name]
self._chrome_trace.emit_obj_delete('Tensor', name, tensor.last_unref,
tensor.pid, 0, tensor.object_id)
allocator = tensor.allocator
if allocator not in allocations:
allocations[allocator] = []
num_bytes = tensor.num_bytes
allocations[allocator].append((tensor.create_time, num_bytes, name))
allocations[allocator].append((tensor.last_unref, -num_bytes, name))
alloc_maxes = {}
# Generate a counter series showing total allocations for each allocator.
for allocator in allocations:
alloc_list = allocations[allocator]
alloc_list.sort()
total_bytes = 0
alloc_tensor_set = set()
alloc_maxes[allocator] = AllocationMaximum(
timestamp=0, num_bytes=0, tensors=set())
for time, num_bytes, name in alloc_list:
total_bytes += num_bytes
if num_bytes < 0:
alloc_tensor_set.discard(name)
else:
alloc_tensor_set.add(name)
if total_bytes > alloc_maxes[allocator].num_bytes:
alloc_maxes[allocator] = AllocationMaximum(
timestamp=time,
num_bytes=total_bytes,
tensors=copy.deepcopy(alloc_tensor_set))
self._chrome_trace.emit_counter('Memory', allocator,
self._allocators_pid, time, allocator,
total_bytes)
self._allocator_maximums = alloc_maxes | [
"def",
"_show_memory_counters",
"(",
"self",
")",
":",
"# Iterate over all tensor trackers to build a list of allocations and",
"# frees for each allocator. Then sort the lists and emit a cumulative",
"# counter series for each allocator.",
"allocations",
"=",
"{",
"}",
"for",
"name",
... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/client/timeline.py#L564-L607 | ||
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | panreas_hnn/hed-globalweight/scripts/cpp_lint.py | python | CheckForMultilineCommentsAndStrings | (filename, clean_lines, linenum, error) | Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Logs an error if we see /* ... */ or "..." that extend past one line. | [
"Logs",
"an",
"error",
"if",
"we",
"see",
"/",
"*",
"...",
"*",
"/",
"or",
"...",
"that",
"extend",
"past",
"one",
"line",
"."
] | def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
"""Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Remove all \\ (escaped backslashes) from the line. They are OK, and the
# second (escaped) slash may trigger later \" detection erroneously.
line = line.replace('\\\\', '')
if line.count('/*') > line.count('*/'):
error(filename, linenum, 'readability/multiline_comment', 5,
'Complex multi-line /*...*/-style comment found. '
'Lint may give bogus warnings. '
'Consider replacing these with //-style comments, '
'with #if 0...#endif, '
'or with more clearly structured multi-line comments.')
if (line.count('"') - line.count('\\"')) % 2:
error(filename, linenum, 'readability/multiline_string', 5,
'Multi-line string ("...") found. This lint script doesn\'t '
'do well with such strings, and may give bogus warnings. '
'Use C++11 raw strings or concatenation instead.') | [
"def",
"CheckForMultilineCommentsAndStrings",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the",
"# secon... | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/scripts/cpp_lint.py#L1526-L1561 | ||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/petro/modelling.py | python | JointPetroInversion.__init__ | (self, managers, trans, verbose=False, debug=False, **kwargs) | TODO. | TODO. | [
"TODO",
"."
] | def __init__(self, managers, trans, verbose=False, debug=False, **kwargs):
"""TODO."""
pg.warn('do not use')
MethodManager.__init__(self, verbose=verbose, debug=debug, **kwargs)
self.managers = managers
self.trans = trans
self.fops = []
self.dataVals = pg.Vector(0)
self.dataErrs = pg.Vector(0)
self.mod = pg.Vector(0) # resulting model
self.data = None
self.tD = pg.trans.TransCumulative()
self.tM = managers[0].tM
for mgr in self.managers:
fop = mgr.createFOP(verbose)
fop.setVerbose(verbose=verbose)
self.fops.append(fop)
self.fop.setFopsAndTrans(self.fops, self.trans) | [
"def",
"__init__",
"(",
"self",
",",
"managers",
",",
"trans",
",",
"verbose",
"=",
"False",
",",
"debug",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"pg",
".",
"warn",
"(",
"'do not use'",
")",
"MethodManager",
".",
"__init__",
"(",
"self",
",... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/petro/modelling.py#L126-L147 | ||
eomahony/Numberjack | 53fa9e994a36f881ffd320d8d04158097190aad8 | Numberjack/__init__.py | python | Model.__iadd__ | (self, *expr) | return self | Can be used to add an expression or a collection of expressions to
the model like: `model += expression`
:param expr: Any number of (or nested lists of) Expression instances. | Can be used to add an expression or a collection of expressions to
the model like: `model += expression` | [
"Can",
"be",
"used",
"to",
"add",
"an",
"expression",
"or",
"a",
"collection",
"of",
"expressions",
"to",
"the",
"model",
"like",
":",
"model",
"+",
"=",
"expression"
] | def __iadd__(self, *expr):
"""Can be used to add an expression or a collection of expressions to
the model like: `model += expression`
:param expr: Any number of (or nested lists of) Expression instances.
"""
self.add_prime(expr)
return self | [
"def",
"__iadd__",
"(",
"self",
",",
"*",
"expr",
")",
":",
"self",
".",
"add_prime",
"(",
"expr",
")",
"return",
"self"
] | https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/__init__.py#L694-L701 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/front/kaldi/loader/utils.py | python | create_edge_attrs | (prev_layer_id: str, next_layer_id: str, tensor_name: str, in_port=0, out_port=0) | return {
'out': out_port,
'in': in_port,
'name': next_layer_id,
'fw_tensor_debug_info': [(prev_layer_id, tensor_name + ":" + str(out_port))],
'in_attrs': ['in', 'permutation'],
'out_attrs': ['out', 'permutation'],
'data_attrs': ['fw_tensor_debug_info']
} | Create common edge's attributes
:param prev_layer_id: id of previous layer
:param next_layer_id: id of next layer
:param tensor_name: framework tensor name
:param in_port: 'in' port
:param out_port: 'out' port
:return: dictionary contains common attributes for edge | Create common edge's attributes
:param prev_layer_id: id of previous layer
:param next_layer_id: id of next layer
:param tensor_name: framework tensor name
:param in_port: 'in' port
:param out_port: 'out' port
:return: dictionary contains common attributes for edge | [
"Create",
"common",
"edge",
"s",
"attributes",
":",
"param",
"prev_layer_id",
":",
"id",
"of",
"previous",
"layer",
":",
"param",
"next_layer_id",
":",
"id",
"of",
"next",
"layer",
":",
"param",
"tensor_name",
":",
"framework",
"tensor",
"name",
":",
"param"... | def create_edge_attrs(prev_layer_id: str, next_layer_id: str, tensor_name: str, in_port=0, out_port=0) -> dict:
"""
Create common edge's attributes
:param prev_layer_id: id of previous layer
:param next_layer_id: id of next layer
:param tensor_name: framework tensor name
:param in_port: 'in' port
:param out_port: 'out' port
:return: dictionary contains common attributes for edge
"""
return {
'out': out_port,
'in': in_port,
'name': next_layer_id,
'fw_tensor_debug_info': [(prev_layer_id, tensor_name + ":" + str(out_port))],
'in_attrs': ['in', 'permutation'],
'out_attrs': ['out', 'permutation'],
'data_attrs': ['fw_tensor_debug_info']
} | [
"def",
"create_edge_attrs",
"(",
"prev_layer_id",
":",
"str",
",",
"next_layer_id",
":",
"str",
",",
"tensor_name",
":",
"str",
",",
"in_port",
"=",
"0",
",",
"out_port",
"=",
"0",
")",
"->",
"dict",
":",
"return",
"{",
"'out'",
":",
"out_port",
",",
"... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/kaldi/loader/utils.py#L323-L341 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/decorators.py | python | Isolated | (*args) | return _Isolated | Decorator for noting that tests must be run in isolation.
The test will be run by itself (not concurrently with any other tests)
if ANY of the args match the browser type, OS name, or OS version. | Decorator for noting that tests must be run in isolation. | [
"Decorator",
"for",
"noting",
"that",
"tests",
"must",
"be",
"run",
"in",
"isolation",
"."
] | def Isolated(*args):
"""Decorator for noting that tests must be run in isolation.
The test will be run by itself (not concurrently with any other tests)
if ANY of the args match the browser type, OS name, or OS version."""
def _Isolated(func):
if not isinstance(func, types.FunctionType):
func._isolated_strings = isolated_strings
return func
@functools.wraps(func)
def wrapper(*args, **kwargs):
func(*args, **kwargs)
wrapper._isolated_strings = isolated_strings
return wrapper
if len(args) == 1 and callable(args[0]):
isolated_strings = []
return _Isolated(args[0])
isolated_strings = list(args)
for isolated_string in isolated_strings:
# TODO(tonyg): Validate that these strings are recognized.
assert isinstance(isolated_string, str), 'Isolated accepts a list of strs'
return _Isolated | [
"def",
"Isolated",
"(",
"*",
"args",
")",
":",
"def",
"_Isolated",
"(",
"func",
")",
":",
"if",
"not",
"isinstance",
"(",
"func",
",",
"types",
".",
"FunctionType",
")",
":",
"func",
".",
"_isolated_strings",
"=",
"isolated_strings",
"return",
"func",
"@... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/decorators.py#L152-L173 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/fpformat.py | python | roundfrac | (intpart, fraction, digs) | Round or extend the fraction to size digs. | Round or extend the fraction to size digs. | [
"Round",
"or",
"extend",
"the",
"fraction",
"to",
"size",
"digs",
"."
] | def roundfrac(intpart, fraction, digs):
"""Round or extend the fraction to size digs."""
f = len(fraction)
if f <= digs:
return intpart, fraction + '0'*(digs-f)
i = len(intpart)
if i+digs < 0:
return '0'*-digs, ''
total = intpart + fraction
nextdigit = total[i+digs]
if nextdigit >= '5': # Hard case: increment last digit, may have carry!
n = i + digs - 1
while n >= 0:
if total[n] != '9': break
n = n-1
else:
total = '0' + total
i = i+1
n = 0
total = total[:n] + chr(ord(total[n]) + 1) + '0'*(len(total)-n-1)
intpart, fraction = total[:i], total[i:]
if digs >= 0:
return intpart, fraction[:digs]
else:
return intpart[:digs] + '0'*-digs, '' | [
"def",
"roundfrac",
"(",
"intpart",
",",
"fraction",
",",
"digs",
")",
":",
"f",
"=",
"len",
"(",
"fraction",
")",
"if",
"f",
"<=",
"digs",
":",
"return",
"intpart",
",",
"fraction",
"+",
"'0'",
"*",
"(",
"digs",
"-",
"f",
")",
"i",
"=",
"len",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/fpformat.py#L64-L88 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pgen2/driver.py | python | Driver.parse_stream | (self, stream, debug=False) | return self.parse_stream_raw(stream, debug) | Parse a stream and return the syntax tree. | Parse a stream and return the syntax tree. | [
"Parse",
"a",
"stream",
"and",
"return",
"the",
"syntax",
"tree",
"."
] | def parse_stream(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
return self.parse_stream_raw(stream, debug) | [
"def",
"parse_stream",
"(",
"self",
",",
"stream",
",",
"debug",
"=",
"False",
")",
":",
"return",
"self",
".",
"parse_stream_raw",
"(",
"stream",
",",
"debug",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pgen2/driver.py#L91-L93 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/mantid/fitfunctions.py | python | CompositeFunctionWrapper.__delitem__ | (self, index) | Delete item of given index from composite function.
**It should not be called directly.**
:param index: index of item | Delete item of given index from composite function. | [
"Delete",
"item",
"of",
"given",
"index",
"from",
"composite",
"function",
"."
] | def __delitem__(self, index):
"""
Delete item of given index from composite function.
**It should not be called directly.**
:param index: index of item
"""
self.fun.__delitem__(index) | [
"def",
"__delitem__",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"fun",
".",
"__delitem__",
"(",
"index",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/fitfunctions.py#L547-L555 | ||
clab/dynet | 93a5cd2d6aabeb8c506f07e51ef3a779506da68b | python/dynet_viz.py | python | BiRNNBuilder.transduce | (self, es) | return es | returns the list of output Expressions obtained by adding the given inputs
to the current state, one by one, to both the forward and backward RNNs,
and concatenating.
@param es: a list of Expression
see also add_inputs(xs)
.transduce(xs) is different from .add_inputs(xs) in the following way:
.add_inputs(xs) returns a list of RNNState pairs. RNNState objects can be
queried in various ways. In particular, they allow access to the previous
state, as well as to the state-vectors (h() and s() )
.transduce(xs) returns a list of Expression. These are just the output
expressions. For many cases, this suffices.
transduce is much more memory efficient than add_inputs. | returns the list of output Expressions obtained by adding the given inputs
to the current state, one by one, to both the forward and backward RNNs,
and concatenating.
@param es: a list of Expression | [
"returns",
"the",
"list",
"of",
"output",
"Expressions",
"obtained",
"by",
"adding",
"the",
"given",
"inputs",
"to",
"the",
"current",
"state",
"one",
"by",
"one",
"to",
"both",
"the",
"forward",
"and",
"backward",
"RNNs",
"and",
"concatenating",
".",
"@para... | def transduce(self, es):
"""
returns the list of output Expressions obtained by adding the given inputs
to the current state, one by one, to both the forward and backward RNNs,
and concatenating.
@param es: a list of Expression
see also add_inputs(xs)
.transduce(xs) is different from .add_inputs(xs) in the following way:
.add_inputs(xs) returns a list of RNNState pairs. RNNState objects can be
queried in various ways. In particular, they allow access to the previous
state, as well as to the state-vectors (h() and s() )
.transduce(xs) returns a list of Expression. These are just the output
expressions. For many cases, this suffices.
transduce is much more memory efficient than add_inputs.
"""
for e in es:
ensure_freshness(e)
for (fb,bb) in self.builder_layers:
fs = fb.initial_state().transduce(es)
bs = bb.initial_state().transduce(reversed(es))
es = [concatenate([f,b]) for f,b in zip(fs, reversed(bs))]
return es | [
"def",
"transduce",
"(",
"self",
",",
"es",
")",
":",
"for",
"e",
"in",
"es",
":",
"ensure_freshness",
"(",
"e",
")",
"for",
"(",
"fb",
",",
"bb",
")",
"in",
"self",
".",
"builder_layers",
":",
"fs",
"=",
"fb",
".",
"initial_state",
"(",
")",
"."... | https://github.com/clab/dynet/blob/93a5cd2d6aabeb8c506f07e51ef3a779506da68b/python/dynet_viz.py#L596-L622 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/cookies.py | python | RequestsCookieJar.iterkeys | (self) | Dict-like iterkeys() that returns an iterator of names of cookies
from the jar. See itervalues() and iteritems(). | Dict-like iterkeys() that returns an iterator of names of cookies
from the jar. See itervalues() and iteritems(). | [
"Dict",
"-",
"like",
"iterkeys",
"()",
"that",
"returns",
"an",
"iterator",
"of",
"names",
"of",
"cookies",
"from",
"the",
"jar",
".",
"See",
"itervalues",
"()",
"and",
"iteritems",
"()",
"."
] | def iterkeys(self):
"""Dict-like iterkeys() that returns an iterator of names of cookies
from the jar. See itervalues() and iteritems()."""
for cookie in iter(self):
yield cookie.name | [
"def",
"iterkeys",
"(",
"self",
")",
":",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"yield",
"cookie",
".",
"name"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/cookies.py#L204-L208 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py | python | LinkFunc | (target, source, env) | return 0 | Relative paths cause problems with symbolic links, so
we use absolute paths, which may be a problem for people
who want to move their soft-linked src-trees around. Those
people should use the 'hard-copy' mode, softlinks cannot be
used for that; at least I have no idea how ... | Relative paths cause problems with symbolic links, so
we use absolute paths, which may be a problem for people
who want to move their soft-linked src-trees around. Those
people should use the 'hard-copy' mode, softlinks cannot be
used for that; at least I have no idea how ... | [
"Relative",
"paths",
"cause",
"problems",
"with",
"symbolic",
"links",
"so",
"we",
"use",
"absolute",
"paths",
"which",
"may",
"be",
"a",
"problem",
"for",
"people",
"who",
"want",
"to",
"move",
"their",
"soft",
"-",
"linked",
"src",
"-",
"trees",
"around"... | def LinkFunc(target, source, env):
"""
Relative paths cause problems with symbolic links, so
we use absolute paths, which may be a problem for people
who want to move their soft-linked src-trees around. Those
people should use the 'hard-copy' mode, softlinks cannot be
used for that; at least I have no idea how ...
"""
src = source[0].get_abspath()
dest = target[0].get_abspath()
dir, file = os.path.split(dest)
if dir and not target[0].fs.isdir(dir):
os.makedirs(dir)
if not Link_Funcs:
# Set a default order of link functions.
set_duplicate('hard-soft-copy')
fs = source[0].fs
# Now link the files with the previously specified order.
for func in Link_Funcs:
try:
func(fs, src, dest)
break
except (IOError, OSError):
# An OSError indicates something happened like a permissions
# problem or an attempt to symlink across file-system
# boundaries. An IOError indicates something like the file
# not existing. In either case, keeping trying additional
# functions in the list and only raise an error if the last
# one failed.
if func == Link_Funcs[-1]:
# exception of the last link method (copy) are fatal
raise
return 0 | [
"def",
"LinkFunc",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"src",
"=",
"source",
"[",
"0",
"]",
".",
"get_abspath",
"(",
")",
"dest",
"=",
"target",
"[",
"0",
"]",
".",
"get_abspath",
"(",
")",
"dir",
",",
"file",
"=",
"os",
".",
"p... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py#L293-L325 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/numbers.py | python | Real.real | (self) | return +self | Real numbers are their real component. | Real numbers are their real component. | [
"Real",
"numbers",
"are",
"their",
"real",
"component",
"."
] | def real(self):
"""Real numbers are their real component."""
return +self | [
"def",
"real",
"(",
"self",
")",
":",
"return",
"+",
"self"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/numbers.py#L254-L256 | |
microsoft/clang | 86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5 | tools/scan-build-py/libscanbuild/compilation.py | python | split_command | (command) | return result if result.files else None | Returns a value when the command is a compilation, None otherwise.
The value on success is a named tuple with the following attributes:
files: list of source files
flags: list of compile options
compiler: string value of 'c' or 'c++' | Returns a value when the command is a compilation, None otherwise. | [
"Returns",
"a",
"value",
"when",
"the",
"command",
"is",
"a",
"compilation",
"None",
"otherwise",
"."
] | def split_command(command):
""" Returns a value when the command is a compilation, None otherwise.
The value on success is a named tuple with the following attributes:
files: list of source files
flags: list of compile options
compiler: string value of 'c' or 'c++' """
# the result of this method
result = collections.namedtuple('Compilation',
['compiler', 'flags', 'files'])
result.compiler = compiler_language(command)
result.flags = []
result.files = []
# quit right now, if the program was not a C/C++ compiler
if not result.compiler:
return None
# iterate on the compile options
args = iter(command[1:])
for arg in args:
# quit when compilation pass is not involved
if arg in {'-E', '-S', '-cc1', '-M', '-MM', '-###'}:
return None
# ignore some flags
elif arg in IGNORED_FLAGS:
count = IGNORED_FLAGS[arg]
for _ in range(count):
next(args)
elif re.match(r'^-(l|L|Wl,).+', arg):
pass
# some parameters could look like filename, take as compile option
elif arg in {'-D', '-I'}:
result.flags.extend([arg, next(args)])
# parameter which looks source file is taken...
elif re.match(r'^[^-].+', arg) and classify_source(arg):
result.files.append(arg)
# and consider everything else as compile option.
else:
result.flags.append(arg)
# do extra check on number of source files
return result if result.files else None | [
"def",
"split_command",
"(",
"command",
")",
":",
"# the result of this method",
"result",
"=",
"collections",
".",
"namedtuple",
"(",
"'Compilation'",
",",
"[",
"'compiler'",
",",
"'flags'",
",",
"'files'",
"]",
")",
"result",
".",
"compiler",
"=",
"compiler_la... | https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/tools/scan-build-py/libscanbuild/compilation.py#L60-L101 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py | python | ExamplePeakFunction.init | (self) | Declare parameters that participate in the fitting (declareParameter)
and attributes that are constants to be passed (declareAttribute) in
and do not participate in the fit. Attributes must have type=int,float,string,bool | Declare parameters that participate in the fitting (declareParameter)
and attributes that are constants to be passed (declareAttribute) in
and do not participate in the fit. Attributes must have type=int,float,string,bool | [
"Declare",
"parameters",
"that",
"participate",
"in",
"the",
"fitting",
"(",
"declareParameter",
")",
"and",
"attributes",
"that",
"are",
"constants",
"to",
"be",
"passed",
"(",
"declareAttribute",
")",
"in",
"and",
"do",
"not",
"participate",
"in",
"the",
"fi... | def init(self):
"""
Declare parameters that participate in the fitting (declareParameter)
and attributes that are constants to be passed (declareAttribute) in
and do not participate in the fit. Attributes must have type=int,float,string,bool
"""
# Active fitting parameters
self.declareParameter("Height")
self.declareParameter("PeakCentre")
self.declareParameter("Sigma")
# Simple attributes required for the function but
# not as part of the fit itself e.g. number of terms to evaluate in some expression
# They must have a default value.
# It is advisable to look at the setAttributeValue function below and take local copies
# of attributes so that they do not have to be retrieved repeatedly througout the fitting.
self.declareAttribute("NTerms", 1) | [
"def",
"init",
"(",
"self",
")",
":",
"# Active fitting parameters",
"self",
".",
"declareParameter",
"(",
"\"Height\"",
")",
"self",
".",
"declareParameter",
"(",
"\"PeakCentre\"",
")",
"self",
".",
"declareParameter",
"(",
"\"Sigma\"",
")",
"# Simple attributes re... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py#L35-L51 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.GetSortedXcodeEnv | (self, additional_settings=None) | return gyp.xcode_emulation.GetSortedXcodeEnv(
self.xcode_settings, abs_build_dir,
os.path.join(abs_build_dir, self.build_to_base), self.config_name,
additional_settings) | Returns the variables Xcode would set for build steps. | Returns the variables Xcode would set for build steps. | [
"Returns",
"the",
"variables",
"Xcode",
"would",
"set",
"for",
"build",
"steps",
"."
] | def GetSortedXcodeEnv(self, additional_settings=None):
"""Returns the variables Xcode would set for build steps."""
assert self.abs_build_dir
abs_build_dir = self.abs_build_dir
return gyp.xcode_emulation.GetSortedXcodeEnv(
self.xcode_settings, abs_build_dir,
os.path.join(abs_build_dir, self.build_to_base), self.config_name,
additional_settings) | [
"def",
"GetSortedXcodeEnv",
"(",
"self",
",",
"additional_settings",
"=",
"None",
")",
":",
"assert",
"self",
".",
"abs_build_dir",
"abs_build_dir",
"=",
"self",
".",
"abs_build_dir",
"return",
"gyp",
".",
"xcode_emulation",
".",
"GetSortedXcodeEnv",
"(",
"self",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/ninja.py#L1409-L1416 | |
quantOS-org/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | mdlink/deps/windows/protobuf-2.5.0/python/mox.py | python | UnknownMethodCallError.__init__ | (self, unknown_method_name) | Init exception.
Args:
# unknown_method_name: Method call that is not part of the mocked class's
# public interface.
unknown_method_name: str | Init exception. | [
"Init",
"exception",
"."
] | def __init__(self, unknown_method_name):
"""Init exception.
Args:
# unknown_method_name: Method call that is not part of the mocked class's
# public interface.
unknown_method_name: str
"""
Error.__init__(self)
self._unknown_method_name = unknown_method_name | [
"def",
"__init__",
"(",
"self",
",",
"unknown_method_name",
")",
":",
"Error",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"_unknown_method_name",
"=",
"unknown_method_name"
] | https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/mox.py#L133-L143 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/remote_operations.py | python | posix_path | (path) | return "{quote}{path}{quote}".format(quote=path_quote, path=new_path) | Returns posix path, used on Windows since scp requires posix style paths. | Returns posix path, used on Windows since scp requires posix style paths. | [
"Returns",
"posix",
"path",
"used",
"on",
"Windows",
"since",
"scp",
"requires",
"posix",
"style",
"paths",
"."
] | def posix_path(path):
""" Returns posix path, used on Windows since scp requires posix style paths. """
# If path is already quoted, we need to remove the quotes before calling
path_quote = "\'" if path.startswith("\'") else ""
path_quote = "\"" if path.startswith("\"") else path_quote
if path_quote:
path = path[1:-1]
drive, new_path = os.path.splitdrive(path)
if drive:
new_path = posixpath.join(
"/cygdrive",
drive.split(":")[0],
*re.split("/|\\\\", new_path))
return "{quote}{path}{quote}".format(quote=path_quote, path=new_path) | [
"def",
"posix_path",
"(",
"path",
")",
":",
"# If path is already quoted, we need to remove the quotes before calling",
"path_quote",
"=",
"\"\\'\"",
"if",
"path",
".",
"startswith",
"(",
"\"\\'\"",
")",
"else",
"\"\"",
"path_quote",
"=",
"\"\\\"\"",
"if",
"path",
"."... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/remote_operations.py#L41-L54 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.SetCaretStyle | (*args, **kwargs) | return _stc.StyledTextCtrl_SetCaretStyle(*args, **kwargs) | SetCaretStyle(self, int caretStyle)
Set the style of the caret to be drawn. | SetCaretStyle(self, int caretStyle) | [
"SetCaretStyle",
"(",
"self",
"int",
"caretStyle",
")"
] | def SetCaretStyle(*args, **kwargs):
"""
SetCaretStyle(self, int caretStyle)
Set the style of the caret to be drawn.
"""
return _stc.StyledTextCtrl_SetCaretStyle(*args, **kwargs) | [
"def",
"SetCaretStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetCaretStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L5631-L5637 | |
chuckcho/video-caffe | fc232b3e3a90ea22dd041b9fc5c542f170581f20 | python/caffe/io.py | python | Transformer.preprocess | (self, in_, data) | return caffe_in | Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray, or
(H' x W' x K x L) ndarray in case of C3D
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net, or
(K x H x W x L) in case of C3D | Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature | [
"Format",
"input",
"for",
"Caffe",
":",
"-",
"convert",
"to",
"single",
"-",
"resize",
"to",
"input",
"dimensions",
"(",
"preserving",
"number",
"of",
"channels",
")",
"-",
"transpose",
"dimensions",
"to",
"K",
"x",
"H",
"x",
"W",
"-",
"reorder",
"channe... | def preprocess(self, in_, data):
"""
Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray, or
(H' x W' x K x L) ndarray in case of C3D
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net, or
(K x H x W x L) in case of C3D
"""
self.__check_input(in_)
caffe_in = data.astype(np.float32, copy=False)
transpose = self.transpose.get(in_)
channel_swap = self.channel_swap.get(in_)
raw_scale = self.raw_scale.get(in_)
mean = self.mean.get(in_)
input_scale = self.input_scale.get(in_)
in_dims = self.inputs[in_][-2:]
if caffe_in.shape[:2] != in_dims:
caffe_in = resize_image(caffe_in, in_dims)
if transpose is not None:
caffe_in = caffe_in.transpose(transpose)
if channel_swap is not None:
caffe_in = caffe_in[channel_swap, :, :]
if raw_scale is not None:
caffe_in *= raw_scale
if mean is not None:
caffe_in -= mean
if input_scale is not None:
caffe_in *= input_scale
return caffe_in | [
"def",
"preprocess",
"(",
"self",
",",
"in_",
",",
"data",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"caffe_in",
"=",
"data",
".",
"astype",
"(",
"np",
".",
"float32",
",",
"copy",
"=",
"False",
")",
"transpose",
"=",
"self",
".",
"t... | https://github.com/chuckcho/video-caffe/blob/fc232b3e3a90ea22dd041b9fc5c542f170581f20/python/caffe/io.py#L122-L164 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/control_flow_ops.py | python | GradLoopState.outer_grad_state | (self) | return self._outer_grad_state | The grad loop state for outer loop. | The grad loop state for outer loop. | [
"The",
"grad",
"loop",
"state",
"for",
"outer",
"loop",
"."
] | def outer_grad_state(self):
"""The grad loop state for outer loop."""
return self._outer_grad_state | [
"def",
"outer_grad_state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_outer_grad_state"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/control_flow_ops.py#L743-L745 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tpu.py | python | _postprocess_non_flat_outputs | (outputs) | return flat_outputs, [] | Validates non-flat outputs, add backs device assignments and other attrs.
Args:
outputs: Output from `computation` inside `tpu.rewrite`.
Returns:
Tensors extracted from outputs and an empty list because Operations are not
allowed in non-flat outputs.. | Validates non-flat outputs, add backs device assignments and other attrs. | [
"Validates",
"non",
"-",
"flat",
"outputs",
"add",
"backs",
"device",
"assignments",
"and",
"other",
"attrs",
"."
] | def _postprocess_non_flat_outputs(outputs):
"""Validates non-flat outputs, add backs device assignments and other attrs.
Args:
outputs: Output from `computation` inside `tpu.rewrite`.
Returns:
Tensors extracted from outputs and an empty list because Operations are not
allowed in non-flat outputs..
"""
# Flatten output items.
flat_outputs = nest.flatten(outputs)
# Convert all non-Operation outputs to Tensors.
for i, o in enumerate(flat_outputs):
if isinstance(o, ops.Operation):
raise ValueError(
"tpu.rewrite does not support Operation as return value in non-flat "
"output structure. You can set returned Operations as control "
"dependencies of returned Tensors so Operations are triggered when "
'Tensors are evaluated. Operation found: "%s"' % o.name)
try:
o = ops.convert_to_tensor(o)
except Exception as e:
raise ValueError(
"TPU function return values must all either be Operations or "
'convertible to Tensors. Got error: "%s"' % str(e))
# Wraps outputs in Identity ops. Otherwise a replicated input copied
# straight to an output would bypass the replicate(). This would be bad
# because the TPUReplicatedInput/TPUReplicatedOutput operator would not
# be rewritten away, leading to a runtime error.
# TODO(phawkins): extend the rewrite to elide these nodes instead.
with ops.device(core(0)):
o = array_ops.identity(o)
# pylint: disable=protected-access
o.op._set_attr("_tpu_output_identity", attr_value_pb2.AttrValue(b=True))
# pylint: enable=protected-access
flat_outputs[i] = array_ops.identity(o)
# All flat_outputs are Tensors, and no Operations.
return flat_outputs, [] | [
"def",
"_postprocess_non_flat_outputs",
"(",
"outputs",
")",
":",
"# Flatten output items.",
"flat_outputs",
"=",
"nest",
".",
"flatten",
"(",
"outputs",
")",
"# Convert all non-Operation outputs to Tensors.",
"for",
"i",
",",
"o",
"in",
"enumerate",
"(",
"flat_outputs"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tpu.py#L1130-L1173 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/pydoc.py | python | isdata | (object) | return not (inspect.ismodule(object) or inspect.isclass(object) or
inspect.isroutine(object) or inspect.isframe(object) or
inspect.istraceback(object) or inspect.iscode(object)) | Check if an object is of a type that probably means it's data. | Check if an object is of a type that probably means it's data. | [
"Check",
"if",
"an",
"object",
"is",
"of",
"a",
"type",
"that",
"probably",
"means",
"it",
"s",
"data",
"."
] | def isdata(object):
"""Check if an object is of a type that probably means it's data."""
return not (inspect.ismodule(object) or inspect.isclass(object) or
inspect.isroutine(object) or inspect.isframe(object) or
inspect.istraceback(object) or inspect.iscode(object)) | [
"def",
"isdata",
"(",
"object",
")",
":",
"return",
"not",
"(",
"inspect",
".",
"ismodule",
"(",
"object",
")",
"or",
"inspect",
".",
"isclass",
"(",
"object",
")",
"or",
"inspect",
".",
"isroutine",
"(",
"object",
")",
"or",
"inspect",
".",
"isframe",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pydoc.py#L114-L118 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | lldb/examples/python/gdbremote.py | python | TerminalColors.underline | (self, on=True) | return '' | Enable or disable underline depending on the "on" parameter. | Enable or disable underline depending on the "on" parameter. | [
"Enable",
"or",
"disable",
"underline",
"depending",
"on",
"the",
"on",
"parameter",
"."
] | def underline(self, on=True):
'''Enable or disable underline depending on the "on" parameter.'''
if self.enabled:
if on:
return "\x1b[4m"
else:
return "\x1b[24m"
return '' | [
"def",
"underline",
"(",
"self",
",",
"on",
"=",
"True",
")",
":",
"if",
"self",
".",
"enabled",
":",
"if",
"on",
":",
"return",
"\"\\x1b[4m\"",
"else",
":",
"return",
"\"\\x1b[24m\"",
"return",
"''"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/examples/python/gdbremote.py#L74-L81 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/model_fitting/model_fitting_data_selector_view.py | python | ModelFittingDataSelectorView.set_slot_for_selected_y_changed | (self, slot) | Connect the slot for when the selected Y changes. | Connect the slot for when the selected Y changes. | [
"Connect",
"the",
"slot",
"for",
"when",
"the",
"selected",
"Y",
"changes",
"."
] | def set_slot_for_selected_y_changed(self, slot) -> None:
"""Connect the slot for when the selected Y changes."""
self.y_selector.currentIndexChanged.connect(slot) | [
"def",
"set_slot_for_selected_y_changed",
"(",
"self",
",",
"slot",
")",
"->",
"None",
":",
"self",
".",
"y_selector",
".",
"currentIndexChanged",
".",
"connect",
"(",
"slot",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/model_fitting/model_fitting_data_selector_view.py#L39-L41 | ||
SerenityOS/serenity | 1aad64fbe4d96ce3d3a7bc57ea5d59ac98f58bcf | Meta/lint-ports.py | python | check_available_ports | (from_table, ports) | return all_good | Check AvailablePorts.md for correct properties.
Args:
from_table (dict): Ports table from AvailablePorts.md
ports (dict): Dictionary with port properties from package.sh
Returns:
bool: no errors encountered | Check AvailablePorts.md for correct properties. | [
"Check",
"AvailablePorts",
".",
"md",
"for",
"correct",
"properties",
"."
] | def check_available_ports(from_table, ports):
"""Check AvailablePorts.md for correct properties.
Args:
from_table (dict): Ports table from AvailablePorts.md
ports (dict): Dictionary with port properties from package.sh
Returns:
bool: no errors encountered
"""
all_good = True
previous_line_len = None
for port in from_table.keys():
if previous_line_len is None:
previous_line_len = from_table[port]["line_len"]
if previous_line_len != from_table[port]["line_len"]:
print(f"Table row for port {port} is improperly aligned with other rows.")
all_good = False
else:
previous_line_len = from_table[port]["line_len"]
actual_ref = from_table[port]["dir_ref"]
expected_ref = f"{port}/"
if actual_ref != expected_ref:
print((
f'Directory link target in AvailablePorts.md for port {port} is '
f'incorrect, expected "{expected_ref}", found "{actual_ref}"'
))
all_good = False
actual_version = from_table[port]["version"]
expected_version = ports[port]["version"]
if GIT_HASH_REGEX.match(expected_version):
expected_version = expected_version[0:7]
if expected_version == "git":
expected_version = ""
if actual_version != expected_version:
print((
f'Version in AvailablePorts.md for port {port} is incorrect, '
f'expected "{expected_version}", found "{actual_version}"'
))
all_good = False
return all_good | [
"def",
"check_available_ports",
"(",
"from_table",
",",
"ports",
")",
":",
"all_good",
"=",
"True",
"previous_line_len",
"=",
"None",
"for",
"port",
"in",
"from_table",
".",
"keys",
"(",
")",
":",
"if",
"previous_line_len",
"is",
"None",
":",
"previous_line_le... | https://github.com/SerenityOS/serenity/blob/1aad64fbe4d96ce3d3a7bc57ea5d59ac98f58bcf/Meta/lint-ports.py#L401-L447 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBLaunchInfo.GetDetachOnError | (self) | return _lldb.SBLaunchInfo_GetDetachOnError(self) | GetDetachOnError(SBLaunchInfo self) -> bool | GetDetachOnError(SBLaunchInfo self) -> bool | [
"GetDetachOnError",
"(",
"SBLaunchInfo",
"self",
")",
"-",
">",
"bool"
] | def GetDetachOnError(self):
"""GetDetachOnError(SBLaunchInfo self) -> bool"""
return _lldb.SBLaunchInfo_GetDetachOnError(self) | [
"def",
"GetDetachOnError",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBLaunchInfo_GetDetachOnError",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L6631-L6633 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/isis_reduction_steps.py | python | DarkRunSubtraction._subtract_dark_run | (self, workspace, dark_run, setting) | return dark_run_correction.execute(scatter_workspace = workspace,
dark_run = dark_run) | Subtract the dark run from the SANS workspace
@param worksapce: the SANS data set
@param dark_run: the dark run workspace
@param setting: a dark run settings tuple | Subtract the dark run from the SANS workspace | [
"Subtract",
"the",
"dark",
"run",
"from",
"the",
"SANS",
"workspace"
] | def _subtract_dark_run(self, workspace, dark_run, setting):
'''
Subtract the dark run from the SANS workspace
@param worksapce: the SANS data set
@param dark_run: the dark run workspace
@param setting: a dark run settings tuple
'''
dark_run_correction = DarkCorr.DarkRunCorrection()
dark_run_correction.set_use_mean(setting.mean)
dark_run_correction.set_use_time(setting.time)
dark_run_correction.set_use_detectors(setting.detector)
dark_run_correction.set_use_monitors(setting.mon)
dark_run_correction.set_mon_numbers(setting.mon_numbers)
return dark_run_correction.execute(scatter_workspace = workspace,
dark_run = dark_run) | [
"def",
"_subtract_dark_run",
"(",
"self",
",",
"workspace",
",",
"dark_run",
",",
"setting",
")",
":",
"dark_run_correction",
"=",
"DarkCorr",
".",
"DarkRunCorrection",
"(",
")",
"dark_run_correction",
".",
"set_use_mean",
"(",
"setting",
".",
"mean",
")",
"dark... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/isis_reduction_steps.py#L1634-L1648 | |
amd/OpenCL-caffe | 638543108517265366c18ae5821f3096cf5cf34a | scripts/cpp_lint.py | python | _BlockInfo.CheckBegin | (self, filename, clean_lines, linenum, error) | Run checks that applies to text up to the opening brace.
This is mostly for checking the text after the class identifier
and the "{", usually where the base class is specified. For other
blocks, there isn't much to check, so we always pass.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Run checks that applies to text up to the opening brace. | [
"Run",
"checks",
"that",
"applies",
"to",
"text",
"up",
"to",
"the",
"opening",
"brace",
"."
] | def CheckBegin(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text up to the opening brace.
This is mostly for checking the text after the class identifier
and the "{", usually where the base class is specified. For other
blocks, there isn't much to check, so we always pass.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass | [
"def",
"CheckBegin",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"pass"
] | https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/scripts/cpp_lint.py#L1763-L1776 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/extras/msvs.py | python | msvs_generator.add_aliases | (self) | Add a specific target that emulates the "make all" necessary for Visual studio when pressing F7
We also add an alias for "make install" (disabled by default) | Add a specific target that emulates the "make all" necessary for Visual studio when pressing F7
We also add an alias for "make install" (disabled by default) | [
"Add",
"a",
"specific",
"target",
"that",
"emulates",
"the",
"make",
"all",
"necessary",
"for",
"Visual",
"studio",
"when",
"pressing",
"F7",
"We",
"also",
"add",
"an",
"alias",
"for",
"make",
"install",
"(",
"disabled",
"by",
"default",
")"
] | def add_aliases(self):
"""
Add a specific target that emulates the "make all" necessary for Visual studio when pressing F7
We also add an alias for "make install" (disabled by default)
"""
base = getattr(self, 'projects_dir', None) or self.tg.path
node_project = base.make_node('build_all_projects' + self.project_extension) # Node
p_build = self.vsnode_build_all(self, node_project)
p_build.collect_properties()
self.all_projects.append(p_build)
node_project = base.make_node('install_all_projects' + self.project_extension) # Node
p_install = self.vsnode_install_all(self, node_project)
p_install.collect_properties()
self.all_projects.append(p_install)
node_project = base.make_node('project_view' + self.project_extension) # Node
p_view = self.vsnode_project_view(self, node_project)
p_view.collect_source()
p_view.collect_properties()
self.all_projects.append(p_view)
n = self.vsnode_vsdir(self, make_uuid(self.srcnode.abspath() + 'build_aliases'), "build_aliases")
p_build.parent = p_install.parent = p_view.parent = n
self.all_projects.append(n) | [
"def",
"add_aliases",
"(",
"self",
")",
":",
"base",
"=",
"getattr",
"(",
"self",
",",
"'projects_dir'",
",",
"None",
")",
"or",
"self",
".",
"tg",
".",
"path",
"node_project",
"=",
"base",
".",
"make_node",
"(",
"'build_all_projects'",
"+",
"self",
".",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/msvs.py#L824-L849 | ||
LisaAnne/lisa-caffe-public | 49b8643ddef23a4f6120017968de30c45e693f59 | scripts/cpp_lint.py | python | CheckForFunctionLengths | (filename, clean_lines, linenum,
function_state, error) | Reports for long function bodies.
For an overview why this is done, see:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
Uses a simplistic algorithm assuming other style guidelines
(especially spacing) are followed.
Only checks unindented functions, so class members are unchecked.
Trivial bodies are unchecked, so constructors with huge initializer lists
may be missed.
Blank/comment lines are not counted so as to avoid encouraging the removal
of vertical space and comments just to get through a lint check.
NOLINT *on the last line of a function* disables this check.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
function_state: Current function name and lines in body so far.
error: The function to call with any errors found. | Reports for long function bodies. | [
"Reports",
"for",
"long",
"function",
"bodies",
"."
] | def CheckForFunctionLengths(filename, clean_lines, linenum,
function_state, error):
"""Reports for long function bodies.
For an overview why this is done, see:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
Uses a simplistic algorithm assuming other style guidelines
(especially spacing) are followed.
Only checks unindented functions, so class members are unchecked.
Trivial bodies are unchecked, so constructors with huge initializer lists
may be missed.
Blank/comment lines are not counted so as to avoid encouraging the removal
of vertical space and comments just to get through a lint check.
NOLINT *on the last line of a function* disables this check.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
function_state: Current function name and lines in body so far.
error: The function to call with any errors found.
"""
lines = clean_lines.lines
line = lines[linenum]
raw = clean_lines.raw_lines
raw_line = raw[linenum]
joined_line = ''
starting_func = False
regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
match_result = Match(regexp, line)
if match_result:
# If the name is all caps and underscores, figure it's a macro and
# ignore it, unless it's TEST or TEST_F.
function_name = match_result.group(1).split()[-1]
if function_name == 'TEST' or function_name == 'TEST_F' or (
not Match(r'[A-Z_]+$', function_name)):
starting_func = True
if starting_func:
body_found = False
for start_linenum in xrange(linenum, clean_lines.NumLines()):
start_line = lines[start_linenum]
joined_line += ' ' + start_line.lstrip()
if Search(r'(;|})', start_line): # Declarations and trivial functions
body_found = True
break # ... ignore
elif Search(r'{', start_line):
body_found = True
function = Search(r'((\w|:)*)\(', line).group(1)
if Match(r'TEST', function): # Handle TEST... macros
parameter_regexp = Search(r'(\(.*\))', joined_line)
if parameter_regexp: # Ignore bad syntax
function += parameter_regexp.group(1)
else:
function += '()'
function_state.Begin(function)
break
if not body_found:
# No body for the function (or evidence of a non-function) was found.
error(filename, linenum, 'readability/fn_size', 5,
'Lint failed to find start of function body.')
elif Match(r'^\}\s*$', line): # function end
function_state.Check(error, filename, linenum)
function_state.End()
elif not Match(r'^\s*$', line):
function_state.Count() | [
"def",
"CheckForFunctionLengths",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"function_state",
",",
"error",
")",
":",
"lines",
"=",
"clean_lines",
".",
"lines",
"line",
"=",
"lines",
"[",
"linenum",
"]",
"raw",
"=",
"clean_lines",
".",
"raw_l... | https://github.com/LisaAnne/lisa-caffe-public/blob/49b8643ddef23a4f6120017968de30c45e693f59/scripts/cpp_lint.py#L2384-L2451 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/memory_inspector/memory_inspector/core/backends.py | python | Device.id | (self) | Unique identifier (within the backend) of the device (e.g., S/N). | Unique identifier (within the backend) of the device (e.g., S/N). | [
"Unique",
"identifier",
"(",
"within",
"the",
"backend",
")",
"of",
"the",
"device",
"(",
"e",
".",
"g",
".",
"S",
"/",
"N",
")",
"."
] | def id(self):
"""Unique identifier (within the backend) of the device (e.g., S/N)."""
raise NotImplementedError() | [
"def",
"id",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/memory_inspector/memory_inspector/core/backends.py#L109-L111 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/internals/array_manager.py | python | ArrayManager.idelete | (self, indexer) | return self | Delete selected locations in-place (new block and array, same BlockManager) | Delete selected locations in-place (new block and array, same BlockManager) | [
"Delete",
"selected",
"locations",
"in",
"-",
"place",
"(",
"new",
"block",
"and",
"array",
"same",
"BlockManager",
")"
] | def idelete(self, indexer):
"""
Delete selected locations in-place (new block and array, same BlockManager)
"""
to_keep = np.ones(self.shape[0], dtype=np.bool_)
to_keep[indexer] = False
self.arrays = [self.arrays[i] for i in np.nonzero(to_keep)[0]]
self._axes = [self._axes[0], self._axes[1][to_keep]]
return self | [
"def",
"idelete",
"(",
"self",
",",
"indexer",
")",
":",
"to_keep",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"np",
".",
"bool_",
")",
"to_keep",
"[",
"indexer",
"]",
"=",
"False",
"self",
".",
"arrays",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/array_manager.py#L889-L898 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | TypeHandler.WriteStruct | (self, func, file) | Writes a structure that matches the arguments to a function. | Writes a structure that matches the arguments to a function. | [
"Writes",
"a",
"structure",
"that",
"matches",
"the",
"arguments",
"to",
"a",
"function",
"."
] | def WriteStruct(self, func, file):
"""Writes a structure that matches the arguments to a function."""
comment = func.GetInfo('cmd_comment')
if not comment == None:
file.Write(comment)
file.Write("struct %s {\n" % func.name)
file.Write(" typedef %s ValueType;\n" % func.name)
file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
func.WriteCmdArgFlag(file)
file.Write("\n")
result = func.GetInfo('result')
if not result == None:
if len(result) == 1:
file.Write(" typedef %s Result;\n\n" % result[0])
else:
file.Write(" struct Result {\n")
for line in result:
file.Write(" %s;\n" % line)
file.Write(" };\n\n")
func.WriteCmdComputeSize(file)
func.WriteCmdSetHeader(file)
func.WriteCmdInit(file)
func.WriteCmdSet(file)
file.Write(" gpu::CommandHeader header;\n")
args = func.GetCmdArgs()
for arg in args:
file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
file.Write("};\n")
file.Write("\n")
size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func.name, size))
file.Write(" Sizeof_%s_is_not_%d);\n" % (func.name, size))
file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func.name)
file.Write(" OffsetOf_%s_header_not_0);\n" % func.name)
offset = _SIZE_OF_COMMAND_HEADER
for arg in args:
file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
(func.name, arg.name, offset))
file.Write(" OffsetOf_%s_%s_not_%d);\n" %
(func.name, arg.name, offset))
offset += _SIZE_OF_UINT32
if not result == None and len(result) > 1:
offset = 0;
for line in result:
parts = line.split()
name = parts[-1]
check = """
COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
"""
file.Write((check.strip() + "\n") % {
'cmd_name': func.name,
'field_name': name,
'offset': offset,
})
offset += _SIZE_OF_UINT32
file.Write("\n") | [
"def",
"WriteStruct",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"comment",
"=",
"func",
".",
"GetInfo",
"(",
"'cmd_comment'",
")",
"if",
"not",
"comment",
"==",
"None",
":",
"file",
".",
"Write",
"(",
"comment",
")",
"file",
".",
"Write",
"(",... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L1879-L1938 | ||
tangzhenyu/Scene-Text-Understanding | 0f7ffc7aea5971a50cdc03d33d0a41075285948b | SynthText_Chinese/synth_utils.py | python | DepthCamera.plane2xyz | (center, ij, plane) | return xyz | converts image pixel indices to xyz on the PLANE.
center : 2-tuple
ij : nx2 int array
plane : 4-tuple
return nx3 array. | converts image pixel indices to xyz on the PLANE. | [
"converts",
"image",
"pixel",
"indices",
"to",
"xyz",
"on",
"the",
"PLANE",
"."
] | def plane2xyz(center, ij, plane):
"""
converts image pixel indices to xyz on the PLANE.
center : 2-tuple
ij : nx2 int array
plane : 4-tuple
return nx3 array.
"""
ij = np.atleast_2d(ij)
n = ij.shape[0]
ij = ij.astype('float')
xy_ray = (ij-center[None,:]) / DepthCamera.f
z = -plane[3]/(xy_ray.dot(plane[:2])+plane[2])
xyz = np.c_[xy_ray, np.ones(n)] * z[:,None]
return xyz | [
"def",
"plane2xyz",
"(",
"center",
",",
"ij",
",",
"plane",
")",
":",
"ij",
"=",
"np",
".",
"atleast_2d",
"(",
"ij",
")",
"n",
"=",
"ij",
".",
"shape",
"[",
"0",
"]",
"ij",
"=",
"ij",
".",
"astype",
"(",
"'float'",
")",
"xy_ray",
"=",
"(",
"i... | https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/SynthText_Chinese/synth_utils.py#L171-L187 | |
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | cpplint.py | python | _SetCountingStyle | (level) | Sets the module's counting options. | Sets the module's counting options. | [
"Sets",
"the",
"module",
"s",
"counting",
"options",
"."
] | def _SetCountingStyle(level):
"""Sets the module's counting options."""
_cpplint_state.SetCountingStyle(level) | [
"def",
"_SetCountingStyle",
"(",
"level",
")",
":",
"_cpplint_state",
".",
"SetCountingStyle",
"(",
"level",
")"
] | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/cpplint.py#L542-L544 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/multiprocessing/process.py | python | current_process | () | return _current_process | Return process object representing the current process | Return process object representing the current process | [
"Return",
"process",
"object",
"representing",
"the",
"current",
"process"
] | def current_process():
'''
Return process object representing the current process
'''
return _current_process | [
"def",
"current_process",
"(",
")",
":",
"return",
"_current_process"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/multiprocessing/process.py#L59-L63 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/sparse/compressed.py | python | _cs_matrix._zero_many | (self, i, j) | Sets value at each (i, j) to zero, preserving sparsity structure.
Here (i,j) index major and minor respectively. | Sets value at each (i, j) to zero, preserving sparsity structure. | [
"Sets",
"value",
"at",
"each",
"(",
"i",
"j",
")",
"to",
"zero",
"preserving",
"sparsity",
"structure",
"."
] | def _zero_many(self, i, j):
"""Sets value at each (i, j) to zero, preserving sparsity structure.
Here (i,j) index major and minor respectively.
"""
i, j, M, N = self._prepare_indices(i, j)
n_samples = len(i)
offsets = np.empty(n_samples, dtype=self.indices.dtype)
ret = _sparsetools.csr_sample_offsets(M, N, self.indptr, self.indices,
n_samples, i, j, offsets)
if ret == 1:
# rinse and repeat
self.sum_duplicates()
_sparsetools.csr_sample_offsets(M, N, self.indptr,
self.indices, n_samples, i, j,
offsets)
# only assign zeros to the existing sparsity structure
self.data[offsets[offsets > -1]] = 0 | [
"def",
"_zero_many",
"(",
"self",
",",
"i",
",",
"j",
")",
":",
"i",
",",
"j",
",",
"M",
",",
"N",
"=",
"self",
".",
"_prepare_indices",
"(",
"i",
",",
"j",
")",
"n_samples",
"=",
"len",
"(",
"i",
")",
"offsets",
"=",
"np",
".",
"empty",
"(",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/compressed.py#L770-L789 | ||
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/optimal_learning/python/cpp_wrappers/covariance.py | python | SquareExponential.set_hyperparameters | (self, hyperparameters) | Set hyperparameters to the specified hyperparameters; ordering must match. | Set hyperparameters to the specified hyperparameters; ordering must match. | [
"Set",
"hyperparameters",
"to",
"the",
"specified",
"hyperparameters",
";",
"ordering",
"must",
"match",
"."
] | def set_hyperparameters(self, hyperparameters):
"""Set hyperparameters to the specified hyperparameters; ordering must match."""
self._hyperparameters = numpy.copy(hyperparameters) | [
"def",
"set_hyperparameters",
"(",
"self",
",",
"hyperparameters",
")",
":",
"self",
".",
"_hyperparameters",
"=",
"numpy",
".",
"copy",
"(",
"hyperparameters",
")"
] | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/cpp_wrappers/covariance.py#L55-L57 | ||
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/build/targets.py | python | BasicTarget.sources | (self) | return self.source_targets_ | Returns the list of AbstractTargets which are used as sources.
The extra properties specified for sources are not represented.
The only used of this rule at the moment is the '--dump-tests'
feature of the test system. | Returns the list of AbstractTargets which are used as sources.
The extra properties specified for sources are not represented.
The only used of this rule at the moment is the '--dump-tests'
feature of the test system. | [
"Returns",
"the",
"list",
"of",
"AbstractTargets",
"which",
"are",
"used",
"as",
"sources",
".",
"The",
"extra",
"properties",
"specified",
"for",
"sources",
"are",
"not",
"represented",
".",
"The",
"only",
"used",
"of",
"this",
"rule",
"at",
"the",
"moment"... | def sources (self):
""" Returns the list of AbstractTargets which are used as sources.
The extra properties specified for sources are not represented.
The only used of this rule at the moment is the '--dump-tests'
feature of the test system.
"""
if self.source_targets_ == None:
self.source_targets_ = []
for s in self.sources_:
self.source_targets_.append(resolve_reference(s, self.project_)[0])
return self.source_targets_ | [
"def",
"sources",
"(",
"self",
")",
":",
"if",
"self",
".",
"source_targets_",
"==",
"None",
":",
"self",
".",
"source_targets_",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"sources_",
":",
"self",
".",
"source_targets_",
".",
"append",
"(",
"resolv... | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/targets.py#L925-L936 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/cef_source/tools/automate/automate-git.py | python | get_git_hash | (path, branch) | return 'Unknown' | Returns the git hash for the specified branch/tag/hash. | Returns the git hash for the specified branch/tag/hash. | [
"Returns",
"the",
"git",
"hash",
"for",
"the",
"specified",
"branch",
"/",
"tag",
"/",
"hash",
"."
] | def get_git_hash(path, branch):
""" Returns the git hash for the specified branch/tag/hash. """
cmd = "%s rev-parse %s" % (git_exe, branch)
result = exec_cmd(cmd, path)
if result['out'] != '':
return result['out'].strip()
return 'Unknown' | [
"def",
"get_git_hash",
"(",
"path",
",",
"branch",
")",
":",
"cmd",
"=",
"\"%s rev-parse %s\"",
"%",
"(",
"git_exe",
",",
"branch",
")",
"result",
"=",
"exec_cmd",
"(",
"cmd",
",",
"path",
")",
"if",
"result",
"[",
"'out'",
"]",
"!=",
"''",
":",
"ret... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/automate/automate-git.py#L119-L125 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/closure_compiler/compile.py | python | Checker._log_error | (self, msg) | Logs |msg| to stderr regardless of --flags.
Args:
msg: An error message to log. | Logs |msg| to stderr regardless of --flags. | [
"Logs",
"|msg|",
"to",
"stderr",
"regardless",
"of",
"--",
"flags",
"."
] | def _log_error(self, msg):
"""Logs |msg| to stderr regardless of --flags.
Args:
msg: An error message to log.
"""
print >> sys.stderr, "(ERROR) %s" % msg | [
"def",
"_log_error",
"(",
"self",
",",
"msg",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"(ERROR) %s\"",
"%",
"msg"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/closure_compiler/compile.py#L69-L75 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.CallTipCancel | (*args, **kwargs) | return _stc.StyledTextCtrl_CallTipCancel(*args, **kwargs) | CallTipCancel(self)
Remove the call tip from the screen. | CallTipCancel(self) | [
"CallTipCancel",
"(",
"self",
")"
] | def CallTipCancel(*args, **kwargs):
"""
CallTipCancel(self)
Remove the call tip from the screen.
"""
return _stc.StyledTextCtrl_CallTipCancel(*args, **kwargs) | [
"def",
"CallTipCancel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_CallTipCancel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3804-L3810 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/mixed_precision/autocast_variable.py | python | AutoCastVariable.dtype | (self) | return self._variable.dtype | The dtype of the underlying variable, before any casts are done. | The dtype of the underlying variable, before any casts are done. | [
"The",
"dtype",
"of",
"the",
"underlying",
"variable",
"before",
"any",
"casts",
"are",
"done",
"."
] | def dtype(self):
"""The dtype of the underlying variable, before any casts are done."""
return self._variable.dtype | [
"def",
"dtype",
"(",
"self",
")",
":",
"return",
"self",
".",
"_variable",
".",
"dtype"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/mixed_precision/autocast_variable.py#L96-L98 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/otci/otci/connectors.py | python | OtCliHandler.readline | (self) | Method readline should return the next line read from OT CLI. | Method readline should return the next line read from OT CLI. | [
"Method",
"readline",
"should",
"return",
"the",
"next",
"line",
"read",
"from",
"OT",
"CLI",
"."
] | def readline(self) -> str:
"""Method readline should return the next line read from OT CLI."""
pass | [
"def",
"readline",
"(",
"self",
")",
"->",
"str",
":",
"pass"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/connectors.py#L40-L42 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/learn/python/learn/utils/export.py | python | _get_saver | () | return saver | Lazy init and return saver. | Lazy init and return saver. | [
"Lazy",
"init",
"and",
"return",
"saver",
"."
] | def _get_saver():
"""Lazy init and return saver."""
saver = _get_first_op_from_collection(ops.GraphKeys.SAVERS)
if saver is not None:
if saver:
saver = saver[0]
else:
saver = None
if saver is None and variables.all_variables():
saver = tf_saver.Saver()
ops.add_to_collection(ops.GraphKeys.SAVERS, saver)
return saver | [
"def",
"_get_saver",
"(",
")",
":",
"saver",
"=",
"_get_first_op_from_collection",
"(",
"ops",
".",
"GraphKeys",
".",
"SAVERS",
")",
"if",
"saver",
"is",
"not",
"None",
":",
"if",
"saver",
":",
"saver",
"=",
"saver",
"[",
"0",
"]",
"else",
":",
"saver"... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/utils/export.py#L45-L56 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/slim/python/slim/nets/inception_v3.py | python | inception_v3 | (inputs,
num_classes=1000,
is_training=True,
dropout_keep_prob=0.8,
min_depth=16,
depth_multiplier=1.0,
prediction_fn=layers_lib.softmax,
spatial_squeeze=True,
reuse=None,
scope='InceptionV3') | return logits, end_points | Inception model from http://arxiv.org/abs/1512.00567.
"Rethinking the Inception Architecture for Computer Vision"
Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens,
Zbigniew Wojna.
With the default arguments this method constructs the exact model defined in
the paper. However, one can experiment with variations of the inception_v3
network by changing arguments dropout_keep_prob, min_depth and
depth_multiplier.
The default image size used to train this network is 299x299.
Args:
inputs: a tensor of size [batch_size, height, width, channels].
num_classes: number of predicted classes.
is_training: whether is training or not.
dropout_keep_prob: the percentage of activation values that are retained.
min_depth: Minimum depth value (number of channels) for all convolution ops.
Enforced when depth_multiplier < 1, and not an active constraint when
depth_multiplier >= 1.
depth_multiplier: Float multiplier for the depth (number of channels)
for all convolution ops. The value must be greater than zero. Typical
usage will be to set this value in (0, 1) to reduce the number of
parameters or computation cost of the model.
prediction_fn: a function to get predictions out of logits.
spatial_squeeze: if True, logits is of shape is [B, C], if false logits is
of shape [B, 1, 1, C], where B is batch_size and C is number of classes.
reuse: whether or not the network and its variables should be reused. To be
able to reuse 'scope' must be given.
scope: Optional variable_scope.
Returns:
logits: the pre-softmax activations, a tensor of size
[batch_size, num_classes]
end_points: a dictionary from components of the network to the corresponding
activation.
Raises:
ValueError: if 'depth_multiplier' is less than or equal to zero. | Inception model from http://arxiv.org/abs/1512.00567. | [
"Inception",
"model",
"from",
"http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1512",
".",
"00567",
"."
] | def inception_v3(inputs,
num_classes=1000,
is_training=True,
dropout_keep_prob=0.8,
min_depth=16,
depth_multiplier=1.0,
prediction_fn=layers_lib.softmax,
spatial_squeeze=True,
reuse=None,
scope='InceptionV3'):
"""Inception model from http://arxiv.org/abs/1512.00567.
"Rethinking the Inception Architecture for Computer Vision"
Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens,
Zbigniew Wojna.
With the default arguments this method constructs the exact model defined in
the paper. However, one can experiment with variations of the inception_v3
network by changing arguments dropout_keep_prob, min_depth and
depth_multiplier.
The default image size used to train this network is 299x299.
Args:
inputs: a tensor of size [batch_size, height, width, channels].
num_classes: number of predicted classes.
is_training: whether is training or not.
dropout_keep_prob: the percentage of activation values that are retained.
min_depth: Minimum depth value (number of channels) for all convolution ops.
Enforced when depth_multiplier < 1, and not an active constraint when
depth_multiplier >= 1.
depth_multiplier: Float multiplier for the depth (number of channels)
for all convolution ops. The value must be greater than zero. Typical
usage will be to set this value in (0, 1) to reduce the number of
parameters or computation cost of the model.
prediction_fn: a function to get predictions out of logits.
spatial_squeeze: if True, logits is of shape is [B, C], if false logits is
of shape [B, 1, 1, C], where B is batch_size and C is number of classes.
reuse: whether or not the network and its variables should be reused. To be
able to reuse 'scope' must be given.
scope: Optional variable_scope.
Returns:
logits: the pre-softmax activations, a tensor of size
[batch_size, num_classes]
end_points: a dictionary from components of the network to the corresponding
activation.
Raises:
ValueError: if 'depth_multiplier' is less than or equal to zero.
"""
if depth_multiplier <= 0:
raise ValueError('depth_multiplier is not greater than zero.')
depth = lambda d: max(int(d * depth_multiplier), min_depth)
with variable_scope.variable_scope(
scope, 'InceptionV3', [inputs, num_classes], reuse=reuse) as scope:
with arg_scope(
[layers_lib.batch_norm, layers_lib.dropout], is_training=is_training):
net, end_points = inception_v3_base(
inputs,
scope=scope,
min_depth=min_depth,
depth_multiplier=depth_multiplier)
# Auxiliary Head logits
with arg_scope(
[layers.conv2d, layers_lib.max_pool2d, layers_lib.avg_pool2d],
stride=1,
padding='SAME'):
aux_logits = end_points['Mixed_6e']
with variable_scope.variable_scope('AuxLogits'):
aux_logits = layers_lib.avg_pool2d(
aux_logits, [5, 5],
stride=3,
padding='VALID',
scope='AvgPool_1a_5x5')
aux_logits = layers.conv2d(
aux_logits, depth(128), [1, 1], scope='Conv2d_1b_1x1')
# Shape of feature map before the final layer.
kernel_size = _reduced_kernel_size_for_small_input(aux_logits, [5, 5])
aux_logits = layers.conv2d(
aux_logits,
depth(768),
kernel_size,
weights_initializer=trunc_normal(0.01),
padding='VALID',
scope='Conv2d_2a_{}x{}'.format(*kernel_size))
aux_logits = layers.conv2d(
aux_logits,
num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
weights_initializer=trunc_normal(0.001),
scope='Conv2d_2b_1x1')
if spatial_squeeze:
aux_logits = array_ops.squeeze(
aux_logits, [1, 2], name='SpatialSqueeze')
end_points['AuxLogits'] = aux_logits
# Final pooling and prediction
with variable_scope.variable_scope('Logits'):
kernel_size = _reduced_kernel_size_for_small_input(net, [8, 8])
net = layers_lib.avg_pool2d(
net,
kernel_size,
padding='VALID',
scope='AvgPool_1a_{}x{}'.format(*kernel_size))
# 1 x 1 x 2048
net = layers_lib.dropout(
net, keep_prob=dropout_keep_prob, scope='Dropout_1b')
end_points['PreLogits'] = net
# 2048
logits = layers.conv2d(
net,
num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
scope='Conv2d_1c_1x1')
if spatial_squeeze:
logits = array_ops.squeeze(logits, [1, 2], name='SpatialSqueeze')
# 1000
end_points['Logits'] = logits
end_points['Predictions'] = prediction_fn(logits, scope='Predictions')
return logits, end_points | [
"def",
"inception_v3",
"(",
"inputs",
",",
"num_classes",
"=",
"1000",
",",
"is_training",
"=",
"True",
",",
"dropout_keep_prob",
"=",
"0.8",
",",
"min_depth",
"=",
"16",
",",
"depth_multiplier",
"=",
"1.0",
",",
"prediction_fn",
"=",
"layers_lib",
".",
"sof... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/slim/python/slim/nets/inception_v3.py#L512-L638 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/compat/chainmap_impl.py | python | ChainMap.clear | (self) | Clear maps[0], leaving maps[1:] intact. | Clear maps[0], leaving maps[1:] intact. | [
"Clear",
"maps",
"[",
"0",
"]",
"leaving",
"maps",
"[",
"1",
":",
"]",
"intact",
"."
] | def clear(self):
'Clear maps[0], leaving maps[1:] intact.'
self.maps[0].clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"maps",
"[",
"0",
"]",
".",
"clear",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/compat/chainmap_impl.py#L155-L157 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/gzip.py | python | GzipFile.fileno | (self) | return self.fileobj.fileno() | Invoke the underlying file object's fileno() method.
This will raise AttributeError if the underlying file object
doesn't support fileno(). | Invoke the underlying file object's fileno() method. | [
"Invoke",
"the",
"underlying",
"file",
"object",
"s",
"fileno",
"()",
"method",
"."
] | def fileno(self):
"""Invoke the underlying file object's fileno() method.
This will raise AttributeError if the underlying file object
doesn't support fileno().
"""
return self.fileobj.fileno() | [
"def",
"fileno",
"(",
"self",
")",
":",
"return",
"self",
".",
"fileobj",
".",
"fileno",
"(",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/gzip.py#L338-L344 | |
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | lib/roi_data_layer/minibatch.py | python | _sample_rois | (roidb, fg_rois_per_image, rois_per_image, num_classes) | return labels, overlaps, rois, bbox_targets, bbox_inside_weights | Generate a random sample of RoIs comprising foreground and background
examples. | Generate a random sample of RoIs comprising foreground and background
examples. | [
"Generate",
"a",
"random",
"sample",
"of",
"RoIs",
"comprising",
"foreground",
"and",
"background",
"examples",
"."
] | def _sample_rois(roidb, fg_rois_per_image, rois_per_image, num_classes):
"""Generate a random sample of RoIs comprising foreground and background
examples.
"""
# label = class RoI has max overlap with
labels = roidb['max_classes']
overlaps = roidb['max_overlaps']
rois = roidb['boxes']
# Select foreground RoIs as those with >= FG_THRESH overlap
fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0]
# Guard against the case when an image has fewer than fg_rois_per_image
# foreground RoIs
fg_rois_per_this_image = np.minimum(fg_rois_per_image, fg_inds.size)
# Sample foreground regions without replacement
if fg_inds.size > 0:
fg_inds = npr.choice(
fg_inds, size=fg_rois_per_this_image, replace=False)
# Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)
bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) &
(overlaps >= cfg.TRAIN.BG_THRESH_LO))[0]
# Compute number of background RoIs to take from this image (guarding
# against there being fewer than desired)
bg_rois_per_this_image = rois_per_image - fg_rois_per_this_image
bg_rois_per_this_image = np.minimum(bg_rois_per_this_image,
bg_inds.size)
# Sample foreground regions without replacement
if bg_inds.size > 0:
bg_inds = npr.choice(
bg_inds, size=bg_rois_per_this_image, replace=False)
# The indices that we're selecting (both fg and bg)
keep_inds = np.append(fg_inds, bg_inds)
# Select sampled values from various arrays:
labels = labels[keep_inds]
# Clamp labels for the background RoIs to 0
labels[fg_rois_per_this_image:] = 0
overlaps = overlaps[keep_inds]
rois = rois[keep_inds]
bbox_targets, bbox_inside_weights = _get_bbox_regression_labels(
roidb['bbox_targets'][keep_inds, :], num_classes)
return labels, overlaps, rois, bbox_targets, bbox_inside_weights | [
"def",
"_sample_rois",
"(",
"roidb",
",",
"fg_rois_per_image",
",",
"rois_per_image",
",",
"num_classes",
")",
":",
"# label = class RoI has max overlap with",
"labels",
"=",
"roidb",
"[",
"'max_classes'",
"]",
"overlaps",
"=",
"roidb",
"[",
"'max_overlaps'",
"]",
"... | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/roi_data_layer/minibatch.py#L85-L129 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | tools/diagnose.py | python | parse_args | () | return args | Parse arguments. | Parse arguments. | [
"Parse",
"arguments",
"."
] | def parse_args():
"""Parse arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Diagnose script for checking the current system.')
choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network']
for choice in choices:
parser.add_argument('--' + choice, default=1, type=int,
help='Diagnose {}.'.format(choice))
parser.add_argument('--region', default='', type=str,
help="Additional sites in which region(s) to test. \
Specify 'cn' for example to test mirror sites in China.")
parser.add_argument('--timeout', default=10, type=int,
help="Connection test timeout threshold, 0 to disable.")
args = parser.parse_args()
return args | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
",",
"description",
"=",
"'Diagnose script for checking the current system.'",
")",
"choices",
"=",
"[",
... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/tools/diagnose.py#L33-L48 | |
google/swiftshader | 8ccc63f045d5975fb67f9dfd3d2b8235b0526990 | third_party/SPIRV-Tools/utils/generate_grammar_tables.py | python | convert_operand_kind | (operand_tuple) | return 'SPV_OPERAND_TYPE_{}'.format(
re.sub(r'([a-z])([A-Z])', r'\1_\2', kind).upper()) | Returns the corresponding operand type used in spirv-tools for the given
operand kind and quantifier used in the JSON grammar.
Arguments:
- operand_tuple: a tuple of two elements:
- operand kind: used in the JSON grammar
- quantifier: '', '?', or '*'
Returns:
a string of the enumerant name in spv_operand_type_t | Returns the corresponding operand type used in spirv-tools for the given
operand kind and quantifier used in the JSON grammar. | [
"Returns",
"the",
"corresponding",
"operand",
"type",
"used",
"in",
"spirv",
"-",
"tools",
"for",
"the",
"given",
"operand",
"kind",
"and",
"quantifier",
"used",
"in",
"the",
"JSON",
"grammar",
"."
] | def convert_operand_kind(operand_tuple):
"""Returns the corresponding operand type used in spirv-tools for the given
operand kind and quantifier used in the JSON grammar.
Arguments:
- operand_tuple: a tuple of two elements:
- operand kind: used in the JSON grammar
- quantifier: '', '?', or '*'
Returns:
a string of the enumerant name in spv_operand_type_t
"""
kind, quantifier = operand_tuple
# The following cases are where we differ between the JSON grammar and
# spirv-tools.
if kind == 'IdResultType':
kind = 'TypeId'
elif kind == 'IdResult':
kind = 'ResultId'
elif kind == 'IdMemorySemantics' or kind == 'MemorySemantics':
kind = 'MemorySemanticsId'
elif kind == 'IdScope' or kind == 'Scope':
kind = 'ScopeId'
elif kind == 'IdRef':
kind = 'Id'
elif kind == 'ImageOperands':
kind = 'Image'
elif kind == 'Dim':
kind = 'Dimensionality'
elif kind == 'ImageFormat':
kind = 'SamplerImageFormat'
elif kind == 'KernelEnqueueFlags':
kind = 'KernelEnqFlags'
elif kind == 'LiteralExtInstInteger':
kind = 'ExtensionInstructionNumber'
elif kind == 'LiteralSpecConstantOpInteger':
kind = 'SpecConstantOpNumber'
elif kind == 'LiteralContextDependentNumber':
kind = 'TypedLiteralNumber'
elif kind == 'PairLiteralIntegerIdRef':
kind = 'LiteralIntegerId'
elif kind == 'PairIdRefLiteralInteger':
kind = 'IdLiteralInteger'
elif kind == 'PairIdRefIdRef': # Used by OpPhi in the grammar
kind = 'Id'
if kind == 'FPRoundingMode':
kind = 'FpRoundingMode'
elif kind == 'FPFastMathMode':
kind = 'FpFastMathMode'
if quantifier == '?':
kind = 'Optional{}'.format(kind)
elif quantifier == '*':
kind = 'Variable{}'.format(kind)
return 'SPV_OPERAND_TYPE_{}'.format(
re.sub(r'([a-z])([A-Z])', r'\1_\2', kind).upper()) | [
"def",
"convert_operand_kind",
"(",
"operand_tuple",
")",
":",
"kind",
",",
"quantifier",
"=",
"operand_tuple",
"# The following cases are where we differ between the JSON grammar and",
"# spirv-tools.",
"if",
"kind",
"==",
"'IdResultType'",
":",
"kind",
"=",
"'TypeId'",
"e... | https://github.com/google/swiftshader/blob/8ccc63f045d5975fb67f9dfd3d2b8235b0526990/third_party/SPIRV-Tools/utils/generate_grammar_tables.py#L149-L209 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Text.edit_modified | (self, arg=None) | return self.edit("modified", arg) | Get or Set the modified flag
If arg is not specified, returns the modified
flag of the widget. The insert, delete, edit undo and
edit redo commands or the user can set or clear the
modified flag. If boolean is specified, sets the
modified flag of the widget to arg. | Get or Set the modified flag | [
"Get",
"or",
"Set",
"the",
"modified",
"flag"
] | def edit_modified(self, arg=None):
"""Get or Set the modified flag
If arg is not specified, returns the modified
flag of the widget. The insert, delete, edit undo and
edit redo commands or the user can set or clear the
modified flag. If boolean is specified, sets the
modified flag of the widget to arg.
"""
return self.edit("modified", arg) | [
"def",
"edit_modified",
"(",
"self",
",",
"arg",
"=",
"None",
")",
":",
"return",
"self",
".",
"edit",
"(",
"\"modified\"",
",",
"arg",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L3043-L3052 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/beanstalk/__init__.py | python | regions | () | return get_regions(
'elasticbeanstalk',
connection_cls=boto.beanstalk.layer1.Layer1
) | Get all available regions for the AWS Elastic Beanstalk service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo` | Get all available regions for the AWS Elastic Beanstalk service. | [
"Get",
"all",
"available",
"regions",
"for",
"the",
"AWS",
"Elastic",
"Beanstalk",
"service",
"."
] | def regions():
"""
Get all available regions for the AWS Elastic Beanstalk service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
import boto.beanstalk.layer1
return get_regions(
'elasticbeanstalk',
connection_cls=boto.beanstalk.layer1.Layer1
) | [
"def",
"regions",
"(",
")",
":",
"import",
"boto",
".",
"beanstalk",
".",
"layer1",
"return",
"get_regions",
"(",
"'elasticbeanstalk'",
",",
"connection_cls",
"=",
"boto",
".",
"beanstalk",
".",
"layer1",
".",
"Layer1",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/beanstalk/__init__.py#L26-L37 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillContextMenu.py | python | DrillContextMenu.setPresenter | (self, presenter) | Set the context menu presenter.
Args:
presenter (DrillContextMenuPresenter): context menu presenter | Set the context menu presenter. | [
"Set",
"the",
"context",
"menu",
"presenter",
"."
] | def setPresenter(self, presenter):
"""
Set the context menu presenter.
Args:
presenter (DrillContextMenuPresenter): context menu presenter
"""
self._presenter = presenter | [
"def",
"setPresenter",
"(",
"self",
",",
"presenter",
")",
":",
"self",
".",
"_presenter",
"=",
"presenter"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillContextMenu.py#L67-L74 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextEvent.GetWParam | (*args, **kwargs) | return _stc.StyledTextEvent_GetWParam(*args, **kwargs) | GetWParam(self) -> int | GetWParam(self) -> int | [
"GetWParam",
"(",
"self",
")",
"-",
">",
"int"
] | def GetWParam(*args, **kwargs):
"""GetWParam(self) -> int"""
return _stc.StyledTextEvent_GetWParam(*args, **kwargs) | [
"def",
"GetWParam",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextEvent_GetWParam",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L7170-L7172 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/random.py | python | WichmannHill.seed | (self, a=None) | Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
If a is an int or long, a is used directly. Distinct values between
0 and 27814431486575L inclusive are guaranteed to yield distinct
internal states (this guarantee is specific to the default
Wichmann-Hill generator). | Initialize internal state from hashable object. | [
"Initialize",
"internal",
"state",
"from",
"hashable",
"object",
"."
] | def seed(self, a=None):
"""Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
If a is an int or long, a is used directly. Distinct values between
0 and 27814431486575L inclusive are guaranteed to yield distinct
internal states (this guarantee is specific to the default
Wichmann-Hill generator).
"""
if a is None:
try:
a = long(_hexlify(_urandom(16)), 16)
except NotImplementedError:
import time
a = long(time.time() * 256) # use fractional seconds
if not isinstance(a, (int, long)):
a = hash(a)
a, x = divmod(a, 30268)
a, y = divmod(a, 30306)
a, z = divmod(a, 30322)
self._seed = int(x)+1, int(y)+1, int(z)+1
self.gauss_next = None | [
"def",
"seed",
"(",
"self",
",",
"a",
"=",
"None",
")",
":",
"if",
"a",
"is",
"None",
":",
"try",
":",
"a",
"=",
"long",
"(",
"_hexlify",
"(",
"_urandom",
"(",
"16",
")",
")",
",",
"16",
")",
"except",
"NotImplementedError",
":",
"import",
"time"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/random.py#L661-L690 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/io/_fortran.py | python | FortranFile.read_ints | (self, dtype='i4') | return self.read_record(dtype) | Reads a record of a given type from the file, defaulting to an integer
type (``INTEGER*4`` in Fortran).
Parameters
----------
dtype : dtype, optional
Data type specifying the size and endiness of the data.
Returns
-------
data : ndarray
A one-dimensional array object.
See Also
--------
read_reals
read_record | Reads a record of a given type from the file, defaulting to an integer
type (``INTEGER*4`` in Fortran). | [
"Reads",
"a",
"record",
"of",
"a",
"given",
"type",
"from",
"the",
"file",
"defaulting",
"to",
"an",
"integer",
"type",
"(",
"INTEGER",
"*",
"4",
"in",
"Fortran",
")",
"."
] | def read_ints(self, dtype='i4'):
"""
Reads a record of a given type from the file, defaulting to an integer
type (``INTEGER*4`` in Fortran).
Parameters
----------
dtype : dtype, optional
Data type specifying the size and endiness of the data.
Returns
-------
data : ndarray
A one-dimensional array object.
See Also
--------
read_reals
read_record
"""
return self.read_record(dtype) | [
"def",
"read_ints",
"(",
"self",
",",
"dtype",
"=",
"'i4'",
")",
":",
"return",
"self",
".",
"read_record",
"(",
"dtype",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/io/_fortran.py#L258-L279 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | uCSIsCatPi | (code) | return ret | Check whether the character is part of Pi UCS Category | Check whether the character is part of Pi UCS Category | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Pi",
"UCS",
"Category"
] | def uCSIsCatPi(code):
"""Check whether the character is part of Pi UCS Category """
ret = libxml2mod.xmlUCSIsCatPi(code)
return ret | [
"def",
"uCSIsCatPi",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsCatPi",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2366-L2369 | |
logcabin/logcabin | ee6c55ae9744b82b451becd9707d26c7c1b6bbfb | scripts/cpplint.py | python | CheckCheck | (filename, clean_lines, linenum, error) | Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks the use of CHECK and EXPECT macros. | [
"Checks",
"the",
"use",
"of",
"CHECK",
"and",
"EXPECT",
"macros",
"."
] | def CheckCheck(filename, clean_lines, linenum, error):
"""Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Decide the set of replacement macros that should be suggested
raw_lines = clean_lines.raw_lines
current_macro = ''
for macro in _CHECK_MACROS:
if raw_lines[linenum].find(macro) >= 0:
current_macro = macro
break
if not current_macro:
# Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
return
line = clean_lines.elided[linenum] # get rid of comments and strings
# Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc.
for operator in ['==', '!=', '>=', '>', '<=', '<']:
if ReplaceableCheck(operator, current_macro, line):
error(filename, linenum, 'readability/check', 2,
'Consider using %s instead of %s(a %s b)' % (
_CHECK_REPLACEMENT[current_macro][operator],
current_macro, operator))
break | [
"def",
"CheckCheck",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Decide the set of replacement macros that should be suggested",
"raw_lines",
"=",
"clean_lines",
".",
"raw_lines",
"current_macro",
"=",
"''",
"for",
"macro",
"in",
"_... | https://github.com/logcabin/logcabin/blob/ee6c55ae9744b82b451becd9707d26c7c1b6bbfb/scripts/cpplint.py#L1974-L2004 | ||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/contrib/crosstalkcaffe/adapter/bvlccaffe/caffeadapter.py | python | SetupCaffeParameters.dropout | (caffe_parameters, inputs_info, cntk_layer_def) | The dropout parameter setup from Caffe to CNTK
Args:
caffe_parameters (:class:`caffe.Parameters`): the parameters of Caffe
inputs_info ('class':`cntk.contrib.crosstalkcaffe.unimodel.cntkmodel.CntkTensorDefinition`):
The input information of current layer
cntk_layer_def ('class':`cntk.contrib.crosstalkcaffe.unimodel.cntkmodel.CntkLayersDefinition`):
The converted definition of CNTK layers
Return:
None | The dropout parameter setup from Caffe to CNTK | [
"The",
"dropout",
"parameter",
"setup",
"from",
"Caffe",
"to",
"CNTK"
] | def dropout(caffe_parameters, inputs_info, cntk_layer_def):
'''
The dropout parameter setup from Caffe to CNTK
Args:
caffe_parameters (:class:`caffe.Parameters`): the parameters of Caffe
inputs_info ('class':`cntk.contrib.crosstalkcaffe.unimodel.cntkmodel.CntkTensorDefinition`):
The input information of current layer
cntk_layer_def ('class':`cntk.contrib.crosstalkcaffe.unimodel.cntkmodel.CntkLayersDefinition`):
The converted definition of CNTK layers
Return:
None
'''
SetupCaffeParameters.default(caffe_parameters, inputs_info, cntk_layer_def) | [
"def",
"dropout",
"(",
"caffe_parameters",
",",
"inputs_info",
",",
"cntk_layer_def",
")",
":",
"SetupCaffeParameters",
".",
"default",
"(",
"caffe_parameters",
",",
"inputs_info",
",",
"cntk_layer_def",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/contrib/crosstalkcaffe/adapter/bvlccaffe/caffeadapter.py#L264-L278 | ||
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/rocksdb-master/linters/cpp_linter/cpplint.py | python | CheckForBadCharacters | (filename, lines, error) | Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error for each line containing bad characters. | [
"Logs",
"an",
"error",
"for",
"each",
"line",
"containing",
"bad",
"characters",
"."
] | def CheckForBadCharacters(filename, lines, error):
"""Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
for linenum, line in enumerate(lines):
if u'\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
if '\0' in line:
error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') | [
"def",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"for",
"linenum",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"u'\\ufffd'",
"in",
"line",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'reada... | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/rocksdb-master/linters/cpp_linter/cpplint.py#L1481-L1503 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_view_interface.py | python | PlottingCanvasViewInterface.number_of_axes | (self) | Number of axes present in the figure | Number of axes present in the figure | [
"Number",
"of",
"axes",
"present",
"in",
"the",
"figure"
] | def number_of_axes(self):
"""Number of axes present in the figure"""
pass | [
"def",
"number_of_axes",
"(",
"self",
")",
":",
"pass"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_view_interface.py#L28-L30 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py | python | TFAsymmetryFittingModel._recalculate_tf_asymmetry_simultaneous_fit_function | (self) | Recalculates the TF Asymmetry simultaneous function. | Recalculates the TF Asymmetry simultaneous function. | [
"Recalculates",
"the",
"TF",
"Asymmetry",
"simultaneous",
"function",
"."
] | def _recalculate_tf_asymmetry_simultaneous_fit_function(self) -> None:
"""Recalculates the TF Asymmetry simultaneous function."""
self.tf_asymmetry_simultaneous_function = self._convert_to_tf_asymmetry_function(
self.fitting_context.simultaneous_fit_function, self.fitting_context.dataset_names) | [
"def",
"_recalculate_tf_asymmetry_simultaneous_fit_function",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"tf_asymmetry_simultaneous_function",
"=",
"self",
".",
"_convert_to_tf_asymmetry_function",
"(",
"self",
".",
"fitting_context",
".",
"simultaneous_fit_function",
... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py#L327-L330 | ||
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/tools/pretty_gyp.py | python | mask_comments | (input) | return [search_re.sub(comment_replace, line) for line in input] | Mask the quoted strings so we skip braces inside quoted strings. | Mask the quoted strings so we skip braces inside quoted strings. | [
"Mask",
"the",
"quoted",
"strings",
"so",
"we",
"skip",
"braces",
"inside",
"quoted",
"strings",
"."
] | def mask_comments(input):
"""Mask the quoted strings so we skip braces inside quoted strings."""
search_re = re.compile(r'(.*?)(#)(.*)')
return [search_re.sub(comment_replace, line) for line in input] | [
"def",
"mask_comments",
"(",
"input",
")",
":",
"search_re",
"=",
"re",
".",
"compile",
"(",
"r'(.*?)(#)(.*)'",
")",
"return",
"[",
"search_re",
".",
"sub",
"(",
"comment_replace",
",",
"line",
")",
"for",
"line",
"in",
"input",
"]"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/tools/pretty_gyp.py#L28-L31 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/cr/cr/commands/init.py | python | InitHook.Run | (self, context, old_version, config) | Run the initialization hook.
This is invoked once per init invocation.
Args:
context: The context of the init command.
old_version: The old version,
0.0 if the old version was bad or missing,
None if building a new output direcory.
config: The mutable config that will be written. | Run the initialization hook. | [
"Run",
"the",
"initialization",
"hook",
"."
] | def Run(self, context, old_version, config):
"""Run the initialization hook.
This is invoked once per init invocation.
Args:
context: The context of the init command.
old_version: The old version,
0.0 if the old version was bad or missing,
None if building a new output direcory.
config: The mutable config that will be written.
"""
raise NotImplementedError('Must be overridden.') | [
"def",
"Run",
"(",
"self",
",",
"context",
",",
"old_version",
",",
"config",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Must be overridden.'",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/cr/cr/commands/init.py#L168-L179 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | TypeHandler.WriteImmediateCmdInit | (self, func, file) | Writes the Init function for the immediate version of a command. | Writes the Init function for the immediate version of a command. | [
"Writes",
"the",
"Init",
"function",
"for",
"the",
"immediate",
"version",
"of",
"a",
"command",
"."
] | def WriteImmediateCmdInit(self, func, file):
"""Writes the Init function for the immediate version of a command."""
raise NotImplementedError(func.name) | [
"def",
"WriteImmediateCmdInit",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"raise",
"NotImplementedError",
"(",
"func",
".",
"name",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L2284-L2286 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_vehicletype.py | python | VehicleTypeDomain.getImperfection | (self, typeID) | return self._getUniversal(tc.VAR_IMPERFECTION, typeID) | getImperfection(string) -> double
Returns the driver's imperfection for vehicles of this type. | getImperfection(string) -> double | [
"getImperfection",
"(",
"string",
")",
"-",
">",
"double"
] | def getImperfection(self, typeID):
"""getImperfection(string) -> double
Returns the driver's imperfection for vehicles of this type.
"""
return self._getUniversal(tc.VAR_IMPERFECTION, typeID) | [
"def",
"getImperfection",
"(",
"self",
",",
"typeID",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_IMPERFECTION",
",",
"typeID",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicletype.py#L95-L100 | |
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/optimal_learning/python/cpp_wrappers/domain.py | python | TensorProductDomain.compute_update_restricted_to_domain | (self, max_relative_change, current_point, update_vector) | r"""Compute a new update so that CheckPointInside(``current_point`` + ``new_update``) is true.
We do not currently expose a C++ endpoint for this call; see :mod:`moe.optimal_learning.python.interfaces.domain_interface` for interface specification. | r"""Compute a new update so that CheckPointInside(``current_point`` + ``new_update``) is true. | [
"r",
"Compute",
"a",
"new",
"update",
"so",
"that",
"CheckPointInside",
"(",
"current_point",
"+",
"new_update",
")",
"is",
"true",
"."
] | def compute_update_restricted_to_domain(self, max_relative_change, current_point, update_vector):
r"""Compute a new update so that CheckPointInside(``current_point`` + ``new_update``) is true.
We do not currently expose a C++ endpoint for this call; see :mod:`moe.optimal_learning.python.interfaces.domain_interface` for interface specification.
"""
raise NotImplementedError("C++ wrapper currently does not support domain member functions.") | [
"def",
"compute_update_restricted_to_domain",
"(",
"self",
",",
"max_relative_change",
",",
"current_point",
",",
"update_vector",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"C++ wrapper currently does not support domain member functions.\"",
")"
] | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/cpp_wrappers/domain.py#L98-L104 | ||
bristolcrypto/SPDZ-2 | 721abfae849625a02ea49aabc534f9cf41ca643f | Compiler/path_oram.py | python | PathORAM.adjust_lca | (self, lca_bits, lev, not_empty, prnt=False) | return new_lca + [add_to_stash] | Adjust LCA based on bucket capacities (and original clear level, lev) | Adjust LCA based on bucket capacities (and original clear level, lev) | [
"Adjust",
"LCA",
"based",
"on",
"bucket",
"capacities",
"(",
"and",
"original",
"clear",
"level",
"lev",
")"
] | def adjust_lca(self, lca_bits, lev, not_empty, prnt=False):
""" Adjust LCA based on bucket capacities (and original clear level, lev) """
found = self.value_type(0)
assigned = self.value_type(0)
try_add_here = self.value_type(0)
new_lca = [self.value_type(0)] * (self.D + 1)
upper = min(lev + self.sigma, self.D)
lower = max(lev - self.tau, 0)
for j in range(upper, lower-1, -1):
found += lca_bits[j]
try_add_here += lca_bits[j]
if self.bucket_size == 4:
new_lca[j] = try_add_here * (1 - self.size_bits[j][2]) # (not_empty => lca_bits all 0)
#new_lca[j] = found * (1 - assigned) * (1 - self.size_bits[j][2]) * not_empty
elif self.bucket_size == 2 or self.bucket_size == 3:
new_lca[j] = try_add_here * (1 - self.size_bits[j][1])
if prnt:
new_lca[j].reveal().print_reg('nl%d' % j)
assigned += new_lca[j]
if self.value_type == sgf2n:
try_add_here += new_lca[j]
else:
try_add_here += new_lca[j] - 2*try_add_here*new_lca[j]
if self.bucket_size == 4:
t = new_lca[j] * self.size_bits[j][0]
t2 = t * self.size_bits[j][1]
# s_0 := s_0 \xor b
# s_1 := s_1 \xor (s_0 & b)
# s_2 := s_2 \xor (s_0 & s_1 & b)
if self.value_type == sgf2n:
self.size_bits[j][0] += new_lca[j]
self.size_bits[j][1] += t
self.size_bits[j][2] += t2 #t * self.size_bits[j][1]
else:
self.size_bits[j][0] += new_lca[j] - 2*t
self.size_bits[j][1] += t - 2*t2
self.size_bits[j][2] += t2
# '1 if empty' bit
#self.size_bits[j][3] *= (1 - new_lca[j])
elif self.bucket_size == 2 or self.bucket_size == 3:
t = new_lca[j] * self.size_bits[j][0]
if self.value_type == sgf2n:
self.size_bits[j][0] += new_lca[j]
else:
self.size_bits[j][0] += new_lca[j] - 2*t
self.size_bits[j][1] += t
else:
raise CompilerError('Bucket size %d not supported' % self.bucket_size)
add_to_stash = not_empty - sum(new_lca)
#final_level = sum(new_lca[i]*i for i in range(self.D+1)) + add_to_stash * (self.D+1)
#
#if_then(cint(reveal(not_empty)))
#final_level.reveal().print_reg('lca')
#for j in range(2):
# for k,b in enumerate(self.size_bits[j]):
# b.reveal().print_reg('u%dj%d' % (k,j))
#end_if()
return new_lca + [add_to_stash] | [
"def",
"adjust_lca",
"(",
"self",
",",
"lca_bits",
",",
"lev",
",",
"not_empty",
",",
"prnt",
"=",
"False",
")",
":",
"found",
"=",
"self",
".",
"value_type",
"(",
"0",
")",
"assigned",
"=",
"self",
".",
"value_type",
"(",
"0",
")",
"try_add_here",
"... | https://github.com/bristolcrypto/SPDZ-2/blob/721abfae849625a02ea49aabc534f9cf41ca643f/Compiler/path_oram.py#L571-L635 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/html.py | python | HtmlPrintout.SetStandardFonts | (*args, **kwargs) | return _html.HtmlPrintout_SetStandardFonts(*args, **kwargs) | SetStandardFonts(self, int size=-1, String normal_face=EmptyString, String fixed_face=EmptyString) | SetStandardFonts(self, int size=-1, String normal_face=EmptyString, String fixed_face=EmptyString) | [
"SetStandardFonts",
"(",
"self",
"int",
"size",
"=",
"-",
"1",
"String",
"normal_face",
"=",
"EmptyString",
"String",
"fixed_face",
"=",
"EmptyString",
")"
] | def SetStandardFonts(*args, **kwargs):
"""SetStandardFonts(self, int size=-1, String normal_face=EmptyString, String fixed_face=EmptyString)"""
return _html.HtmlPrintout_SetStandardFonts(*args, **kwargs) | [
"def",
"SetStandardFonts",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlPrintout_SetStandardFonts",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L1296-L1298 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/RecoTrack/python/plotting/validation.py | python | Sample.pileupType | (self, release=None) | Return the pileup type | Return the pileup type | [
"Return",
"the",
"pileup",
"type"
] | def pileupType(self, release=None):
"""Return the pileup type"""
if isinstance(self._putype, dict):
return self._putype.get(release, self._putype["default"])
else:
return self._putype | [
"def",
"pileupType",
"(",
"self",
",",
"release",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_putype",
",",
"dict",
")",
":",
"return",
"self",
".",
"_putype",
".",
"get",
"(",
"release",
",",
"self",
".",
"_putype",
"[",
"\"defaul... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/validation.py#L560-L565 | ||
lhmRyan/deep-supervised-hashing-DSH | 631901f82e2ab031fbac33f914a5b08ef8e21d57 | scripts/cpp_lint.py | python | CheckStyle | (filename, clean_lines, linenum, file_extension, nesting_state,
error) | Checks rules from the 'C++ style rules' section of cppguide.html.
Most of these rules are hard to test (naming, comment style), but we
do what we can. In particular we check for 2-space indents, line lengths,
tab usage, spaces inside code, etc.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks rules from the 'C++ style rules' section of cppguide.html. | [
"Checks",
"rules",
"from",
"the",
"C",
"++",
"style",
"rules",
"section",
"of",
"cppguide",
".",
"html",
"."
] | def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
error):
"""Checks rules from the 'C++ style rules' section of cppguide.html.
Most of these rules are hard to test (naming, comment style), but we
do what we can. In particular we check for 2-space indents, line lengths,
tab usage, spaces inside code, etc.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw_lines = clean_lines.lines_without_raw_strings
line = raw_lines[linenum]
if line.find('\t') != -1:
error(filename, linenum, 'whitespace/tab', 1,
'Tab found; better to use spaces')
# One or three blank spaces at the beginning of the line is weird; it's
# hard to reconcile that with 2-space indents.
# NOTE: here are the conditions rob pike used for his tests. Mine aren't
# as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
# if(RLENGTH > 20) complain = 0;
# if(match($0, " +(error|private|public|protected):")) complain = 0;
# if(match(prev, "&& *$")) complain = 0;
# if(match(prev, "\\|\\| *$")) complain = 0;
# if(match(prev, "[\",=><] *$")) complain = 0;
# if(match($0, " <<")) complain = 0;
# if(match(prev, " +for \\(")) complain = 0;
# if(prevodd && match(prevprev, " +for \\(")) complain = 0;
initial_spaces = 0
cleansed_line = clean_lines.elided[linenum]
while initial_spaces < len(line) and line[initial_spaces] == ' ':
initial_spaces += 1
if line and line[-1].isspace():
error(filename, linenum, 'whitespace/end_of_line', 4,
'Line ends in whitespace. Consider deleting these extra spaces.')
# There are certain situations we allow one space, notably for section labels
elif ((initial_spaces == 1 or initial_spaces == 3) and
not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
error(filename, linenum, 'whitespace/indent', 3,
'Weird number of spaces at line-start. '
'Are you using a 2-space indent?')
# Check if the line is a header guard.
is_header_guard = False
if file_extension == 'h':
cppvar = GetHeaderGuardCPPVariable(filename)
if (line.startswith('#ifndef %s' % cppvar) or
line.startswith('#define %s' % cppvar) or
line.startswith('#endif // %s' % cppvar)):
is_header_guard = True
# #include lines and header guards can be long, since there's no clean way to
# split them.
#
# URLs can be long too. It's possible to split these, but it makes them
# harder to cut&paste.
#
# The "$Id:...$" comment may also get very long without it being the
# developers fault.
if (not line.startswith('#include') and not is_header_guard and
not Match(r'^\s*//.*http(s?)://\S*$', line) and
not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
line_width = GetLineWidth(line)
extended_length = int((_line_length * 1.25))
if line_width > extended_length:
error(filename, linenum, 'whitespace/line_length', 4,
'Lines should very rarely be longer than %i characters' %
extended_length)
elif line_width > _line_length:
error(filename, linenum, 'whitespace/line_length', 2,
'Lines should be <= %i characters long' % _line_length)
if (cleansed_line.count(';') > 1 and
# for loops are allowed two ;'s (and may run over two lines).
cleansed_line.find('for') == -1 and
(GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
# It's ok to have many commands in a switch case that fits in 1 line
not ((cleansed_line.find('case ') != -1 or
cleansed_line.find('default:') != -1) and
cleansed_line.find('break;') != -1)):
error(filename, linenum, 'whitespace/newline', 0,
'More than one command on the same line')
# Some more style checks
CheckBraces(filename, clean_lines, linenum, error)
CheckEmptyBlockBody(filename, clean_lines, linenum, error)
CheckAccess(filename, clean_lines, linenum, nesting_state, error)
CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
CheckCheck(filename, clean_lines, linenum, error)
CheckAltTokens(filename, clean_lines, linenum, error)
classinfo = nesting_state.InnermostClass()
if classinfo:
CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) | [
"def",
"CheckStyle",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"file_extension",
",",
"nesting_state",
",",
"error",
")",
":",
"# Don't use \"elided\" lines here, otherwise we can't check commented lines.",
"# Don't want to use \"raw\" either, because we don't want ... | https://github.com/lhmRyan/deep-supervised-hashing-DSH/blob/631901f82e2ab031fbac33f914a5b08ef8e21d57/scripts/cpp_lint.py#L3459-L3563 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.