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
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/math_ops.py
python
_as_indexed_slices_list
(inputs)
return casted_outputs
Convert all elements of 'inputs' to IndexedSlices. Additionally, homogenize the types of all the indices to either int32 or int64. Args: inputs: List containing either Tensor or IndexedSlices objects. Returns: A list of IndexedSlices objects. Raises: TypeError: If 'inputs' is not a list or a tuple.
Convert all elements of 'inputs' to IndexedSlices.
[ "Convert", "all", "elements", "of", "inputs", "to", "IndexedSlices", "." ]
def _as_indexed_slices_list(inputs): """Convert all elements of 'inputs' to IndexedSlices. Additionally, homogenize the types of all the indices to either int32 or int64. Args: inputs: List containing either Tensor or IndexedSlices objects. Returns: A list of IndexedSlices objects. Raises: TypeError: If 'inputs' is not a list or a tuple. """ if not isinstance(inputs, (list, tuple)): raise TypeError("Expected a list or tuple, not a %s" % type(inputs)) outputs = [_as_indexed_slices(i) for i in inputs] with_int32_index = [o.indices for o in outputs if o.indices.dtype == dtypes.int32] if not with_int32_index or len(with_int32_index) == len(outputs): return outputs casted_outputs = [] for o in outputs: if o.indices.dtype == dtypes.int32: casted_outputs.append( ops.IndexedSlices(o.values, cast(o.indices, dtypes.int64), o.dense_shape)) else: casted_outputs.append(o) return casted_outputs
[ "def", "_as_indexed_slices_list", "(", "inputs", ")", ":", "if", "not", "isinstance", "(", "inputs", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"Expected a list or tuple, not a %s\"", "%", "type", "(", "inputs", ")", ")", "ou...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L1413-L1443
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py
python
pyparsing_common.convertToDatetime
(fmt="%Y-%m-%dT%H:%M:%S.%f")
return cvt_fn
Helper to create a parse action for converting parsed datetime string to Python datetime.datetime Params - - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"}) Example:: dt_expr = pyparsing_common.iso8601_datetime.copy() dt_expr.setParseAction(pyparsing_common.convertToDatetime()) print(dt_expr.parseString("1999-12-31T23:59:59.999")) prints:: [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
Helper to create a parse action for converting parsed datetime string to Python datetime.datetime
[ "Helper", "to", "create", "a", "parse", "action", "for", "converting", "parsed", "datetime", "string", "to", "Python", "datetime", ".", "datetime" ]
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"): """ Helper to create a parse action for converting parsed datetime string to Python datetime.datetime Params - - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"}) Example:: dt_expr = pyparsing_common.iso8601_datetime.copy() dt_expr.setParseAction(pyparsing_common.convertToDatetime()) print(dt_expr.parseString("1999-12-31T23:59:59.999")) prints:: [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] """ def cvt_fn(s,l,t): try: return datetime.strptime(t[0], fmt) except ValueError as ve: raise ParseException(s, l, str(ve)) return cvt_fn
[ "def", "convertToDatetime", "(", "fmt", "=", "\"%Y-%m-%dT%H:%M:%S.%f\"", ")", ":", "def", "cvt_fn", "(", "s", ",", "l", ",", "t", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "t", "[", "0", "]", ",", "fmt", ")", "except", "ValueE...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py#L5615-L5634
jolibrain/deepdetect
9bc840f0b1055426670d64b5285701d6faceabb9
clients/python/dd_client/__init__.py
python
DD.post_train
( self, sname, data, parameters_input, parameters_mllib, parameters_output, jasync=True, )
return self.post(self.__urls["train"], json=data)
Creates a training job Parameters: sname -- service name as a resource jasync -- whether to run the job as non-blocking data -- array of input data / dataset for training parameters_input -- dict of input parameters parameters_mllib -- dict ML library parameters parameters_output -- dict of output parameters
Creates a training job Parameters: sname -- service name as a resource jasync -- whether to run the job as non-blocking data -- array of input data / dataset for training parameters_input -- dict of input parameters parameters_mllib -- dict ML library parameters parameters_output -- dict of output parameters
[ "Creates", "a", "training", "job", "Parameters", ":", "sname", "--", "service", "name", "as", "a", "resource", "jasync", "--", "whether", "to", "run", "the", "job", "as", "non", "-", "blocking", "data", "--", "array", "of", "input", "data", "/", "dataset...
def post_train( self, sname, data, parameters_input, parameters_mllib, parameters_output, jasync=True, ): """ Creates a training job Parameters: sname -- service name as a resource jasync -- whether to run the job as non-blocking data -- array of input data / dataset for training parameters_input -- dict of input parameters parameters_mllib -- dict ML library parameters parameters_output -- dict of output parameters """ data = { "service": sname, "async": jasync, "parameters": { "input": parameters_input, "mllib": parameters_mllib, "output": parameters_output, }, "data": data, } return self.post(self.__urls["train"], json=data)
[ "def", "post_train", "(", "self", ",", "sname", ",", "data", ",", "parameters_input", ",", "parameters_mllib", ",", "parameters_output", ",", "jasync", "=", "True", ",", ")", ":", "data", "=", "{", "\"service\"", ":", "sname", ",", "\"async\"", ":", "jasyn...
https://github.com/jolibrain/deepdetect/blob/9bc840f0b1055426670d64b5285701d6faceabb9/clients/python/dd_client/__init__.py#L193-L222
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/learn/python/learn/experiment.py
python
Experiment.local_run
(self)
return self.evaluate(delay_secs=0)
Run when called on local machine. Returns: The result of the `evaluate` call to the `Estimator`.
Run when called on local machine.
[ "Run", "when", "called", "on", "local", "machine", "." ]
def local_run(self): """Run when called on local machine. Returns: The result of the `evaluate` call to the `Estimator`. """ self._train_monitors = self._train_monitors or [] if self._local_eval_frequency: self._train_monitors += [monitors.ValidationMonitor( input_fn=self._eval_input_fn, eval_steps=self._eval_steps, metrics=self._eval_metrics, every_n_steps=self._local_eval_frequency )] self.train(delay_secs=0) return self.evaluate(delay_secs=0)
[ "def", "local_run", "(", "self", ")", ":", "self", ".", "_train_monitors", "=", "self", ".", "_train_monitors", "or", "[", "]", "if", "self", ".", "_local_eval_frequency", ":", "self", ".", "_train_monitors", "+=", "[", "monitors", ".", "ValidationMonitor", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/experiment.py#L146-L159
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/fourcircle_utility.py
python
get_spice_file_name
(instrument_name, exp_number, scan_number)
return file_name
Get standard HB3A SPICE file name from experiment number and scan number :param instrument_name :param exp_number: :param scan_number: :return:
Get standard HB3A SPICE file name from experiment number and scan number :param instrument_name :param exp_number: :param scan_number: :return:
[ "Get", "standard", "HB3A", "SPICE", "file", "name", "from", "experiment", "number", "and", "scan", "number", ":", "param", "instrument_name", ":", "param", "exp_number", ":", ":", "param", "scan_number", ":", ":", "return", ":" ]
def get_spice_file_name(instrument_name, exp_number, scan_number): """ Get standard HB3A SPICE file name from experiment number and scan number :param instrument_name :param exp_number: :param scan_number: :return: """ assert isinstance(instrument_name, str) assert isinstance(exp_number, int) and isinstance(scan_number, int) file_name = '%s_exp%04d_scan%04d.dat' % (instrument_name, exp_number, scan_number) return file_name
[ "def", "get_spice_file_name", "(", "instrument_name", ",", "exp_number", ",", "scan_number", ")", ":", "assert", "isinstance", "(", "instrument_name", ",", "str", ")", "assert", "isinstance", "(", "exp_number", ",", "int", ")", "and", "isinstance", "(", "scan_nu...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/fourcircle_utility.py#L411-L423
OPAE/opae-sdk
221124343c8275243a249eb72d69e0ea2d568d1b
python/opae.admin/opae/admin/sysfs.py
python
pci_node.device
(self)
return self._pci_address['device']
device get the pci device of the node
device get the pci device of the node
[ "device", "get", "the", "pci", "device", "of", "the", "node" ]
def device(self): """device get the pci device of the node""" return self._pci_address['device']
[ "def", "device", "(", "self", ")", ":", "return", "self", ".", "_pci_address", "[", "'device'", "]" ]
https://github.com/OPAE/opae-sdk/blob/221124343c8275243a249eb72d69e0ea2d568d1b/python/opae.admin/opae/admin/sysfs.py#L366-L368
rbgirshick/caffe-fast-rcnn
28a579eaf0668850705598b3075b8969f22226d9
python/caffe/draw.py
python
choose_color_by_layertype
(layertype)
return color
Define colors for nodes based on the layer type.
Define colors for nodes based on the layer type.
[ "Define", "colors", "for", "nodes", "based", "on", "the", "layer", "type", "." ]
def choose_color_by_layertype(layertype): """Define colors for nodes based on the layer type. """ color = '#6495ED' # Default if layertype == 'Convolution': color = '#FF5050' elif layertype == 'Pooling': color = '#FF9900' elif layertype == 'InnerProduct': color = '#CC33FF' return color
[ "def", "choose_color_by_layertype", "(", "layertype", ")", ":", "color", "=", "'#6495ED'", "# Default", "if", "layertype", "==", "'Convolution'", ":", "color", "=", "'#FF5050'", "elif", "layertype", "==", "'Pooling'", ":", "color", "=", "'#FF9900'", "elif", "lay...
https://github.com/rbgirshick/caffe-fast-rcnn/blob/28a579eaf0668850705598b3075b8969f22226d9/python/caffe/draw.py#L108-L118
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/numbers.py
python
Integral.__and__
(self, other)
self & other
self & other
[ "self", "&", "other" ]
def __and__(self, other): """self & other""" raise NotImplementedError
[ "def", "__and__", "(", "self", ",", "other", ")", ":", "raise", "NotImplementedError" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/numbers.py#L341-L343
akai-katto/dandere2x
bf1a46d5c9f9ffc8145a412c3571b283345b8512
src/dandere2x/dandere2xlib/wrappers/ffmpeg/ffprobe.py
python
get_video_info
(ffprobe_dir, input_video)
return json.loads(json_str.decode('utf-8'))
Gets input video information This method reads input video information using ffprobe in dictionary. Arguments: input_video {string} -- input video file path Returns: dictionary -- JSON text of input video information
Gets input video information This method reads input video information using ffprobe in dictionary. Arguments: input_video {string} -- input video file path Returns: dictionary -- JSON text of input video information
[ "Gets", "input", "video", "information", "This", "method", "reads", "input", "video", "information", "using", "ffprobe", "in", "dictionary", ".", "Arguments", ":", "input_video", "{", "string", "}", "--", "input", "video", "file", "path", "Returns", ":", "dict...
def get_video_info(ffprobe_dir, input_video): """ Gets input video information This method reads input video information using ffprobe in dictionary. Arguments: input_video {string} -- input video file path Returns: dictionary -- JSON text of input video information """ assert get_operating_system() != "win32" or os.path.exists(ffprobe_dir), "%s does not exist!" % ffprobe_dir # this execution command needs to be hard-coded # since video2x only strictly recignizes this one format execute = [ ffprobe_dir, '-v', 'panic', '-print_format', 'json', '-show_format', '-show_streams', '-i', input_video ] log = logging.getLogger() log.info("Loading video meta-data with ffprobe.. this might take a while.") log.info("Command: %s" % str(execute)) json_str = subprocess.run(execute, check=True, stdout=subprocess.PIPE).stdout return json.loads(json_str.decode('utf-8'))
[ "def", "get_video_info", "(", "ffprobe_dir", ",", "input_video", ")", ":", "assert", "get_operating_system", "(", ")", "!=", "\"win32\"", "or", "os", ".", "path", ".", "exists", "(", "ffprobe_dir", ")", ",", "\"%s does not exist!\"", "%", "ffprobe_dir", "# this ...
https://github.com/akai-katto/dandere2x/blob/bf1a46d5c9f9ffc8145a412c3571b283345b8512/src/dandere2x/dandere2xlib/wrappers/ffmpeg/ffprobe.py#L13-L44
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
PointCloud.join
(self, pc)
return _robotsim.PointCloud_join(self, pc)
join(PointCloud self, PointCloud pc) Adds the given point cloud to this one. They must share the same properties or else an exception is raised.
join(PointCloud self, PointCloud pc)
[ "join", "(", "PointCloud", "self", "PointCloud", "pc", ")" ]
def join(self, pc): """ join(PointCloud self, PointCloud pc) Adds the given point cloud to this one. They must share the same properties or else an exception is raised. """ return _robotsim.PointCloud_join(self, pc)
[ "def", "join", "(", "self", ",", "pc", ")", ":", "return", "_robotsim", ".", "PointCloud_join", "(", "self", ",", "pc", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L1196-L1206
vslavik/poedit
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
deps/boost/tools/build/src/build/targets.py
python
ProjectTarget.targets_to_build
(self)
return result
Computes and returns a list of AbstractTarget instances which must be built when this project is built.
Computes and returns a list of AbstractTarget instances which must be built when this project is built.
[ "Computes", "and", "returns", "a", "list", "of", "AbstractTarget", "instances", "which", "must", "be", "built", "when", "this", "project", "is", "built", "." ]
def targets_to_build (self): """ Computes and returns a list of AbstractTarget instances which must be built when this project is built. """ result = [] if not self.built_main_targets_: self.build_main_targets () # Collect all main targets here, except for "explicit" ones. for n, t in self.main_target_.iteritems (): if not t.name () in self.explicit_targets_: result.append (t) # Collect all projects referenced via "projects-to-build" attribute. self_location = self.get ('location') for pn in self.get ('projects-to-build'): result.append (self.find(pn + "/")) return result
[ "def", "targets_to_build", "(", "self", ")", ":", "result", "=", "[", "]", "if", "not", "self", ".", "built_main_targets_", ":", "self", ".", "build_main_targets", "(", ")", "# Collect all main targets here, except for \"explicit\" ones.", "for", "n", ",", "t", "i...
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/targets.py#L450-L469
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/descriptor.py
python
Descriptor.__init__
(self, name, full_name, filename, containing_type, fields, nested_types, enum_types, extensions, options=None, serialized_options=None, is_extendable=True, extension_ranges=None, oneofs=None, file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin syntax=None, create_key=None)
Arguments to __init__() are as described in the description of Descriptor fields above. Note that filename is an obsolete argument, that is not used anymore. Please use file.name to access this as an attribute.
Arguments to __init__() are as described in the description of Descriptor fields above.
[ "Arguments", "to", "__init__", "()", "are", "as", "described", "in", "the", "description", "of", "Descriptor", "fields", "above", "." ]
def __init__(self, name, full_name, filename, containing_type, fields, nested_types, enum_types, extensions, options=None, serialized_options=None, is_extendable=True, extension_ranges=None, oneofs=None, file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin syntax=None, create_key=None): """Arguments to __init__() are as described in the description of Descriptor fields above. Note that filename is an obsolete argument, that is not used anymore. Please use file.name to access this as an attribute. """ if create_key is not _internal_create_key: _Deprecated('Descriptor') super(Descriptor, self).__init__( options, 'MessageOptions', name, full_name, file, containing_type, serialized_start=serialized_start, serialized_end=serialized_end, serialized_options=serialized_options) # We have fields in addition to fields_by_name and fields_by_number, # so that: # 1. Clients can index fields by "order in which they're listed." # 2. Clients can easily iterate over all fields with the terse # syntax: for f in descriptor.fields: ... self.fields = fields for field in self.fields: field.containing_type = self self.fields_by_number = dict((f.number, f) for f in fields) self.fields_by_name = dict((f.name, f) for f in fields) self._fields_by_camelcase_name = None self.nested_types = nested_types for nested_type in nested_types: nested_type.containing_type = self self.nested_types_by_name = dict((t.name, t) for t in nested_types) self.enum_types = enum_types for enum_type in self.enum_types: enum_type.containing_type = self self.enum_types_by_name = dict((t.name, t) for t in enum_types) self.enum_values_by_name = dict( (v.name, v) for t in enum_types for v in t.values) self.extensions = extensions for extension in self.extensions: extension.extension_scope = self self.extensions_by_name = dict((f.name, f) for f in extensions) self.is_extendable = is_extendable self.extension_ranges = extension_ranges self.oneofs = oneofs if oneofs is not None else [] self.oneofs_by_name = dict((o.name, o) for o in self.oneofs) for oneof in self.oneofs: oneof.containing_type = self self.syntax = syntax or "proto2"
[ "def", "__init__", "(", "self", ",", "name", ",", "full_name", ",", "filename", ",", "containing_type", ",", "fields", ",", "nested_types", ",", "enum_types", ",", "extensions", ",", "options", "=", "None", ",", "serialized_options", "=", "None", ",", "is_ex...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/descriptor.py#L316-L370
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Task.py
python
compile_fun_shell
(line)
return (funex(c), dvars)
Creates a compiled function to execute a process through a sub-shell
Creates a compiled function to execute a process through a sub-shell
[ "Creates", "a", "compiled", "function", "to", "execute", "a", "process", "through", "a", "sub", "-", "shell" ]
def compile_fun_shell(line): """ Creates a compiled function to execute a process through a sub-shell """ extr = [] def repl(match): g = match.group if g('dollar'): return "$" elif g('backslash'): return '\\\\' elif g('subst'): extr.append((g('var'), g('code'))) return "%s" return None line = reg_act.sub(repl, line) or line dvars = [] def add_dvar(x): if x not in dvars: dvars.append(x) def replc(m): # performs substitutions and populates dvars if m.group('and'): return ' and ' elif m.group('or'): return ' or ' else: x = m.group('var') add_dvar(x) return 'env[%r]' % x parm = [] app = parm.append for (var, meth) in extr: if var == 'SRC': if meth: app('tsk.inputs%s' % meth) else: app('" ".join([a.path_from(cwdx) for a in tsk.inputs])') elif var == 'TGT': if meth: app('tsk.outputs%s' % meth) else: app('" ".join([a.path_from(cwdx) for a in tsk.outputs])') elif meth: if meth.startswith(':'): add_dvar(var) m = meth[1:] if m == 'SRC': m = '[a.path_from(cwdx) for a in tsk.inputs]' elif m == 'TGT': m = '[a.path_from(cwdx) for a in tsk.outputs]' elif re_novar.match(m): m = '[tsk.inputs%s]' % m[3:] elif re_novar.match(m): m = '[tsk.outputs%s]' % m[3:] else: add_dvar(m) if m[:3] not in ('tsk', 'gen', 'bld'): m = '%r' % m app('" ".join(tsk.colon(%r, %s))' % (var, m)) elif meth.startswith('?'): # In A?B|C output env.A if one of env.B or env.C is non-empty expr = re_cond.sub(replc, meth[1:]) app('p(%r) if (%s) else ""' % (var, expr)) else: call = '%s%s' % (var, meth) add_dvar(call) app(call) else: add_dvar(var) app("p('%s')" % var) if parm: parm = "%% (%s) " % (',\n\t\t'.join(parm)) else: parm = '' c = COMPILE_TEMPLATE_SHELL % (line, parm) Logs.debug('action: %s', c.strip().splitlines()) return (funex(c), dvars)
[ "def", "compile_fun_shell", "(", "line", ")", ":", "extr", "=", "[", "]", "def", "repl", "(", "match", ")", ":", "g", "=", "match", ".", "group", "if", "g", "(", "'dollar'", ")", ":", "return", "\"$\"", "elif", "g", "(", "'backslash'", ")", ":", ...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Task.py#L1056-L1136
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/demand/virtualpop.py
python
Virtualpopulation.select_plans_random
(self, fraction=0.1, **kwargs)
return True
A fraction of the population changes a plan. The new plans are chosen randomly.
A fraction of the population changes a plan. The new plans are chosen randomly.
[ "A", "fraction", "of", "the", "population", "changes", "a", "plan", ".", "The", "new", "plans", "are", "chosen", "randomly", "." ]
def select_plans_random(self, fraction=0.1, **kwargs): """ A fraction of the population changes a plan. The new plans are chosen randomly. """ ids_pers_all = self.get_ids() print 'select_plans_random', len(ids_pers_all), fraction times_est = self.get_plans().times_est # self.ids_plan.reset() # ids_mode[random_choice(n,shares/np.sum(shares))] ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)] print ' ids_pers', ids_pers for id_pers, ids_plan in zip(ids_pers, self.lists_ids_plan[ids_pers]): if len(ids_plan) > 0: # print ' id_pers,ids_plan',id_pers,ids_plan self.ids_plan[id_pers] = ids_plan[np.random.randint(len(ids_plan))] return True
[ "def", "select_plans_random", "(", "self", ",", "fraction", "=", "0.1", ",", "*", "*", "kwargs", ")", ":", "ids_pers_all", "=", "self", ".", "get_ids", "(", ")", "print", "'select_plans_random'", ",", "len", "(", "ids_pers_all", ")", ",", "fraction", "time...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/virtualpop.py#L6496-L6514
llvm-mirror/libcxx
78d6a7767ed57b50122a161b91f59f19c9bd0d19
utils/google-benchmark/tools/gbench/util.py
python
run_benchmark
(exe_name, benchmark_flags)
return json_res
Run a benchmark specified by 'exe_name' with the specified 'benchmark_flags'. The benchmark is run directly as a subprocess to preserve real time console output. RETURNS: A JSON object representing the benchmark output
Run a benchmark specified by 'exe_name' with the specified 'benchmark_flags'. The benchmark is run directly as a subprocess to preserve real time console output. RETURNS: A JSON object representing the benchmark output
[ "Run", "a", "benchmark", "specified", "by", "exe_name", "with", "the", "specified", "benchmark_flags", ".", "The", "benchmark", "is", "run", "directly", "as", "a", "subprocess", "to", "preserve", "real", "time", "console", "output", ".", "RETURNS", ":", "A", ...
def run_benchmark(exe_name, benchmark_flags): """ Run a benchmark specified by 'exe_name' with the specified 'benchmark_flags'. The benchmark is run directly as a subprocess to preserve real time console output. RETURNS: A JSON object representing the benchmark output """ output_name = find_benchmark_flag('--benchmark_out=', benchmark_flags) is_temp_output = False if output_name is None: is_temp_output = True thandle, output_name = tempfile.mkstemp() os.close(thandle) benchmark_flags = list(benchmark_flags) + \ ['--benchmark_out=%s' % output_name] cmd = [exe_name] + benchmark_flags print("RUNNING: %s" % ' '.join(cmd)) exitCode = subprocess.call(cmd) if exitCode != 0: print('TEST FAILED...') sys.exit(exitCode) json_res = load_benchmark_results(output_name) if is_temp_output: os.unlink(output_name) return json_res
[ "def", "run_benchmark", "(", "exe_name", ",", "benchmark_flags", ")", ":", "output_name", "=", "find_benchmark_flag", "(", "'--benchmark_out='", ",", "benchmark_flags", ")", "is_temp_output", "=", "False", "if", "output_name", "is", "None", ":", "is_temp_output", "=...
https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/utils/google-benchmark/tools/gbench/util.py#L122-L148
eldar/deepcut-cnn
928bf2f224fce132f6e4404b4c95fb017297a5e0
scripts/cpp_lint.py
python
_IncludeState.IsInAlphabeticalOrder
(self, clean_lines, linenum, header_path)
return True
Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order.
Check if a header is in alphabetical order with the previous header.
[ "Check", "if", "a", "header", "is", "in", "alphabetical", "order", "with", "the", "previous", "header", "." ]
def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): """Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order. """ # If previous section is different from current section, _last_header will # be reset to empty string, so it's always less than current header. # # If previous line was a blank line, assume that the headers are # intentionally sorted the way they are. if (self._last_header > header_path and not Match(r'^\s*$', clean_lines.elided[linenum - 1])): return False return True
[ "def", "IsInAlphabeticalOrder", "(", "self", ",", "clean_lines", ",", "linenum", ",", "header_path", ")", ":", "# If previous section is different from current section, _last_header will", "# be reset to empty string, so it's always less than current header.", "#", "# If previous line ...
https://github.com/eldar/deepcut-cnn/blob/928bf2f224fce132f6e4404b4c95fb017297a5e0/scripts/cpp_lint.py#L612-L631
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/platform/android_platform_backend.py
python
AndroidPlatformBackend.PurgeUnpinnedMemory
(self)
Purges the unpinned ashmem memory for the whole system. This can be used to make memory measurements more stable. Requires root.
Purges the unpinned ashmem memory for the whole system.
[ "Purges", "the", "unpinned", "ashmem", "memory", "for", "the", "whole", "system", "." ]
def PurgeUnpinnedMemory(self): """Purges the unpinned ashmem memory for the whole system. This can be used to make memory measurements more stable. Requires root. """ if not self._can_elevate_privilege: logging.warning('Cannot run purge_ashmem. Requires a rooted device.') return if not android_prebuilt_profiler_helper.InstallOnDevice( self._device, 'purge_ashmem'): raise Exception('Error installing purge_ashmem.') output = self._device.RunShellCommand([ android_prebuilt_profiler_helper.GetDevicePath('purge_ashmem')]) for l in output: logging.info(l)
[ "def", "PurgeUnpinnedMemory", "(", "self", ")", ":", "if", "not", "self", ".", "_can_elevate_privilege", ":", "logging", ".", "warning", "(", "'Cannot run purge_ashmem. Requires a rooted device.'", ")", "return", "if", "not", "android_prebuilt_profiler_helper", ".", "In...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/platform/android_platform_backend.py#L240-L255
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/connectionpool.py
python
HTTPSConnectionPool._new_conn
(self)
return self._prepare_conn(conn)
Return a fresh :class:`httplib.HTTPSConnection`.
Return a fresh :class:`httplib.HTTPSConnection`.
[ "Return", "a", "fresh", ":", "class", ":", "httplib", ".", "HTTPSConnection", "." ]
def _new_conn(self): """ Return a fresh :class:`httplib.HTTPSConnection`. """ self.num_connections += 1 log.debug( "Starting new HTTPS connection (%d): %s:%s", self.num_connections, self.host, self.port or "443", ) if not self.ConnectionCls or self.ConnectionCls is DummyConnection: raise SSLError( "Can't connect to HTTPS URL because the SSL module is not available." ) actual_host = self.host actual_port = self.port if self.proxy is not None: actual_host = self.proxy.host actual_port = self.proxy.port conn = self.ConnectionCls( host=actual_host, port=actual_port, timeout=self.timeout.connect_timeout, strict=self.strict, cert_file=self.cert_file, key_file=self.key_file, key_password=self.key_password, **self.conn_kw ) return self._prepare_conn(conn)
[ "def", "_new_conn", "(", "self", ")", ":", "self", ".", "num_connections", "+=", "1", "log", ".", "debug", "(", "\"Starting new HTTPS connection (%d): %s:%s\"", ",", "self", ".", "num_connections", ",", "self", ".", "host", ",", "self", ".", "port", "or", "\...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/connectionpool.py#L950-L984
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/Dice3DS/util.py
python
calculate_normals_by_angle_subtended
(pointarray,facearray,smarray)
return points, numpy.asarray(fnorms,numpy.float32)
Calculate normals by smoothing, weighting by angle subtended. points,norms = calculate_normals_by_angle_subtended( pointarray,facearray,smarray) Takes an array of points, faces, and a smoothing group in exactly the same form in which they appear in the 3DS DOM. Returns a numpy.array of points, one per row, and a numpy.array of the corresponding normals. The points are returned as a list of consecutive triangles; the first three rows make up the first triangle, the second three rows make up the second triangle, and so on. To calculate the normal of a given vertex on a given face, this function averages the normal vector for all faces which have share that vertex, and a smoothing group. The normals being averaged are weighted by the angle subtended.
Calculate normals by smoothing, weighting by angle subtended.
[ "Calculate", "normals", "by", "smoothing", "weighting", "by", "angle", "subtended", "." ]
def calculate_normals_by_angle_subtended(pointarray,facearray,smarray): """Calculate normals by smoothing, weighting by angle subtended. points,norms = calculate_normals_by_angle_subtended( pointarray,facearray,smarray) Takes an array of points, faces, and a smoothing group in exactly the same form in which they appear in the 3DS DOM. Returns a numpy.array of points, one per row, and a numpy.array of the corresponding normals. The points are returned as a list of consecutive triangles; the first three rows make up the first triangle, the second three rows make up the second triangle, and so on. To calculate the normal of a given vertex on a given face, this function averages the normal vector for all faces which have share that vertex, and a smoothing group. The normals being averaged are weighted by the angle subtended. """ # prepare to calculate normals. define some arrays m = len(facearray) rnorms = numpy.zeros((m*3,3),_calc_precision_type) fnorms = numpy.zeros((m*3,3),_calc_precision_type) points = pointarray[facearray.ravel()] exarray = numpy.zeros(3*m,numpy.uint32) if smarray is not None: exarray[0::3] = exarray[1::3] = exarray[2::3] = smarray # weed out degenerate triangles first # unlike cross-product, angle subtended blows up on degeneracy A = numpy.asarray(pointarray[facearray[:,0]],_calc_precision_type) B = numpy.asarray(pointarray[facearray[:,1]],_calc_precision_type) C = numpy.asarray(pointarray[facearray[:,2]],_calc_precision_type) a = C - B b = A - C c = B - A p = numpy.zeros((len(facearray),3),_calc_precision_type) p[:,0] = c[:,2]*b[:,1]-c[:,1]*b[:,2] p[:,1] = c[:,0]*b[:,2]-c[:,2]*b[:,0] p[:,2] = c[:,1]*b[:,0]-c[:,0]*b[:,1] aa = numpy.sum(a*a,axis=1) bb = numpy.sum(b*b,axis=1) cc = numpy.sum(c*c,axis=1) pp = numpy.sum(p*p,axis=1) ndg = numpy.nonzero(numpy.logical_and.reduce((aa,bb,cc,pp)))[0] # calculate scaled normals (according to angle subtended) p = p[ndg] la = numpy.sqrt(aa[ndg]) lb = numpy.sqrt(bb[ndg]) lc = numpy.sqrt(cc[ndg]) lp = numpy.sqrt(pp[ndg]) sinA = numpy.clip(lp/lb/lc,-1.0,1.0) sinB = numpy.clip(lp/la/lc,-1.0,1.0) sinC = numpy.clip(lp/la/lb,-1.0,1.0) sinA2 = sinA*sinA sinB2 = sinB*sinB sinC2 = sinC*sinC angA = numpy.arcsin(sinA) angB = numpy.arcsin(sinB) angC = numpy.arcsin(sinC) angA = numpy.where(sinA2 > sinB2 + sinC2, numpy.pi - angA, angA) angB = numpy.where(sinB2 > sinA2 + sinC2, numpy.pi - angB, angB) angC = numpy.where(sinC2 > sinA2 + sinB2, numpy.pi - angC, angC) rnorms[0::3][ndg] = p*(angA/lp)[:,numpy.newaxis] rnorms[1::3][ndg] = p*(angB/lp)[:,numpy.newaxis] rnorms[2::3][ndg] = p*(angC/lp)[:,numpy.newaxis] # normalize vectors according to passed in smoothing group lex = numpy.lexsort(numpy.transpose(points)) brs = numpy.nonzero( numpy.any(points[lex[1:],:]-points[lex[:-1],:],axis=1))[0]+1 lslice = numpy.empty((len(brs)+1,),numpy.int) lslice[0] = 0 lslice[1:] = brs rslice = numpy.empty((len(brs)+1,),numpy.int) rslice[:-1] = brs rslice[-1] = 3*m for i in xrange(len(brs)+1): rgroup = lex[lslice[i]:rslice[i]] xgroup = exarray[rgroup] normpat = numpy.logical_or( numpy.bitwise_and.outer(xgroup,xgroup), numpy.eye(len(xgroup))) fnorms[rgroup,:] = numpy.dot(normpat,rnorms[rgroup,:]) q = numpy.sum(fnorms*fnorms,axis=1) qnz = numpy.nonzero(q)[0] lq = 1.0 / numpy.sqrt(q[qnz]) fnt = numpy.transpose(fnorms) fnt[:,qnz] *= lq # we're done return points, numpy.asarray(fnorms,numpy.float32)
[ "def", "calculate_normals_by_angle_subtended", "(", "pointarray", ",", "facearray", ",", "smarray", ")", ":", "# prepare to calculate normals. define some arrays", "m", "=", "len", "(", "facearray", ")", "rnorms", "=", "numpy", ".", "zeros", "(", "(", "m", "*", "3...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/Dice3DS/util.py#L175-L276
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchStructure.py
python
makeStructure
(baseobj=None,length=None,width=None,height=None,name="Structure")
return obj
makeStructure([obj],[length],[width],[height],[swap]): creates a structure element based on the given profile object and the given extrusion height. If no base object is given, you can also specify length and width for a cubic object.
makeStructure([obj],[length],[width],[height],[swap]): creates a structure element based on the given profile object and the given extrusion height. If no base object is given, you can also specify length and width for a cubic object.
[ "makeStructure", "(", "[", "obj", "]", "[", "length", "]", "[", "width", "]", "[", "height", "]", "[", "swap", "]", ")", ":", "creates", "a", "structure", "element", "based", "on", "the", "given", "profile", "object", "and", "the", "given", "extrusion"...
def makeStructure(baseobj=None,length=None,width=None,height=None,name="Structure"): '''makeStructure([obj],[length],[width],[height],[swap]): creates a structure element based on the given profile object and the given extrusion height. If no base object is given, you can also specify length and width for a cubic object.''' if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch") obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Structure") obj.Label = translate("Arch","Structure") _Structure(obj) if FreeCAD.GuiUp: _ViewProviderStructure(obj.ViewObject) if baseobj: obj.Base = baseobj if FreeCAD.GuiUp: obj.Base.ViewObject.hide() if width: obj.Width = width else: obj.Width = p.GetFloat("StructureWidth",100) if height: obj.Height = height else: if not length: obj.Height = p.GetFloat("StructureHeight",1000) if length: obj.Length = length else: if not baseobj: # don't set the length if we have a base object, otherwise the length X height calc # gets wrong obj.Length = p.GetFloat("StructureLength",100) if baseobj: w = 0 h = 0 if hasattr(baseobj,"Width") and hasattr(baseobj,"Height"): w = baseobj.Width.Value h = baseobj.Height.Value elif hasattr(baseobj,"Length") and hasattr(baseobj,"Width"): w = baseobj.Length.Value h = baseobj.Width.Value elif hasattr(baseobj,"Length") and hasattr(baseobj,"Height"): w = baseobj.Length.Value h = baseobj.Height.Value if w and h: if length and not height: obj.Width = w obj.Height = h elif height and not length: obj.Width = w obj.Length = h if not height and not length: obj.IfcType = "Undefined" elif obj.Length > obj.Height: obj.IfcType = "Beam" obj.Label = translate("Arch","Beam") elif obj.Height > obj.Length: obj.IfcType = "Column" obj.Label = translate("Arch","Column") return obj
[ "def", "makeStructure", "(", "baseobj", "=", "None", ",", "length", "=", "None", ",", "width", "=", "None", ",", "height", "=", "None", ",", "name", "=", "\"Structure\"", ")", ":", "if", "not", "FreeCAD", ".", "ActiveDocument", ":", "FreeCAD", ".", "Co...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchStructure.py#L64-L128
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/modes/basemode.py
python
BaseMode.cut_selection_to_clipboard
(self, e)
Copy the text in the region to the windows clipboard.
Copy the text in the region to the windows clipboard.
[ "Copy", "the", "text", "in", "the", "region", "to", "the", "windows", "clipboard", "." ]
def cut_selection_to_clipboard(self, e): # () '''Copy the text in the region to the windows clipboard.''' self.l_buffer.cut_selection_to_clipboard()
[ "def", "cut_selection_to_clipboard", "(", "self", ",", "e", ")", ":", "# ()", "self", ".", "l_buffer", ".", "cut_selection_to_clipboard", "(", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/modes/basemode.py#L429-L431
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/packages/six.py
python
add_move
(move)
Add an item to six.moves.
Add an item to six.moves.
[ "Add", "an", "item", "to", "six", ".", "moves", "." ]
def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
[ "def", "add_move", "(", "move", ")", ":", "setattr", "(", "_MovedItems", ",", "move", ".", "name", ",", "move", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/packages/six.py#L516-L518
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/applesingle.py
python
decode
(infile, outpath, resonly=False, verbose=False)
decode(infile, outpath [, resonly=False, verbose=False]) Creates a decoded file from an AppleSingle encoded file. If resonly is True, then it will create a regular file at outpath containing only the resource fork from infile. Otherwise it will create an AppleDouble file at outpath with the data and resource forks from infile. On platforms without the MacOS module, it will create inpath and inpath+'.rsrc' with the data and resource forks respectively.
decode(infile, outpath [, resonly=False, verbose=False])
[ "decode", "(", "infile", "outpath", "[", "resonly", "=", "False", "verbose", "=", "False", "]", ")" ]
def decode(infile, outpath, resonly=False, verbose=False): """decode(infile, outpath [, resonly=False, verbose=False]) Creates a decoded file from an AppleSingle encoded file. If resonly is True, then it will create a regular file at outpath containing only the resource fork from infile. Otherwise it will create an AppleDouble file at outpath with the data and resource forks from infile. On platforms without the MacOS module, it will create inpath and inpath+'.rsrc' with the data and resource forks respectively. """ if not hasattr(infile, 'read'): if isinstance(infile, Carbon.File.Alias): infile = infile.ResolveAlias()[0] if hasattr(Carbon.File, "FSSpec"): if isinstance(infile, (Carbon.File.FSSpec, Carbon.File.FSRef)): infile = infile.as_pathname() else: if isinstance(infile, Carbon.File.FSRef): infile = infile.as_pathname() infile = open(infile, 'rb') asfile = AppleSingle(infile, verbose=verbose) asfile.tofile(outpath, resonly=resonly)
[ "def", "decode", "(", "infile", ",", "outpath", ",", "resonly", "=", "False", ",", "verbose", "=", "False", ")", ":", "if", "not", "hasattr", "(", "infile", ",", "'read'", ")", ":", "if", "isinstance", "(", "infile", ",", "Carbon", ".", "File", ".", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/applesingle.py#L107-L132
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/matplotlib-inline/matplotlib_inline/config.py
python
pil_available
()
return out
Test if PIL/Pillow is available
Test if PIL/Pillow is available
[ "Test", "if", "PIL", "/", "Pillow", "is", "available" ]
def pil_available(): """Test if PIL/Pillow is available""" out = False try: from PIL import Image # noqa out = True except ImportError: pass return out
[ "def", "pil_available", "(", ")", ":", "out", "=", "False", "try", ":", "from", "PIL", "import", "Image", "# noqa", "out", "=", "True", "except", "ImportError", ":", "pass", "return", "out" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/matplotlib-inline/matplotlib_inline/config.py#L16-L24
apache/kudu
90895ce76590f10730ad7aac3613b69d89ff5422
python/kudu/util.py
python
from_unixtime_micros
(unixtime_micros)
Convert the input unixtime_micros value to a datetime in UTC. Parameters ---------- unixtime_micros : int Number of microseconds since the unix epoch. Returns ------- timestamp : datetime.datetime in UTC
Convert the input unixtime_micros value to a datetime in UTC.
[ "Convert", "the", "input", "unixtime_micros", "value", "to", "a", "datetime", "in", "UTC", "." ]
def from_unixtime_micros(unixtime_micros): """ Convert the input unixtime_micros value to a datetime in UTC. Parameters ---------- unixtime_micros : int Number of microseconds since the unix epoch. Returns ------- timestamp : datetime.datetime in UTC """ if isinstance(unixtime_micros, int): return _epoch() + datetime.timedelta(microseconds=unixtime_micros) else: raise ValueError("Invalid unixtime_micros value." + "You must provide an integer value.")
[ "def", "from_unixtime_micros", "(", "unixtime_micros", ")", ":", "if", "isinstance", "(", "unixtime_micros", ",", "int", ")", ":", "return", "_epoch", "(", ")", "+", "datetime", ".", "timedelta", "(", "microseconds", "=", "unixtime_micros", ")", "else", ":", ...
https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/python/kudu/util.py#L87-L104
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/plugin.py
python
PluginConfigObject.GetBitmap
(self)
return wx.NullBitmap
Get the 32x32 bitmap to show in the config dialog @return: wx.Bitmap @note: Optional if not implemented default icon will be used
Get the 32x32 bitmap to show in the config dialog @return: wx.Bitmap @note: Optional if not implemented default icon will be used
[ "Get", "the", "32x32", "bitmap", "to", "show", "in", "the", "config", "dialog", "@return", ":", "wx", ".", "Bitmap", "@note", ":", "Optional", "if", "not", "implemented", "default", "icon", "will", "be", "used" ]
def GetBitmap(self): """Get the 32x32 bitmap to show in the config dialog @return: wx.Bitmap @note: Optional if not implemented default icon will be used """ return wx.NullBitmap
[ "def", "GetBitmap", "(", "self", ")", ":", "return", "wx", ".", "NullBitmap" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/plugin.py#L254-L260
wujixiu/helmet-detection
8eff5c59ddfba5a29e0b76aeb48babcb49246178
hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py
python
FindPreviousMatchingAngleBracket
(clean_lines, linenum, init_prefix)
return False
Find the corresponding < that started a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_prefix: Part of the current line before the initial >. Returns: True if a matching bracket exists.
Find the corresponding < that started a template.
[ "Find", "the", "corresponding", "<", "that", "started", "a", "template", "." ]
def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix): """Find the corresponding < that started a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_prefix: Part of the current line before the initial >. Returns: True if a matching bracket exists. """ line = init_prefix nesting_stack = ['>'] while True: # Find the previous operator match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line) if match: # Found an operator, update nesting stack operator = match.group(2) line = match.group(1) if nesting_stack[-1] == '>': # Expecting opening angle bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator == '<': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma before a bracket, this is most likely a # template argument. The opening angle bracket is probably # there if we look for it, so just return early here. return True else: # Got some other operator. return False else: # Expecting opening parenthesis or opening bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator in ('(', '['): nesting_stack.pop() else: # Scan the previous line linenum -= 1 if linenum < 0: break line = clean_lines.elided[linenum] # Exhausted all earlier lines and still no matching angle bracket. return False
[ "def", "FindPreviousMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "init_prefix", ")", ":", "line", "=", "init_prefix", "nesting_stack", "=", "[", "'>'", "]", "while", "True", ":", "# Find the previous operator", "match", "=", "Search", "(", "r'^(...
https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py#L2590-L2644
xlgames-inc/XLE
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
Foreign/FreeType/src/tools/docmaker/content.py
python
ContentProcessor.add_markup
( self )
Add a new markup section.
Add a new markup section.
[ "Add", "a", "new", "markup", "section", "." ]
def add_markup( self ): """Add a new markup section.""" if self.markup and self.markup_lines: # get rid of last line of markup if it's empty marks = self.markup_lines if len( marks ) > 0 and not string.strip( marks[-1] ): self.markup_lines = marks[:-1] m = DocMarkup( self.markup, self.markup_lines ) self.markups.append( m ) self.markup = None self.markup_lines = []
[ "def", "add_markup", "(", "self", ")", ":", "if", "self", ".", "markup", "and", "self", ".", "markup_lines", ":", "# get rid of last line of markup if it's empty", "marks", "=", "self", ".", "markup_lines", "if", "len", "(", "marks", ")", ">", "0", "and", "n...
https://github.com/xlgames-inc/XLE/blob/cdd8682367d9e9fdbdda9f79d72bb5b1499cec46/Foreign/FreeType/src/tools/docmaker/content.py#L415-L429
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBThreadPlan.SetPlanComplete
(self, success)
return _lldb.SBThreadPlan_SetPlanComplete(self, success)
SetPlanComplete(SBThreadPlan self, bool success)
SetPlanComplete(SBThreadPlan self, bool success)
[ "SetPlanComplete", "(", "SBThreadPlan", "self", "bool", "success", ")" ]
def SetPlanComplete(self, success): """SetPlanComplete(SBThreadPlan self, bool success)""" return _lldb.SBThreadPlan_SetPlanComplete(self, success)
[ "def", "SetPlanComplete", "(", "self", ",", "success", ")", ":", "return", "_lldb", ".", "SBThreadPlan_SetPlanComplete", "(", "self", ",", "success", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L12162-L12164
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/mantid/simpleapi.py
python
_get_function_spec
(func)
return calltip
Get the python function signature for the given function object :param func: A Python function object
Get the python function signature for the given function object
[ "Get", "the", "python", "function", "signature", "for", "the", "given", "function", "object" ]
def _get_function_spec(func): """Get the python function signature for the given function object :param func: A Python function object """ import inspect try: argspec = inspect.getfullargspec(func) except TypeError: return '' # Algorithm functions have varargs set not args args = argspec[0] if args: # For methods strip the self argument if hasattr(func, 'im_func'): args = args[1:] defs = argspec[3] elif argspec[1] is not None: # Get from varargs/keywords arg_str = argspec[1].strip().lstrip('\b') defs = [] # Keyword args kwargs = argspec[2] if kwargs is not None: kwargs = kwargs.strip().lstrip('\b\b') if kwargs == 'kwargs': kwargs = '**' + kwargs + '=None' arg_str += ',%s' % kwargs # Any default argument appears in the string # on the rhs of an equal for arg in arg_str.split(','): arg = arg.strip() if '=' in arg: arg_token = arg.split('=') args.append(arg_token[0]) defs.append(arg_token[1]) else: args.append(arg) if len(defs) == 0: defs = None else: return '' if defs is None: calltip = ','.join(args) calltip = '(' + calltip + ')' else: # The defaults list contains the default values for the last n arguments diff = len(args) - len(defs) calltip = '' for index in range(len(args) - 1, -1, -1): def_index = index - diff if def_index >= 0: calltip = '[' + args[index] + '],' + calltip else: calltip = args[index] + "," + calltip calltip = '(' + calltip.rstrip(',') + ')' return calltip
[ "def", "_get_function_spec", "(", "func", ")", ":", "import", "inspect", "try", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "except", "TypeError", ":", "return", "''", "# Algorithm functions have varargs set not args", "args", "=", "ar...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/simpleapi.py#L570-L627
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/python/op_hint.py
python
_find_all_hints_in_nodes
(nodes)
return func_calls
Look at the all the input nodes and return a list of LiteFuncCall objs. Args: nodes: A TensorFlow graph_def to look for LiteFuncCalls. Returns: a list of `LifeFuncCall` objects in the form
Look at the all the input nodes and return a list of LiteFuncCall objs.
[ "Look", "at", "the", "all", "the", "input", "nodes", "and", "return", "a", "list", "of", "LiteFuncCall", "objs", "." ]
def _find_all_hints_in_nodes(nodes): """Look at the all the input nodes and return a list of LiteFuncCall objs. Args: nodes: A TensorFlow graph_def to look for LiteFuncCalls. Returns: a list of `LifeFuncCall` objects in the form """ func_calls = _collections.defaultdict(_LiteFuncCall) for node in nodes: attr = node.attr # This is an op hint if it has a FUNCTION_UUID_ATTR, otherwise skip if (OpHint.FUNCTION_UUID_ATTR not in attr or not attr[OpHint.FUNCTION_UUID_ATTR].s): continue uuid = attr[OpHint.FUNCTION_UUID_ATTR].s # Start building function call_def = func_calls[uuid] call_def.uuid = uuid call_def.function_name = attr[OpHint.FUNCTION_NAME_ATTR].s call_def.level = attr[OpHint.FUNCTION_LEVEL_ATTR].i # Get sorting and aggregation information sort = (attr[OpHint.FUNCTION_SORT_INDEX_ATTR].i if OpHint.FUNCTION_SORT_INDEX_ATTR in attr else None) if sort == -1: sort = None aggregation = None if OpHint.FUNCTION_AGGREGATE_ATTR in attr: aggregation = _compat.as_text(attr[OpHint.FUNCTION_AGGREGATE_ATTR].s) if OpHint.CHILDREN_INPUTS_MAPPINGS in attr: call_def.children_inputs_mappings = _json.loads( _compat.as_text(attr[OpHint.CHILDREN_INPUTS_MAPPINGS].s)) # Add the input or output def put_operand(stuff, index, sort, operand, aggregation): """Add a given index into the function structure.""" if sort is None: stuff[index] = _LiteSingleOperand(operand) else: if index not in stuff: stuff[index] = _LiteAggregateOperand(aggregation) stuff[index].add(sort, operand) if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr: put_operand(call_def.inputs, attr[OpHint.FUNCTION_INPUT_INDEX_ATTR].i, sort, node, aggregation) if OpHint.FUNCTION_OUTPUT_INDEX_ATTR in attr: put_operand(call_def.outputs, attr[OpHint.FUNCTION_OUTPUT_INDEX_ATTR].i, sort, node, aggregation) # Remember attributes for a in attr: if a.startswith("_tflite_attr_"): call_def.params[a.replace("_tflite_attr_,", "")] = attr[a].tensor return func_calls
[ "def", "_find_all_hints_in_nodes", "(", "nodes", ")", ":", "func_calls", "=", "_collections", ".", "defaultdict", "(", "_LiteFuncCall", ")", "for", "node", "in", "nodes", ":", "attr", "=", "node", ".", "attr", "# This is an op hint if it has a FUNCTION_UUID_ATTR, othe...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/python/op_hint.py#L723-L783
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
com/win32com/server/register.py
python
_set_string
(path, value, base=win32con.HKEY_CLASSES_ROOT)
Set a string value in the registry.
Set a string value in the registry.
[ "Set", "a", "string", "value", "in", "the", "registry", "." ]
def _set_string(path, value, base=win32con.HKEY_CLASSES_ROOT): "Set a string value in the registry." win32api.RegSetValue(base, path, win32con.REG_SZ, value)
[ "def", "_set_string", "(", "path", ",", "value", ",", "base", "=", "win32con", ".", "HKEY_CLASSES_ROOT", ")", ":", "win32api", ".", "RegSetValue", "(", "base", ",", "path", ",", "win32con", ".", "REG_SZ", ",", "value", ")" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32com/server/register.py#L28-L31
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/grappler/item.py
python
Item.__init__
(self, metagraph, ignore_colocation=True, ignore_user_placement=False)
Creates an Item. Args: metagraph: a TensorFlow metagraph. ignore_colocation: if set, the tool will ignore all the colocation constraints generated by TensorFlow. ignore_user_placement: if set, all the placement annotations annotated in the metagraph will be ignored. Raises: ValueError: the metagraph is incomplete or invalid.
Creates an Item.
[ "Creates", "an", "Item", "." ]
def __init__(self, metagraph, ignore_colocation=True, ignore_user_placement=False): """Creates an Item. Args: metagraph: a TensorFlow metagraph. ignore_colocation: if set, the tool will ignore all the colocation constraints generated by TensorFlow. ignore_user_placement: if set, all the placement annotations annotated in the metagraph will be ignored. Raises: ValueError: the metagraph is incomplete or invalid. """ self._metagraph = metagraph self._item_graph = meta_graph_pb2.MetaGraphDef() self._item_graph.CopyFrom(metagraph) self._ignore_colocation = ignore_colocation self._ignore_user_placement = ignore_user_placement self._tf_item = None self._BuildTFItem()
[ "def", "__init__", "(", "self", ",", "metagraph", ",", "ignore_colocation", "=", "True", ",", "ignore_user_placement", "=", "False", ")", ":", "self", ".", "_metagraph", "=", "metagraph", "self", ".", "_item_graph", "=", "meta_graph_pb2", ".", "MetaGraphDef", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/grappler/item.py#L25-L46
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/distributions/beta.py
python
Beta.concentration1
(self)
return self._concentration1
Concentration parameter associated with a `1` outcome.
Concentration parameter associated with a `1` outcome.
[ "Concentration", "parameter", "associated", "with", "a", "1", "outcome", "." ]
def concentration1(self): """Concentration parameter associated with a `1` outcome.""" return self._concentration1
[ "def", "concentration1", "(", "self", ")", ":", "return", "self", ".", "_concentration1" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/distributions/beta.py#L180-L182
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/linalg/_interpolative_backend.py
python
idz_frm
(n, w, x)
return _id.idz_frm(n, w, x)
Transform complex vector via a composition of Rokhlin's random transform, random subselection, and an FFT. In contrast to :func:`idz_sfrm`, this routine works best when the length of the transformed vector is the power-of-two integer output by :func:`idz_frmi`, or when the length is not specified but instead determined a posteriori from the output. The returned transformed vector is randomly permuted. :param n: Greatest power-of-two integer satisfying `n <= x.size` as obtained from :func:`idz_frmi`; `n` is also the length of the output vector. :type n: int :param w: Initialization array constructed by :func:`idz_frmi`. :type w: :class:`numpy.ndarray` :param x: Vector to be transformed. :type x: :class:`numpy.ndarray` :return: Transformed vector. :rtype: :class:`numpy.ndarray`
Transform complex vector via a composition of Rokhlin's random transform, random subselection, and an FFT.
[ "Transform", "complex", "vector", "via", "a", "composition", "of", "Rokhlin", "s", "random", "transform", "random", "subselection", "and", "an", "FFT", "." ]
def idz_frm(n, w, x): """ Transform complex vector via a composition of Rokhlin's random transform, random subselection, and an FFT. In contrast to :func:`idz_sfrm`, this routine works best when the length of the transformed vector is the power-of-two integer output by :func:`idz_frmi`, or when the length is not specified but instead determined a posteriori from the output. The returned transformed vector is randomly permuted. :param n: Greatest power-of-two integer satisfying `n <= x.size` as obtained from :func:`idz_frmi`; `n` is also the length of the output vector. :type n: int :param w: Initialization array constructed by :func:`idz_frmi`. :type w: :class:`numpy.ndarray` :param x: Vector to be transformed. :type x: :class:`numpy.ndarray` :return: Transformed vector. :rtype: :class:`numpy.ndarray` """ return _id.idz_frm(n, w, x)
[ "def", "idz_frm", "(", "n", ",", "w", ",", "x", ")", ":", "return", "_id", ".", "idz_frm", "(", "n", ",", "w", ",", "x", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/linalg/_interpolative_backend.py#L878-L904
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/interpolate/interpolate.py
python
spleval
(xck, xnew, deriv=0)
return res
Evaluate a fixed spline represented by the given tuple at the new x-values The `xj` values are the interior knot points. The approximation region is `xj[0]` to `xj[-1]`. If N+1 is the length of `xj`, then `cvals` should have length N+k where `k` is the order of the spline. Parameters ---------- (xj, cvals, k) : tuple Parameters that define the fixed spline xj : array_like Interior knot points cvals : array_like Curvature k : int Order of the spline xnew : array_like Locations to calculate spline deriv : int Deriv Returns ------- spleval : ndarray If `cvals` represents more than one curve (`cvals.ndim` > 1) and/or `xnew` is N-d, then the result is `xnew.shape` + `cvals.shape[1:]` providing the interpolation of multiple curves. Notes ----- Internally, an additional `k`-1 knot points are added on either side of the spline.
Evaluate a fixed spline represented by the given tuple at the new x-values
[ "Evaluate", "a", "fixed", "spline", "represented", "by", "the", "given", "tuple", "at", "the", "new", "x", "-", "values" ]
def spleval(xck, xnew, deriv=0): """ Evaluate a fixed spline represented by the given tuple at the new x-values The `xj` values are the interior knot points. The approximation region is `xj[0]` to `xj[-1]`. If N+1 is the length of `xj`, then `cvals` should have length N+k where `k` is the order of the spline. Parameters ---------- (xj, cvals, k) : tuple Parameters that define the fixed spline xj : array_like Interior knot points cvals : array_like Curvature k : int Order of the spline xnew : array_like Locations to calculate spline deriv : int Deriv Returns ------- spleval : ndarray If `cvals` represents more than one curve (`cvals.ndim` > 1) and/or `xnew` is N-d, then the result is `xnew.shape` + `cvals.shape[1:]` providing the interpolation of multiple curves. Notes ----- Internally, an additional `k`-1 knot points are added on either side of the spline. """ (xj,cvals,k) = xck oldshape = np.shape(xnew) xx = np.ravel(xnew) sh = cvals.shape[1:] res = np.empty(xx.shape + sh, dtype=cvals.dtype) for index in np.ndindex(*sh): sl = (slice(None),)+index if issubclass(cvals.dtype.type, np.complexfloating): res[sl].real = _fitpack._bspleval(xx,xj,cvals.real[sl],k,deriv) res[sl].imag = _fitpack._bspleval(xx,xj,cvals.imag[sl],k,deriv) else: res[sl] = _fitpack._bspleval(xx,xj,cvals[sl],k,deriv) res.shape = oldshape + sh return res
[ "def", "spleval", "(", "xck", ",", "xnew", ",", "deriv", "=", "0", ")", ":", "(", "xj", ",", "cvals", ",", "k", ")", "=", "xck", "oldshape", "=", "np", ".", "shape", "(", "xnew", ")", "xx", "=", "np", ".", "ravel", "(", "xnew", ")", "sh", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/interpolate/interpolate.py#L2937-L2986
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/serve/publish/publish_manager_helper.py
python
PublishManagerHelper.GetTargetDetails
(self, target_path)
return target_details
gets target details by target path. Args: target_path: target path. Raises: PublishServeException Returns: target details of a target.
gets target details by target path.
[ "gets", "target", "details", "by", "target", "path", "." ]
def GetTargetDetails(self, target_path): """gets target details by target path. Args: target_path: target path. Raises: PublishServeException Returns: target details of a target. """ target_details = {} target_db_details = {} publish_context = {} target_db_details = self._QueryTargetDbDetailsByPath(target_path) if not target_db_details: error_msg = ( "GetTargetDetails: No target details found for target path %s. " "Make sure target path exists." % target_path) raise exceptions.PublishServeException(error_msg) target_details.update({ "targetpath": target_path, "servewms": target_db_details["servewms"], "fusion_host": target_db_details["fusion_host"], "dbname": target_db_details["dbname"], "vhname": target_db_details["vhname"], }) publish_context = self._QueryPublishContextByTargetPath(target_path) if publish_context: target_details.update({"publishcontext": publish_context,}) return target_details
[ "def", "GetTargetDetails", "(", "self", ",", "target_path", ")", ":", "target_details", "=", "{", "}", "target_db_details", "=", "{", "}", "publish_context", "=", "{", "}", "target_db_details", "=", "self", ".", "_QueryTargetDbDetailsByPath", "(", "target_path", ...
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/publish/publish_manager_helper.py#L1591-L1625
ablab/spades
3a754192b88540524ce6fb69eef5ea9273a38465
webvis/pydot.py
python
graph_from_adjacency_matrix
(matrix, node_prefix= u'', directed=False)
return graph
Creates a basic graph out of an adjacency matrix. The matrix has to be a list of rows of values representing an adjacency matrix. The values can be anything: bool, int, float, as long as they can evaluate to True or False.
Creates a basic graph out of an adjacency matrix. The matrix has to be a list of rows of values representing an adjacency matrix. The values can be anything: bool, int, float, as long as they can evaluate to True or False.
[ "Creates", "a", "basic", "graph", "out", "of", "an", "adjacency", "matrix", ".", "The", "matrix", "has", "to", "be", "a", "list", "of", "rows", "of", "values", "representing", "an", "adjacency", "matrix", ".", "The", "values", "can", "be", "anything", ":...
def graph_from_adjacency_matrix(matrix, node_prefix= u'', directed=False): """Creates a basic graph out of an adjacency matrix. The matrix has to be a list of rows of values representing an adjacency matrix. The values can be anything: bool, int, float, as long as they can evaluate to True or False. """ node_orig = 1 if directed: graph = Dot(graph_type='digraph') else: graph = Dot(graph_type='graph') for row in matrix: if not directed: skip = matrix.index(row) r = row[skip:] else: skip = 0 r = row node_dest = skip+1 for e in r: if e: graph.add_edge( Edge( node_prefix + node_orig, node_prefix + node_dest) ) node_dest += 1 node_orig += 1 return graph
[ "def", "graph_from_adjacency_matrix", "(", "matrix", ",", "node_prefix", "=", "u''", ",", "directed", "=", "False", ")", ":", "node_orig", "=", "1", "if", "directed", ":", "graph", "=", "Dot", "(", "graph_type", "=", "'digraph'", ")", "else", ":", "graph",...
https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/webvis/pydot.py#L274-L307
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/jinja2/ext.py
python
InternationalizationExtension._make_node
(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num)
return nodes.Output([node])
Generates a useful node from the data provided.
Generates a useful node from the data provided.
[ "Generates", "a", "useful", "node", "from", "the", "data", "provided", "." ]
def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num): """Generates a useful node from the data provided.""" # no variables referenced? no need to escape for old style # gettext invocations only if there are vars. if not vars_referenced and not self.environment.newstyle_gettext: singular = singular.replace('%%', '%') if plural: plural = plural.replace('%%', '%') # singular only: if plural_expr is None: gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None) # singular and plural else: ngettext = nodes.Name('ngettext', 'load') node = nodes.Call(ngettext, [ nodes.Const(singular), nodes.Const(plural), plural_expr ], [], None, None) # in case newstyle gettext is used, the method is powerful # enough to handle the variable expansion and autoescape # handling itself if self.environment.newstyle_gettext: for key, value in iteritems(variables): # the function adds that later anyways in case num was # called num, so just skip it. if num_called_num and key == 'num': continue node.kwargs.append(nodes.Keyword(key, value)) # otherwise do that here else: # mark the return value as safe if we are in an # environment with autoescaping turned on node = nodes.MarkSafeIfAutoescape(node) if variables: node = nodes.Mod(node, nodes.Dict([ nodes.Pair(nodes.Const(key), value) for key, value in variables.items() ])) return nodes.Output([node])
[ "def", "_make_node", "(", "self", ",", "singular", ",", "plural", ",", "variables", ",", "plural_expr", ",", "vars_referenced", ",", "num_called_num", ")", ":", "# no variables referenced? no need to escape for old style", "# gettext invocations only if there are vars.", "if...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/ext.py#L341-L387
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/dispatch.py
python
HsaUFuncDispatcher.__call__
(self, *args, **kws)
return HsaUFuncMechanism.call(self.functions, args, kws)
*args: numpy arrays **kws: stream -- hsa stream; when defined, asynchronous mode is used. out -- output array. Can be a numpy array or DeviceArrayBase depending on the input arguments. Type must match the input arguments.
*args: numpy arrays **kws: stream -- hsa stream; when defined, asynchronous mode is used. out -- output array. Can be a numpy array or DeviceArrayBase depending on the input arguments. Type must match the input arguments.
[ "*", "args", ":", "numpy", "arrays", "**", "kws", ":", "stream", "--", "hsa", "stream", ";", "when", "defined", "asynchronous", "mode", "is", "used", ".", "out", "--", "output", "array", ".", "Can", "be", "a", "numpy", "array", "or", "DeviceArrayBase", ...
def __call__(self, *args, **kws): """ *args: numpy arrays **kws: stream -- hsa stream; when defined, asynchronous mode is used. out -- output array. Can be a numpy array or DeviceArrayBase depending on the input arguments. Type must match the input arguments. """ return HsaUFuncMechanism.call(self.functions, args, kws)
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kws", ")", ":", "return", "HsaUFuncMechanism", ".", "call", "(", "self", ".", "functions", ",", "args", ",", "kws", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/dispatch.py#L19-L28
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
cd/utils/artifact_repository.py
python
write_libmxnet_meta
(args: argparse.Namespace, destination: str)
Writes a file called libmxnet.meta in the 'destination' folder that contains the libmxnet library information (commit id, type, etc.). :param args: A Namespace object containing the library :param destination: The folder in which to place the libmxnet.meta
Writes a file called libmxnet.meta in the 'destination' folder that contains the libmxnet library information (commit id, type, etc.). :param args: A Namespace object containing the library :param destination: The folder in which to place the libmxnet.meta
[ "Writes", "a", "file", "called", "libmxnet", ".", "meta", "in", "the", "destination", "folder", "that", "contains", "the", "libmxnet", "library", "information", "(", "commit", "id", "type", "etc", ".", ")", ".", ":", "param", "args", ":", "A", "Namespace",...
def write_libmxnet_meta(args: argparse.Namespace, destination: str): """ Writes a file called libmxnet.meta in the 'destination' folder that contains the libmxnet library information (commit id, type, etc.). :param args: A Namespace object containing the library :param destination: The folder in which to place the libmxnet.meta """ with open(os.path.join(destination, 'libmxnet.meta'), 'w') as fp: fp.write(yaml.dump({ "variant": args.variant, "os": args.os, "commit_id": args.git_sha, "dependency_linking": args.libtype, }))
[ "def", "write_libmxnet_meta", "(", "args", ":", "argparse", ".", "Namespace", ",", "destination", ":", "str", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "destination", ",", "'libmxnet.meta'", ")", ",", "'w'", ")", "as", "fp", "...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/cd/utils/artifact_repository.py#L71-L84
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/tools/clang/docs/tools/dump_ast_matchers.py
python
unify_arguments
(args)
return args
Gets rid of anything the user doesn't care about in the argument list.
Gets rid of anything the user doesn't care about in the argument list.
[ "Gets", "rid", "of", "anything", "the", "user", "doesn", "t", "care", "about", "in", "the", "argument", "list", "." ]
def unify_arguments(args): """Gets rid of anything the user doesn't care about in the argument list.""" args = re.sub(r'internal::', r'', args) args = re.sub(r'extern const\s+(.*)&', r'\1 ', args) args = re.sub(r'&', r' ', args) args = re.sub(r'(^|\s)M\d?(\s)', r'\1Matcher<*>\2', args) return args
[ "def", "unify_arguments", "(", "args", ")", ":", "args", "=", "re", ".", "sub", "(", "r'internal::'", ",", "r''", ",", "args", ")", "args", "=", "re", ".", "sub", "(", "r'extern const\\s+(.*)&'", ",", "r'\\1 '", ",", "args", ")", "args", "=", "re", "...
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/docs/tools/dump_ast_matchers.py#L98-L104
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/grit/grit/format/policy_templates/writers/plist_writer.py
python
PListWriter._AddTargets
(self, parent, policy)
Adds the following XML snippet to an XML element: <key>pfm_targets</key> <array> <string>user-managed</string> </array> Args: parent: The parent XML element where the snippet will be added.
Adds the following XML snippet to an XML element: <key>pfm_targets</key> <array> <string>user-managed</string> </array>
[ "Adds", "the", "following", "XML", "snippet", "to", "an", "XML", "element", ":", "<key", ">", "pfm_targets<", "/", "key", ">", "<array", ">", "<string", ">", "user", "-", "managed<", "/", "string", ">", "<", "/", "array", ">" ]
def _AddTargets(self, parent, policy): '''Adds the following XML snippet to an XML element: <key>pfm_targets</key> <array> <string>user-managed</string> </array> Args: parent: The parent XML element where the snippet will be added. ''' array = self._AddKeyValuePair(parent, 'pfm_targets', 'array') if self.CanBeRecommended(policy): self.AddElement(array, 'string', {}, 'user') if self.CanBeMandatory(policy): self.AddElement(array, 'string', {}, 'user-managed')
[ "def", "_AddTargets", "(", "self", ",", "parent", ",", "policy", ")", ":", "array", "=", "self", ".", "_AddKeyValuePair", "(", "parent", ",", "'pfm_targets'", ",", "'array'", ")", "if", "self", ".", "CanBeRecommended", "(", "policy", ")", ":", "self", "....
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/format/policy_templates/writers/plist_writer.py#L70-L84
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-time.py
python
SConsTimer.get_object_counts
(self, file, object_name, index=None)
return result
Returns the counts of the specified object_name.
Returns the counts of the specified object_name.
[ "Returns", "the", "counts", "of", "the", "specified", "object_name", "." ]
def get_object_counts(self, file, object_name, index=None): """ Returns the counts of the specified object_name. """ object_string = ' ' + object_name + '\n' with open(file) as f: lines = f.readlines() line = [l for l in lines if l.endswith(object_string)][0] result = [int(field) for field in line.split()[:4]] if index is not None: result = result[index] return result
[ "def", "get_object_counts", "(", "self", ",", "file", ",", "object_name", ",", "index", "=", "None", ")", ":", "object_string", "=", "' '", "+", "object_name", "+", "'\\n'", "with", "open", "(", "file", ")", "as", "f", ":", "lines", "=", "f", ".", "r...
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-time.py#L686-L697
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py
python
update_dist_caches
(dist_path, fix_zipimporter_caches)
Fix any globally cached `dist_path` related data `dist_path` should be a path of a newly installed egg distribution (zipped or unzipped). sys.path_importer_cache contains finder objects that have been cached when importing data from the original distribution. Any such finders need to be cleared since the replacement distribution might be packaged differently, e.g. a zipped egg distribution might get replaced with an unzipped egg folder or vice versa. Having the old finders cached may then cause Python to attempt loading modules from the replacement distribution using an incorrect loader. zipimport.zipimporter objects are Python loaders charged with importing data packaged inside zip archives. If stale loaders referencing the original distribution, are left behind, they can fail to load modules from the replacement distribution. E.g. if an old zipimport.zipimporter instance is used to load data from a new zipped egg archive, it may cause the operation to attempt to locate the requested data in the wrong location - one indicated by the original distribution's zip archive directory information. Such an operation may then fail outright, e.g. report having read a 'bad local file header', or even worse, it may fail silently & return invalid data. zipimport._zip_directory_cache contains cached zip archive directory information for all existing zipimport.zipimporter instances and all such instances connected to the same archive share the same cached directory information. If asked, and the underlying Python implementation allows it, we can fix all existing zipimport.zipimporter instances instead of having to track them down and remove them one by one, by updating their shared cached zip archive directory information. This, of course, assumes that the replacement distribution is packaged as a zipped egg. If not asked to fix existing zipimport.zipimporter instances, we still do our best to clear any remaining zipimport.zipimporter related cached data that might somehow later get used when attempting to load data from the new distribution and thus cause such load operations to fail. Note that when tracking down such remaining stale data, we can not catch every conceivable usage from here, and we clear only those that we know of and have found to cause problems if left alive. Any remaining caches should be updated by whomever is in charge of maintaining them, i.e. they should be ready to handle us replacing their zip archives with new distributions at runtime.
Fix any globally cached `dist_path` related data
[ "Fix", "any", "globally", "cached", "dist_path", "related", "data" ]
def update_dist_caches(dist_path, fix_zipimporter_caches): """ Fix any globally cached `dist_path` related data `dist_path` should be a path of a newly installed egg distribution (zipped or unzipped). sys.path_importer_cache contains finder objects that have been cached when importing data from the original distribution. Any such finders need to be cleared since the replacement distribution might be packaged differently, e.g. a zipped egg distribution might get replaced with an unzipped egg folder or vice versa. Having the old finders cached may then cause Python to attempt loading modules from the replacement distribution using an incorrect loader. zipimport.zipimporter objects are Python loaders charged with importing data packaged inside zip archives. If stale loaders referencing the original distribution, are left behind, they can fail to load modules from the replacement distribution. E.g. if an old zipimport.zipimporter instance is used to load data from a new zipped egg archive, it may cause the operation to attempt to locate the requested data in the wrong location - one indicated by the original distribution's zip archive directory information. Such an operation may then fail outright, e.g. report having read a 'bad local file header', or even worse, it may fail silently & return invalid data. zipimport._zip_directory_cache contains cached zip archive directory information for all existing zipimport.zipimporter instances and all such instances connected to the same archive share the same cached directory information. If asked, and the underlying Python implementation allows it, we can fix all existing zipimport.zipimporter instances instead of having to track them down and remove them one by one, by updating their shared cached zip archive directory information. This, of course, assumes that the replacement distribution is packaged as a zipped egg. If not asked to fix existing zipimport.zipimporter instances, we still do our best to clear any remaining zipimport.zipimporter related cached data that might somehow later get used when attempting to load data from the new distribution and thus cause such load operations to fail. Note that when tracking down such remaining stale data, we can not catch every conceivable usage from here, and we clear only those that we know of and have found to cause problems if left alive. Any remaining caches should be updated by whomever is in charge of maintaining them, i.e. they should be ready to handle us replacing their zip archives with new distributions at runtime. """ # There are several other known sources of stale zipimport.zipimporter # instances that we do not clear here, but might if ever given a reason to # do so: # * Global setuptools pkg_resources.working_set (a.k.a. 'master working # set') may contain distributions which may in turn contain their # zipimport.zipimporter loaders. # * Several zipimport.zipimporter loaders held by local variables further # up the function call stack when running the setuptools installation. # * Already loaded modules may have their __loader__ attribute set to the # exact loader instance used when importing them. Python 3.4 docs state # that this information is intended mostly for introspection and so is # not expected to cause us problems. normalized_path = normalize_path(dist_path) _uncache(normalized_path, sys.path_importer_cache) if fix_zipimporter_caches: _replace_zip_directory_cache_data(normalized_path) else: # Here, even though we do not want to fix existing and now stale # zipimporter cache information, we still want to remove it. Related to # Python's zip archive directory information cache, we clear each of # its stale entries in two phases: # 1. Clear the entry so attempting to access zip archive information # via any existing stale zipimport.zipimporter instances fails. # 2. Remove the entry from the cache so any newly constructed # zipimport.zipimporter instances do not end up using old stale # zip archive directory information. # This whole stale data removal step does not seem strictly necessary, # but has been left in because it was done before we started replacing # the zip archive directory information cache content if possible, and # there are no relevant unit tests that we can depend on to tell us if # this is really needed. _remove_and_clear_zip_directory_cache_data(normalized_path)
[ "def", "update_dist_caches", "(", "dist_path", ",", "fix_zipimporter_caches", ")", ":", "# There are several other known sources of stale zipimport.zipimporter", "# instances that we do not clear here, but might if ever given a reason to", "# do so:", "# * Global setuptools pkg_resources.worki...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py#L1727-L1806
flexflow/FlexFlow
581fad8ba8d10a16a3102ee2b406b0319586df24
python/flexflow/keras/utils/data_utils.py
python
OrderedEnqueuer._run
(self)
Submits request to the executor and queue the `Future` objects.
Submits request to the executor and queue the `Future` objects.
[ "Submits", "request", "to", "the", "executor", "and", "queue", "the", "Future", "objects", "." ]
def _run(self): """Submits request to the executor and queue the `Future` objects.""" while True: sequence = list(range(len(self.sequence))) self._send_sequence() # Share the initial sequence if self.shuffle: random.shuffle(sequence) with closing(self.executor_fn(_SHARED_SEQUENCES)) as executor: for i in sequence: if self.stop_signal.is_set(): return future = executor.apply_async(get_index, (self.uid, i)) future.idx = i self.queue.put(future, block=True) # Done with the current epoch, waiting for the final batches self._wait_queue() if self.stop_signal.is_set(): # We're done return # Call the internal on epoch end. self.sequence.on_epoch_end() # communicate on_epoch_end to the main thread self.end_of_epoch_signal.set()
[ "def", "_run", "(", "self", ")", ":", "while", "True", ":", "sequence", "=", "list", "(", "range", "(", "len", "(", "self", ".", "sequence", ")", ")", ")", "self", ".", "_send_sequence", "(", ")", "# Share the initial sequence", "if", "self", ".", "shu...
https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/python/flexflow/keras/utils/data_utils.py#L563-L590
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
Wrapping/Python/paraview/selection.py
python
SelectIDs
(IDs=[], FieldType='POINT', ContainingCells=False, Source=None, Modifier=None)
Select attributes by attribute IDs. - IDs - list of IDs of attribute types to select. Defined as (process number, attribute ID) pairs interleaved in a single list. For multiblock datasets, this will select attributes on all blocks of the provided (processor number, attribute ID) pairs - FieldType - type of attribute to select, e.g., 'POINT', 'CELL' - ContainingCells - if True and FieldType is 'POINT', select the cells containing the points corresponding to the given IDs. - Source - If not None, specifies the sources whose elements should be selected by ID. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection should modify the existing selection.
Select attributes by attribute IDs.
[ "Select", "attributes", "by", "attribute", "IDs", "." ]
def SelectIDs(IDs=[], FieldType='POINT', ContainingCells=False, Source=None, Modifier=None): """Select attributes by attribute IDs. - IDs - list of IDs of attribute types to select. Defined as (process number, attribute ID) pairs interleaved in a single list. For multiblock datasets, this will select attributes on all blocks of the provided (processor number, attribute ID) pairs - FieldType - type of attribute to select, e.g., 'POINT', 'CELL' - ContainingCells - if True and FieldType is 'POINT', select the cells containing the points corresponding to the given IDs. - Source - If not None, specifies the sources whose elements should be selected by ID. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection should modify the existing selection. """ _selectIDsHelper('IDSelectionSource', **locals())
[ "def", "SelectIDs", "(", "IDs", "=", "[", "]", ",", "FieldType", "=", "'POINT'", ",", "ContainingCells", "=", "False", ",", "Source", "=", "None", ",", "Modifier", "=", "None", ")", ":", "_selectIDsHelper", "(", "'IDSelectionSource'", ",", "*", "*", "loc...
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/selection.py#L358-L371
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/backends/chrome/tab_list_backend.py
python
TabListBackend.CloseTab
(self, tab_id, timeout=300)
Closes the tab with the given debugger_url. Raises: devtools_http.DevToolsClientConnectionError devtools_client_backend.TabNotFoundError TabUnexpectedResponseException exceptions.TimeoutException
Closes the tab with the given debugger_url.
[ "Closes", "the", "tab", "with", "the", "given", "debugger_url", "." ]
def CloseTab(self, tab_id, timeout=300): """Closes the tab with the given debugger_url. Raises: devtools_http.DevToolsClientConnectionError devtools_client_backend.TabNotFoundError TabUnexpectedResponseException exceptions.TimeoutException """ assert self._browser_backend.supports_tab_control # TODO(dtu): crbug.com/160946, allow closing the last tab on some platforms. # For now, just create a new tab before closing the last tab. if len(self) <= 1: self.New(timeout) response = self._browser_backend.devtools_client.CloseTab(tab_id, timeout) if response != 'Target is closing': raise TabUnexpectedResponseException( app=self._browser_backend.browser, msg='Received response: %s' % response) util.WaitFor(lambda: tab_id not in self.IterContextIds(), timeout=5)
[ "def", "CloseTab", "(", "self", ",", "tab_id", ",", "timeout", "=", "300", ")", ":", "assert", "self", ".", "_browser_backend", ".", "supports_tab_control", "# TODO(dtu): crbug.com/160946, allow closing the last tab on some platforms.", "# For now, just create a new tab before ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/backends/chrome/tab_list_backend.py#L44-L66
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/util/tf_inspect.py
python
isfunction
(object)
return _inspect.isfunction(tf_decorator.unwrap(object)[1])
TFDecorator-aware replacement for inspect.isfunction.
TFDecorator-aware replacement for inspect.isfunction.
[ "TFDecorator", "-", "aware", "replacement", "for", "inspect", ".", "isfunction", "." ]
def isfunction(object): # pylint: disable=redefined-builtin """TFDecorator-aware replacement for inspect.isfunction.""" return _inspect.isfunction(tf_decorator.unwrap(object)[1])
[ "def", "isfunction", "(", "object", ")", ":", "# pylint: disable=redefined-builtin", "return", "_inspect", ".", "isfunction", "(", "tf_decorator", ".", "unwrap", "(", "object", ")", "[", "1", "]", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/util/tf_inspect.py#L379-L381
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/nn/qat/modules/conv.py
python
QuantizedConv2d.from_float
(cls, mod, qconfig)
return conv
Create a qat module from a float module. Args: mod: A float module of type torch.nn.Conv2d. qconfig (pytorch_nndct.quantization.quant_aware_training.QConfig): A qconfig object that saves the quantizers for the module.
Create a qat module from a float module.
[ "Create", "a", "qat", "module", "from", "a", "float", "module", "." ]
def from_float(cls, mod, qconfig): """Create a qat module from a float module. Args: mod: A float module of type torch.nn.Conv2d. qconfig (pytorch_nndct.quantization.quant_aware_training.QConfig): A qconfig object that saves the quantizers for the module. """ assert qconfig, 'qconfig must be provided for quantized module' assert type(mod) == cls._FLOAT_MODULE, ' qat.' + cls.__name__ + \ '.from_float only works for ' + cls._FLOAT_MODULE.__name__ conv = cls( mod.in_channels, mod.out_channels, mod.kernel_size, stride=mod.stride, padding=mod.padding, dilation=mod.dilation, groups=mod.groups, bias=mod.bias is not None, padding_mode=mod.padding_mode, qconfig=qconfig) conv.weight = mod.weight conv.bias = mod.bias return conv
[ "def", "from_float", "(", "cls", ",", "mod", ",", "qconfig", ")", ":", "assert", "qconfig", ",", "'qconfig must be provided for quantized module'", "assert", "type", "(", "mod", ")", "==", "cls", ".", "_FLOAT_MODULE", ",", "' qat.'", "+", "cls", ".", "__name__...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/nn/qat/modules/conv.py#L84-L110
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/fromnumeric.py
python
put
(a, ind, v, mode='raise')
return put(ind, v, mode=mode)
Replaces specified elements of an array with given values. The indexing works on the flattened target array. `put` is roughly equivalent to: :: a.flat[ind] = v Parameters ---------- a : ndarray Target array. ind : array_like Target indices, interpreted as integers. v : array_like Values to place in `a` at target indices. If `v` is shorter than `ind` it will be repeated as necessary. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices will behave. * 'raise' -- raise an error (default) * 'wrap' -- wrap around * 'clip' -- clip to the range 'clip' mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers. In 'raise' mode, if an exception occurs the target array may still be modified. See Also -------- putmask, place put_along_axis : Put elements by matching the array and the index arrays Examples -------- >>> a = np.arange(5) >>> np.put(a, [0, 2], [-44, -55]) >>> a array([-44, 1, -55, 3, 4]) >>> a = np.arange(5) >>> np.put(a, 22, -5, mode='clip') >>> a array([ 0, 1, 2, 3, -5])
Replaces specified elements of an array with given values.
[ "Replaces", "specified", "elements", "of", "an", "array", "with", "given", "values", "." ]
def put(a, ind, v, mode='raise'): """ Replaces specified elements of an array with given values. The indexing works on the flattened target array. `put` is roughly equivalent to: :: a.flat[ind] = v Parameters ---------- a : ndarray Target array. ind : array_like Target indices, interpreted as integers. v : array_like Values to place in `a` at target indices. If `v` is shorter than `ind` it will be repeated as necessary. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices will behave. * 'raise' -- raise an error (default) * 'wrap' -- wrap around * 'clip' -- clip to the range 'clip' mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers. In 'raise' mode, if an exception occurs the target array may still be modified. See Also -------- putmask, place put_along_axis : Put elements by matching the array and the index arrays Examples -------- >>> a = np.arange(5) >>> np.put(a, [0, 2], [-44, -55]) >>> a array([-44, 1, -55, 3, 4]) >>> a = np.arange(5) >>> np.put(a, 22, -5, mode='clip') >>> a array([ 0, 1, 2, 3, -5]) """ try: put = a.put except AttributeError: raise TypeError("argument 1 must be numpy.ndarray, " "not {name}".format(name=type(a).__name__)) return put(ind, v, mode=mode)
[ "def", "put", "(", "a", ",", "ind", ",", "v", ",", "mode", "=", "'raise'", ")", ":", "try", ":", "put", "=", "a", ".", "put", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"argument 1 must be numpy.ndarray, \"", "\"not {name}\"", ".", "form...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/fromnumeric.py#L490-L546
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
armorycolors.py
python
tweakColor
(qcolor, op, tweaks)
return QColor(r,g,b)
We want to be able to take existing colors (from the palette) and tweak them. This may involved "inverting" them, or multiplying or adding scalars to the various channels.
We want to be able to take existing colors (from the palette) and tweak them. This may involved "inverting" them, or multiplying or adding scalars to the various channels.
[ "We", "want", "to", "be", "able", "to", "take", "existing", "colors", "(", "from", "the", "palette", ")", "and", "tweak", "them", ".", "This", "may", "involved", "inverting", "them", "or", "multiplying", "or", "adding", "scalars", "to", "the", "various", ...
def tweakColor(qcolor, op, tweaks): """ We want to be able to take existing colors (from the palette) and tweak them. This may involved "inverting" them, or multiplying or adding scalars to the various channels. """ if len(tweaks) != 3: raise InvalidColor, 'Must supply list or tuple of RGB tweaks' # Determine what the "tweaks" list/tuple means tweakChannel = lambda x,mod: x # identity if op.lower() in ('times', '*'): def tweakChannel(color, mod): if mod < 0: color = (255 - color) mod *= -1 returnColor = color * mod returnColor = min(returnColor, 255) return int(max(returnColor, 0)) elif op.lower() in ('plus', '+'): def tweakChannel(color, mod): returnColor = color + mod returnColor = min(returnColor, 255) return int(max(returnColor, 0)) else: raise InvalidColor, 'Invalid color operation: "%s"' % op r,g,b = qcolor.red(), qcolor.green(), qcolor.blue() r = tweakChannel(r, tweaks[0]) g = tweakChannel(g, tweaks[1]) b = tweakChannel(b, tweaks[2]) return QColor(r,g,b)
[ "def", "tweakColor", "(", "qcolor", ",", "op", ",", "tweaks", ")", ":", "if", "len", "(", "tweaks", ")", "!=", "3", ":", "raise", "InvalidColor", ",", "'Must supply list or tuple of RGB tweaks'", "# Determine what the \"tweaks\" list/tuple means", "tweakChannel", "=",...
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armorycolors.py#L42-L73
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/xml/sax/handler.py
python
ContentHandler.ignorableWhitespace
(self, whitespace)
Receive notification of ignorable whitespace in element content. Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models. SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information.
Receive notification of ignorable whitespace in element content.
[ "Receive", "notification", "of", "ignorable", "whitespace", "in", "element", "content", "." ]
def ignorableWhitespace(self, whitespace): """Receive notification of ignorable whitespace in element content. Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models. SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information."""
[ "def", "ignorableWhitespace", "(", "self", ",", "whitespace", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/sax/handler.py#L168-L180
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exodus2.in.py
python
exodus.get_side_set
(self, id)
return (side_set_elem_list, side_set_side_list)
ss_elems, ss_sides = exo.get_side_set(side_set_id) -> get the lists of element and side indices in a side set; the two lists correspond: together, ss_elems[i] and ss_sides[i] define the face of an element input value(s): <int> side_set_id side set *ID* (not *INDEX*) return value(s): if array_type == 'ctype': <list<int>> ss_elems <list<int>> ss_sides if array_type == 'numpy': <np_array<int>> ss_elems <np_array<int>> ss_sides
ss_elems, ss_sides = exo.get_side_set(side_set_id)
[ "ss_elems", "ss_sides", "=", "exo", ".", "get_side_set", "(", "side_set_id", ")" ]
def get_side_set(self, id): """ ss_elems, ss_sides = exo.get_side_set(side_set_id) -> get the lists of element and side indices in a side set; the two lists correspond: together, ss_elems[i] and ss_sides[i] define the face of an element input value(s): <int> side_set_id side set *ID* (not *INDEX*) return value(s): if array_type == 'ctype': <list<int>> ss_elems <list<int>> ss_sides if array_type == 'numpy': <np_array<int>> ss_elems <np_array<int>> ss_sides """ (side_set_elem_list, side_set_side_list) = self.__ex_get_side_set(id) if self.use_numpy: side_set_elem_list = ctype_to_numpy(self, side_set_elem_list) side_set_side_list = ctype_to_numpy(self, side_set_side_list) return (side_set_elem_list, side_set_side_list)
[ "def", "get_side_set", "(", "self", ",", "id", ")", ":", "(", "side_set_elem_list", ",", "side_set_side_list", ")", "=", "self", ".", "__ex_get_side_set", "(", "id", ")", "if", "self", ".", "use_numpy", ":", "side_set_elem_list", "=", "ctype_to_numpy", "(", ...
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus2.in.py#L2689-L2714
daijifeng001/caffe-rfcn
543f8f6a4b7c88256ea1445ae951a12d1ad9cffd
scripts/cpp_lint.py
python
CloseExpression
(clean_lines, linenum, pos)
return (line, clean_lines.NumLines(), -1)
If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ( or { or [ or <, finds the position that closes it.
[ "If", "input", "points", "to", "(", "or", "{", "or", "[", "or", "<", "finds", "the", "position", "that", "closes", "it", "." ]
def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] startchar = line[pos] if startchar not in '({[<': return (line, clean_lines.NumLines(), -1) if startchar == '(': endchar = ')' if startchar == '[': endchar = ']' if startchar == '{': endchar = '}' if startchar == '<': endchar = '>' # Check first line (end_pos, num_open) = FindEndOfExpressionInLine( line, pos, 0, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, num_open) = FindEndOfExpressionInLine( line, 0, num_open, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) # Did not find endchar before end of file, give up return (line, clean_lines.NumLines(), -1)
[ "def", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "startchar", "=", "line", "[", "pos", "]", "if", "startchar", "not", "in", "'({[<'", ":", "return", "(", ...
https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/scripts/cpp_lint.py#L1254-L1297
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/debug/lib/common.py
python
get_graph_element_name
(elem)
return elem.name if hasattr(elem, "name") else str(elem)
Obtain the name or string representation of a graph element. If the graph element has the attribute "name", return name. Otherwise, return a __str__ representation of the graph element. Certain graph elements, such as `SparseTensor`s, do not have the attribute "name". Args: elem: The graph element in question. Returns: If the attribute 'name' is available, return the name. Otherwise, return str(fetch).
Obtain the name or string representation of a graph element.
[ "Obtain", "the", "name", "or", "string", "representation", "of", "a", "graph", "element", "." ]
def get_graph_element_name(elem): """Obtain the name or string representation of a graph element. If the graph element has the attribute "name", return name. Otherwise, return a __str__ representation of the graph element. Certain graph elements, such as `SparseTensor`s, do not have the attribute "name". Args: elem: The graph element in question. Returns: If the attribute 'name' is available, return the name. Otherwise, return str(fetch). """ return elem.name if hasattr(elem, "name") else str(elem)
[ "def", "get_graph_element_name", "(", "elem", ")", ":", "return", "elem", ".", "name", "if", "hasattr", "(", "elem", ",", "\"name\"", ")", "else", "str", "(", "elem", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/common.py#L25-L40
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_Rewrap_REQUEST.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPM2_Rewrap_REQUEST)
Returns new TPM2_Rewrap_REQUEST object constructed from its marshaled representation in the given byte buffer
Returns new TPM2_Rewrap_REQUEST object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPM2_Rewrap_REQUEST", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPM2_Rewrap_REQUEST object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPM2_Rewrap_REQUEST)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPM2_Rewrap_REQUEST", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L10429-L10433
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/toolkits/_internal_utils.py
python
_summarize_coefficients
(top_coefs, bottom_coefs)
return ([top_coefs_list, bottom_coefs_list], \ [ 'Highest Positive Coefficients', 'Lowest Negative Coefficients'] )
Return a tuple of sections and section titles. Sections are pretty print of model coefficients Parameters ---------- top_coefs : SFrame of top k coefficients bottom_coefs : SFrame of bottom k coefficients Returns ------- (sections, section_titles) : tuple sections : list summary sections for top/bottom k coefficients section_titles : list summary section titles
Return a tuple of sections and section titles. Sections are pretty print of model coefficients
[ "Return", "a", "tuple", "of", "sections", "and", "section", "titles", ".", "Sections", "are", "pretty", "print", "of", "model", "coefficients" ]
def _summarize_coefficients(top_coefs, bottom_coefs): """ Return a tuple of sections and section titles. Sections are pretty print of model coefficients Parameters ---------- top_coefs : SFrame of top k coefficients bottom_coefs : SFrame of bottom k coefficients Returns ------- (sections, section_titles) : tuple sections : list summary sections for top/bottom k coefficients section_titles : list summary section titles """ def get_row_name(row): if row['index'] == None: return row['name'] else: return "%s[%s]" % (row['name'], row['index']) if len(top_coefs) == 0: top_coefs_list = [('No Positive Coefficients', _precomputed_field('') )] else: top_coefs_list = [ (get_row_name(row), _precomputed_field(row['value'])) \ for row in top_coefs ] if len(bottom_coefs) == 0: bottom_coefs_list = [('No Negative Coefficients', _precomputed_field(''))] else: bottom_coefs_list = [ (get_row_name(row), _precomputed_field(row['value'])) \ for row in bottom_coefs ] return ([top_coefs_list, bottom_coefs_list], \ [ 'Highest Positive Coefficients', 'Lowest Negative Coefficients'] )
[ "def", "_summarize_coefficients", "(", "top_coefs", ",", "bottom_coefs", ")", ":", "def", "get_row_name", "(", "row", ")", ":", "if", "row", "[", "'index'", "]", "==", "None", ":", "return", "row", "[", "'name'", "]", "else", ":", "return", "\"%s[%s]\"", ...
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/toolkits/_internal_utils.py#L105-L146
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_wx/mainframe.py
python
AgileMainframe.on_open
(self, event)
Open a document
Open a document
[ "Open", "a", "document" ]
def on_open(self, event): """Open a document""" #wildcards = CreateWildCards() + "All files (*.*)|*.*" print 'open it!!'
[ "def", "on_open", "(", "self", ",", "event", ")", ":", "#wildcards = CreateWildCards() + \"All files (*.*)|*.*\"", "print", "'open it!!'" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/mainframe.py#L397-L400
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGridInterface.SetPropertyAttribute
(*args, **kwargs)
return _propgrid.PropertyGridInterface_SetPropertyAttribute(*args, **kwargs)
SetPropertyAttribute(self, PGPropArg id, String attrName, wxVariant value, long argFlags=0)
SetPropertyAttribute(self, PGPropArg id, String attrName, wxVariant value, long argFlags=0)
[ "SetPropertyAttribute", "(", "self", "PGPropArg", "id", "String", "attrName", "wxVariant", "value", "long", "argFlags", "=", "0", ")" ]
def SetPropertyAttribute(*args, **kwargs): """SetPropertyAttribute(self, PGPropArg id, String attrName, wxVariant value, long argFlags=0)""" return _propgrid.PropertyGridInterface_SetPropertyAttribute(*args, **kwargs)
[ "def", "SetPropertyAttribute", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_SetPropertyAttribute", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L1377-L1379
microsoft/clang
86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5
tools/scan-build-py/libscanbuild/analyze.py
python
analyze_compiler_wrapper
()
return compiler_wrapper(analyze_compiler_wrapper_impl)
Entry point for `analyze-cc` and `analyze-c++` compiler wrappers.
Entry point for `analyze-cc` and `analyze-c++` compiler wrappers.
[ "Entry", "point", "for", "analyze", "-", "cc", "and", "analyze", "-", "c", "++", "compiler", "wrappers", "." ]
def analyze_compiler_wrapper(): """ Entry point for `analyze-cc` and `analyze-c++` compiler wrappers. """ return compiler_wrapper(analyze_compiler_wrapper_impl)
[ "def", "analyze_compiler_wrapper", "(", ")", ":", "return", "compiler_wrapper", "(", "analyze_compiler_wrapper_impl", ")" ]
https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/tools/scan-build-py/libscanbuild/analyze.py#L291-L294
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/cephfs/kernel_mount.py
python
KernelMount.get_osd_epoch
(self)
return epoch, barrier
Return 2-tuple of osd_epoch, osd_epoch_barrier
Return 2-tuple of osd_epoch, osd_epoch_barrier
[ "Return", "2", "-", "tuple", "of", "osd_epoch", "osd_epoch_barrier" ]
def get_osd_epoch(self): """ Return 2-tuple of osd_epoch, osd_epoch_barrier """ osd_map = self.read_debug_file("osdmap") assert osd_map lines = osd_map.split("\n") first_line_tokens = lines[0].split() epoch, barrier = int(first_line_tokens[1]), int(first_line_tokens[3]) return epoch, barrier
[ "def", "get_osd_epoch", "(", "self", ")", ":", "osd_map", "=", "self", ".", "read_debug_file", "(", "\"osdmap\"", ")", "assert", "osd_map", "lines", "=", "osd_map", ".", "split", "(", "\"\\n\"", ")", "first_line_tokens", "=", "lines", "[", "0", "]", ".", ...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/cephfs/kernel_mount.py#L338-L349
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMS_CREATION_INFO.fromTpm
(buf)
return buf.createObj(TPMS_CREATION_INFO)
Returns new TPMS_CREATION_INFO object constructed from its marshaled representation in the given TpmBuffer buffer
Returns new TPMS_CREATION_INFO object constructed from its marshaled representation in the given TpmBuffer buffer
[ "Returns", "new", "TPMS_CREATION_INFO", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "TpmBuffer", "buffer" ]
def fromTpm(buf): """ Returns new TPMS_CREATION_INFO object constructed from its marshaled representation in the given TpmBuffer buffer """ return buf.createObj(TPMS_CREATION_INFO)
[ "def", "fromTpm", "(", "buf", ")", ":", "return", "buf", ".", "createObj", "(", "TPMS_CREATION_INFO", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L5305-L5309
wy1iu/LargeMargin_Softmax_Loss
c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec
python/caffe/pycaffe.py
python
_Net_forward_backward_all
(self, blobs=None, diffs=None, **kwargs)
return all_outs, all_diffs
Run net forward + backward in batches. Parameters ---------- blobs: list of blobs to extract as in forward() diffs: list of diffs to extract as in backward() kwargs: Keys are input (for forward) and output (for backward) blob names and values are ndarrays. Refer to forward() and backward(). Prefilled variants are called for lack of input or output blobs. Returns ------- all_blobs: {blob name: blob ndarray} dict. all_diffs: {blob name: diff ndarray} dict.
Run net forward + backward in batches.
[ "Run", "net", "forward", "+", "backward", "in", "batches", "." ]
def _Net_forward_backward_all(self, blobs=None, diffs=None, **kwargs): """ Run net forward + backward in batches. Parameters ---------- blobs: list of blobs to extract as in forward() diffs: list of diffs to extract as in backward() kwargs: Keys are input (for forward) and output (for backward) blob names and values are ndarrays. Refer to forward() and backward(). Prefilled variants are called for lack of input or output blobs. Returns ------- all_blobs: {blob name: blob ndarray} dict. all_diffs: {blob name: diff ndarray} dict. """ # Batch blobs and diffs. all_outs = {out: [] for out in set(self.outputs + (blobs or []))} all_diffs = {diff: [] for diff in set(self.inputs + (diffs or []))} forward_batches = self._batch({in_: kwargs[in_] for in_ in self.inputs if in_ in kwargs}) backward_batches = self._batch({out: kwargs[out] for out in self.outputs if out in kwargs}) # Collect outputs from batches (and heed lack of forward/backward batches). for fb, bb in izip_longest(forward_batches, backward_batches, fillvalue={}): batch_blobs = self.forward(blobs=blobs, **fb) batch_diffs = self.backward(diffs=diffs, **bb) for out, out_blobs in six.iteritems(batch_blobs): all_outs[out].extend(out_blobs.copy()) for diff, out_diffs in six.iteritems(batch_diffs): all_diffs[diff].extend(out_diffs.copy()) # Package in ndarray. for out, diff in zip(all_outs, all_diffs): all_outs[out] = np.asarray(all_outs[out]) all_diffs[diff] = np.asarray(all_diffs[diff]) # Discard padding at the end and package in ndarray. pad = len(six.next(six.itervalues(all_outs))) - len(six.next(six.itervalues(kwargs))) if pad: for out, diff in zip(all_outs, all_diffs): all_outs[out] = all_outs[out][:-pad] all_diffs[diff] = all_diffs[diff][:-pad] return all_outs, all_diffs
[ "def", "_Net_forward_backward_all", "(", "self", ",", "blobs", "=", "None", ",", "diffs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Batch blobs and diffs.", "all_outs", "=", "{", "out", ":", "[", "]", "for", "out", "in", "set", "(", "self", "....
https://github.com/wy1iu/LargeMargin_Softmax_Loss/blob/c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec/python/caffe/pycaffe.py#L206-L248
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
Region.UnionRegion
(*args, **kwargs)
return _gdi_.Region_UnionRegion(*args, **kwargs)
UnionRegion(self, Region region) -> bool
UnionRegion(self, Region region) -> bool
[ "UnionRegion", "(", "self", "Region", "region", ")", "-", ">", "bool" ]
def UnionRegion(*args, **kwargs): """UnionRegion(self, Region region) -> bool""" return _gdi_.Region_UnionRegion(*args, **kwargs)
[ "def", "UnionRegion", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Region_UnionRegion", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L1611-L1613
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/quantize/python/graph_matcher.py
python
GraphMatcher.__init__
(self, pattern)
Initializes a GraphMatcher. Args: pattern: The `Pattern` against which `GraphMatcher` matches subgraphs.
Initializes a GraphMatcher.
[ "Initializes", "a", "GraphMatcher", "." ]
def __init__(self, pattern): """Initializes a GraphMatcher. Args: pattern: The `Pattern` against which `GraphMatcher` matches subgraphs. """ self._pattern = pattern
[ "def", "__init__", "(", "self", ",", "pattern", ")", ":", "self", ".", "_pattern", "=", "pattern" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/quantize/python/graph_matcher.py#L204-L211
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
DateTime.__init__
(self, *args, **kwargs)
__init__(self) -> DateTime
__init__(self) -> DateTime
[ "__init__", "(", "self", ")", "-", ">", "DateTime" ]
def __init__(self, *args, **kwargs): """__init__(self) -> DateTime""" _misc_.DateTime_swiginit(self,_misc_.new_DateTime(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_misc_", ".", "DateTime_swiginit", "(", "self", ",", "_misc_", ".", "new_DateTime", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L3781-L3783
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Rect.SetTopLeft
(*args, **kwargs)
return _core_.Rect_SetTopLeft(*args, **kwargs)
SetTopLeft(self, Point p)
SetTopLeft(self, Point p)
[ "SetTopLeft", "(", "self", "Point", "p", ")" ]
def SetTopLeft(*args, **kwargs): """SetTopLeft(self, Point p)""" return _core_.Rect_SetTopLeft(*args, **kwargs)
[ "def", "SetTopLeft", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Rect_SetTopLeft", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1325-L1327
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/site.py
python
enablerlcompleter
()
Enable default readline configuration on interactive prompts, by registering a sys.__interactivehook__. If the readline module can be imported, the hook will set the Tab key as completion key and register ~/.python_history as history file. This can be overridden in the sitecustomize or usercustomize module, or in a PYTHONSTARTUP file.
Enable default readline configuration on interactive prompts, by registering a sys.__interactivehook__.
[ "Enable", "default", "readline", "configuration", "on", "interactive", "prompts", "by", "registering", "a", "sys", ".", "__interactivehook__", "." ]
def enablerlcompleter(): """Enable default readline configuration on interactive prompts, by registering a sys.__interactivehook__. If the readline module can be imported, the hook will set the Tab key as completion key and register ~/.python_history as history file. This can be overridden in the sitecustomize or usercustomize module, or in a PYTHONSTARTUP file. """ def register_readline(): import atexit try: import readline import rlcompleter except ImportError: return # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 history = os.path.join(os.path.expanduser('~'), '.python_history') try: readline.read_history_file(history) except OSError: pass def write_history(): try: readline.write_history_file(history) except OSError: # bpo-19891, bpo-41193: Home directory does not exist # or is not writable, or the filesystem is read-only. pass atexit.register(write_history) sys.__interactivehook__ = register_readline
[ "def", "enablerlcompleter", "(", ")", ":", "def", "register_readline", "(", ")", ":", "import", "atexit", "try", ":", "import", "readline", "import", "rlcompleter", "except", "ImportError", ":", "return", "# Reading the initialization (config) file may not be enough to se...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/site.py#L406-L463
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/tools/grit/grit/format/chrome_messages_json.py
python
Format
(root, lang='en', output_dir='.')
Format the messages as JSON.
Format the messages as JSON.
[ "Format", "the", "messages", "as", "JSON", "." ]
def Format(root, lang='en', output_dir='.'): """Format the messages as JSON.""" yield '{' encoder = JSONEncoder(ensure_ascii=False) format = '"%s":{"message":%s%s}' placeholder_format = '"%i":{"content":"$%i"}' first = True for child in root.ActiveDescendants(): if isinstance(child, message.MessageNode): id = child.attrs['name'] if id.startswith('IDR_') or id.startswith('IDS_'): id = id[4:] translation_missing = child.GetCliques()[0].clique.get(lang) is None; if (child.ShouldFallbackToEnglish() and translation_missing and lang not in constants.PSEUDOLOCALES): # Skip the string if it's not translated. Chrome will fallback # to English automatically. continue loc_message = encoder.encode(child.ws_at_start + child.Translate(lang) + child.ws_at_end) # Replace $n place-holders with $n$ and add an appropriate "placeholders" # entry. Note that chrome.i18n.getMessage only supports 9 placeholders: # https://developer.chrome.com/extensions/i18n#method-getMessage placeholders = '' for i in range(1, 10): if loc_message.find('$%d' % i) == -1: break loc_message = loc_message.replace('$%d' % i, '$%d$' % i) if placeholders: placeholders += ',' placeholders += placeholder_format % (i, i) if not first: yield ',' first = False if placeholders: placeholders = ',"placeholders":{%s}' % placeholders yield format % (id, loc_message, placeholders) yield '}'
[ "def", "Format", "(", "root", ",", "lang", "=", "'en'", ",", "output_dir", "=", "'.'", ")", ":", "yield", "'{'", "encoder", "=", "JSONEncoder", "(", "ensure_ascii", "=", "False", ")", "format", "=", "'\"%s\":{\"message\":%s%s}'", "placeholder_format", "=", "...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/format/chrome_messages_json.py#L15-L59
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/roscpp/rosbuild/scripts/msg_gen.py
python
write_end
(s, spec)
Writes the end of the header file: the ending of the include guards @param s: The stream to write to @type s: stream @param spec: The spec @type spec: roslib.msgs.MsgSpec
Writes the end of the header file: the ending of the include guards
[ "Writes", "the", "end", "of", "the", "header", "file", ":", "the", "ending", "of", "the", "include", "guards" ]
def write_end(s, spec): """ Writes the end of the header file: the ending of the include guards @param s: The stream to write to @type s: stream @param spec: The spec @type spec: roslib.msgs.MsgSpec """ s.write('#endif // %s_MESSAGE_%s_H\n'%(spec.package.upper(), spec.short_name.upper()))
[ "def", "write_end", "(", "s", ",", "spec", ")", ":", "s", ".", "write", "(", "'#endif // %s_MESSAGE_%s_H\\n'", "%", "(", "spec", ".", "package", ".", "upper", "(", ")", ",", "spec", ".", "short_name", ".", "upper", "(", ")", ")", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roscpp/rosbuild/scripts/msg_gen.py#L130-L139
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/optparse.py
python
HelpFormatter.format_option_strings
(self, option)
return ", ".join(opts)
Return a comma-separated list of option strings & metavariables.
Return a comma-separated list of option strings & metavariables.
[ "Return", "a", "comma", "-", "separated", "list", "of", "option", "strings", "&", "metavariables", "." ]
def format_option_strings(self, option): """Return a comma-separated list of option strings & metavariables.""" if option.takes_value(): metavar = option.metavar or option.dest.upper() short_opts = [self._short_opt_fmt % (sopt, metavar) for sopt in option._short_opts] long_opts = [self._long_opt_fmt % (lopt, metavar) for lopt in option._long_opts] else: short_opts = option._short_opts long_opts = option._long_opts if self.short_first: opts = short_opts + long_opts else: opts = long_opts + short_opts return ", ".join(opts)
[ "def", "format_option_strings", "(", "self", ",", "option", ")", ":", "if", "option", ".", "takes_value", "(", ")", ":", "metavar", "=", "option", ".", "metavar", "or", "option", ".", "dest", ".", "upper", "(", ")", "short_opts", "=", "[", "self", ".",...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/optparse.py#L342-L359
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings._GetAdditionalLibraryDirectories
(self, root, config, gyp_to_build_path)
return ['/LIBPATH:"' + p + '"' for p in libpaths]
Get and normalize the list of paths in AdditionalLibraryDirectories setting.
Get and normalize the list of paths in AdditionalLibraryDirectories setting.
[ "Get", "and", "normalize", "the", "list", "of", "paths", "in", "AdditionalLibraryDirectories", "setting", "." ]
def _GetAdditionalLibraryDirectories(self, root, config, gyp_to_build_path): """Get and normalize the list of paths in AdditionalLibraryDirectories setting.""" config = self._TargetConfig(config) libpaths = self._Setting( (root, "AdditionalLibraryDirectories"), config, default=[] ) libpaths = [ os.path.normpath(gyp_to_build_path(self.ConvertVSMacros(p, config=config))) for p in libpaths ] return ['/LIBPATH:"' + p + '"' for p in libpaths]
[ "def", "_GetAdditionalLibraryDirectories", "(", "self", ",", "root", ",", "config", ",", "gyp_to_build_path", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "libpaths", "=", "self", ".", "_Setting", "(", "(", "root", ",", "\"Addit...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/msvs_emulation.py#L581-L592
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/model/coordinates.py
python
Frame.worldOrigin
(self)
return self._worldCoordinates[1]
Returns an element of R^3 denoting the translation of the origin of this frame in world coordinates
Returns an element of R^3 denoting the translation of the origin of this frame in world coordinates
[ "Returns", "an", "element", "of", "R^3", "denoting", "the", "translation", "of", "the", "origin", "of", "this", "frame", "in", "world", "coordinates" ]
def worldOrigin(self): """Returns an element of R^3 denoting the translation of the origin of this frame in world coordinates""" return self._worldCoordinates[1]
[ "def", "worldOrigin", "(", "self", ")", ":", "return", "self", ".", "_worldCoordinates", "[", "1", "]" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/coordinates.py#L51-L54
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/tabart.py
python
VC8TabArt.Clone
(self)
return art
Clones the art object.
Clones the art object.
[ "Clones", "the", "art", "object", "." ]
def Clone(self): """ Clones the art object. """ art = type(self)() art.SetNormalFont(self.GetNormalFont()) art.SetSelectedFont(self.GetSelectedFont()) art.SetMeasuringFont(self.GetMeasuringFont()) art = CopyAttributes(art, self) return art
[ "def", "Clone", "(", "self", ")", ":", "art", "=", "type", "(", "self", ")", "(", ")", "art", ".", "SetNormalFont", "(", "self", ".", "GetNormalFont", "(", ")", ")", "art", ".", "SetSelectedFont", "(", "self", ".", "GetSelectedFont", "(", ")", ")", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/tabart.py#L2179-L2188
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings._GetLdManifestFlags
(self, config, name, gyp_to_build_path, allow_isolation, build_dir)
return flags, output_name, manifest_files
Returns a 3-tuple: - the set of flags that need to be added to the link to generate a default manifest - the intermediate manifest that the linker will generate that should be used to assert it doesn't add anything to the merged one. - the list of all the manifest files to be merged by the manifest tool and included into the link.
Returns a 3-tuple: - the set of flags that need to be added to the link to generate a default manifest - the intermediate manifest that the linker will generate that should be used to assert it doesn't add anything to the merged one. - the list of all the manifest files to be merged by the manifest tool and included into the link.
[ "Returns", "a", "3", "-", "tuple", ":", "-", "the", "set", "of", "flags", "that", "need", "to", "be", "added", "to", "the", "link", "to", "generate", "a", "default", "manifest", "-", "the", "intermediate", "manifest", "that", "the", "linker", "will", "...
def _GetLdManifestFlags(self, config, name, gyp_to_build_path, allow_isolation, build_dir): """Returns a 3-tuple: - the set of flags that need to be added to the link to generate a default manifest - the intermediate manifest that the linker will generate that should be used to assert it doesn't add anything to the merged one. - the list of all the manifest files to be merged by the manifest tool and included into the link.""" generate_manifest = self._Setting(('VCLinkerTool', 'GenerateManifest'), config, default='true') if generate_manifest != 'true': # This means not only that the linker should not generate the intermediate # manifest but also that the manifest tool should do nothing even when # additional manifests are specified. return ['/MANIFEST:NO'], [], [] output_name = name + '.intermediate.manifest' flags = [ '/MANIFEST', '/ManifestFile:' + output_name, ] # Instead of using the MANIFESTUAC flags, we generate a .manifest to # include into the list of manifests. This allows us to avoid the need to # do two passes during linking. The /MANIFEST flag and /ManifestFile are # still used, and the intermediate manifest is used to assert that the # final manifest we get from merging all the additional manifest files # (plus the one we generate here) isn't modified by merging the # intermediate into it. # Always NO, because we generate a manifest file that has what we want. flags.append('/MANIFESTUAC:NO') config = self._TargetConfig(config) enable_uac = self._Setting(('VCLinkerTool', 'EnableUAC'), config, default='true') manifest_files = [] generated_manifest_outer = \ "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" \ "<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>%s" \ "</assembly>" if enable_uac == 'true': execution_level = self._Setting(('VCLinkerTool', 'UACExecutionLevel'), config, default='0') execution_level_map = { '0': 'asInvoker', '1': 'highestAvailable', '2': 'requireAdministrator' } ui_access = self._Setting(('VCLinkerTool', 'UACUIAccess'), config, default='false') inner = ''' <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level='%s' uiAccess='%s' /> </requestedPrivileges> </security> </trustInfo>''' % (execution_level_map[execution_level], ui_access) else: inner = '' generated_manifest_contents = generated_manifest_outer % inner generated_name = name + '.generated.manifest' # Need to join with the build_dir here as we're writing it during # generation time, but we return the un-joined version because the build # will occur in that directory. We only write the file if the contents # have changed so that simply regenerating the project files doesn't # cause a relink. build_dir_generated_name = os.path.join(build_dir, generated_name) gyp.common.EnsureDirExists(build_dir_generated_name) f = gyp.common.WriteOnDiff(build_dir_generated_name) f.write(generated_manifest_contents) f.close() manifest_files = [generated_name] if allow_isolation: flags.append('/ALLOWISOLATION') manifest_files += self._GetAdditionalManifestFiles(config, gyp_to_build_path) return flags, output_name, manifest_files
[ "def", "_GetLdManifestFlags", "(", "self", ",", "config", ",", "name", ",", "gyp_to_build_path", ",", "allow_isolation", ",", "build_dir", ")", ":", "generate_manifest", "=", "self", ".", "_Setting", "(", "(", "'VCLinkerTool'", ",", "'GenerateManifest'", ")", ",...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py#L671-L756
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBTypeSynthetic.CreateWithScriptCode
(*args)
return _lldb.SBTypeSynthetic_CreateWithScriptCode(*args)
CreateWithScriptCode(str data, uint32_t options = 0) -> SBTypeSynthetic CreateWithScriptCode(str data) -> SBTypeSynthetic
CreateWithScriptCode(str data, uint32_t options = 0) -> SBTypeSynthetic CreateWithScriptCode(str data) -> SBTypeSynthetic
[ "CreateWithScriptCode", "(", "str", "data", "uint32_t", "options", "=", "0", ")", "-", ">", "SBTypeSynthetic", "CreateWithScriptCode", "(", "str", "data", ")", "-", ">", "SBTypeSynthetic" ]
def CreateWithScriptCode(*args): """ CreateWithScriptCode(str data, uint32_t options = 0) -> SBTypeSynthetic CreateWithScriptCode(str data) -> SBTypeSynthetic """ return _lldb.SBTypeSynthetic_CreateWithScriptCode(*args)
[ "def", "CreateWithScriptCode", "(", "*", "args", ")", ":", "return", "_lldb", ".", "SBTypeSynthetic_CreateWithScriptCode", "(", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L11562-L11567
llvm-dcpu16/llvm-dcpu16
ae6b01fecd03219677e391d4421df5d966d80dcf
utils/lit/lit/LitConfig.py
python
LitConfig.getBashPath
(self)
return self.bashPath
getBashPath - Get the path to 'bash
getBashPath - Get the path to 'bash
[ "getBashPath", "-", "Get", "the", "path", "to", "bash" ]
def getBashPath(self): """getBashPath - Get the path to 'bash'""" import os, Util if self.bashPath is not None: return self.bashPath self.bashPath = Util.which('bash', os.pathsep.join(self.path)) if self.bashPath is None: # Check some known paths. for path in ('/bin/bash', '/usr/bin/bash', '/usr/local/bin/bash'): if os.path.exists(path): self.bashPath = path break if self.bashPath is None: self.warning("Unable to find 'bash', running Tcl tests internally.") self.bashPath = '' return self.bashPath
[ "def", "getBashPath", "(", "self", ")", ":", "import", "os", ",", "Util", "if", "self", ".", "bashPath", "is", "not", "None", ":", "return", "self", ".", "bashPath", "self", ".", "bashPath", "=", "Util", ".", "which", "(", "'bash'", ",", "os", ".", ...
https://github.com/llvm-dcpu16/llvm-dcpu16/blob/ae6b01fecd03219677e391d4421df5d966d80dcf/utils/lit/lit/LitConfig.py#L70-L89
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/packages/six.py
python
with_metaclass
(meta, *bases)
return type.__new__(metaclass, "temporary_class", (), {})
Create a base class with a metaclass.
Create a base class with a metaclass.
[ "Create", "a", "base", "class", "with", "a", "metaclass", "." ]
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases) return type.__new__(metaclass, "temporary_class", (), {})
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# This requires a bit of explanation: the basic idea is to make a dummy", "# metaclass for one level of class instantiation that replaces itself with", "# the actual metaclass.", "class", "metaclass", "(", "type", ")...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/packages/six.py#L884-L897
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/random_array.py
python
random_integers
(maximum, minimum=1, shape=[])
return randint(minimum, maximum+1, shape)
random_integers(max, min=1, shape=[]) = random integers in range min-max inclusive
random_integers(max, min=1, shape=[]) = random integers in range min-max inclusive
[ "random_integers", "(", "max", "min", "=", "1", "shape", "=", "[]", ")", "=", "random", "integers", "in", "range", "min", "-", "max", "inclusive" ]
def random_integers(maximum, minimum=1, shape=[]): """random_integers(max, min=1, shape=[]) = random integers in range min-max inclusive""" return randint(minimum, maximum+1, shape)
[ "def", "random_integers", "(", "maximum", ",", "minimum", "=", "1", ",", "shape", "=", "[", "]", ")", ":", "return", "randint", "(", "minimum", ",", "maximum", "+", "1", ",", "shape", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/random_array.py#L59-L61
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathGeom.py
python
isHorizontal
(obj)
return None
isHorizontal(obj) ... answer True if obj points into X or Y
isHorizontal(obj) ... answer True if obj points into X or Y
[ "isHorizontal", "(", "obj", ")", "...", "answer", "True", "if", "obj", "points", "into", "X", "or", "Y" ]
def isHorizontal(obj): """isHorizontal(obj) ... answer True if obj points into X or Y""" if type(obj) == FreeCAD.Vector: return isRoughly(obj.z, 0) if obj.ShapeType == "Face": if type(obj.Surface) == Part.Plane: return isVertical(obj.Surface.Axis) if type(obj.Surface) == Part.Cylinder or type(obj.Surface) == Part.Cone: return isHorizontal(obj.Surface.Axis) if type(obj.Surface) == Part.Sphere: return True if type(obj.Surface) == Part.SurfaceOfExtrusion: return isHorizontal(obj.Surface.Direction) if type(obj.Surface) == Part.SurfaceOfRevolution: return isVertical(obj.Surface.Direction) return isRoughly(obj.BoundBox.ZLength, 0.0) if obj.ShapeType == "Edge": if type(obj.Curve) == Part.Line or type(obj.Curve) == Part.LineSegment: return isHorizontal(obj.Vertexes[1].Point - obj.Vertexes[0].Point) if ( type(obj.Curve) == Part.Circle or type(obj.Curve) == Part.Ellipse ): # or type(obj.Curve) == Part.BSplineCurve: return isVertical(obj.Curve.Axis) return isRoughly(obj.BoundBox.ZLength, 0.0) PathLog.error(translate("PathGeom", "isHorizontal(%s) not supported") % obj) return None
[ "def", "isHorizontal", "(", "obj", ")", ":", "if", "type", "(", "obj", ")", "==", "FreeCAD", ".", "Vector", ":", "return", "isRoughly", "(", "obj", ".", "z", ",", "0", ")", "if", "obj", ".", "ShapeType", "==", "\"Face\"", ":", "if", "type", "(", ...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathGeom.py#L200-L228
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
WorldModel.enableGeometryLoading
(self, enabled)
return _robotsim.WorldModel_enableGeometryLoading(self, enabled)
enableGeometryLoading(WorldModel self, bool enabled) If geometry loading is set to false, then only the kinematics are loaded from disk, and no geometry / visualization / collision detection structures will be loaded. Useful for quick scripts that just use kinematics / dynamics of a robot.
enableGeometryLoading(WorldModel self, bool enabled)
[ "enableGeometryLoading", "(", "WorldModel", "self", "bool", "enabled", ")" ]
def enableGeometryLoading(self, enabled): """ enableGeometryLoading(WorldModel self, bool enabled) If geometry loading is set to false, then only the kinematics are loaded from disk, and no geometry / visualization / collision detection structures will be loaded. Useful for quick scripts that just use kinematics / dynamics of a robot. """ return _robotsim.WorldModel_enableGeometryLoading(self, enabled)
[ "def", "enableGeometryLoading", "(", "self", ",", "enabled", ")", ":", "return", "_robotsim", ".", "WorldModel_enableGeometryLoading", "(", "self", ",", "enabled", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L6095-L6106
spring/spring
553a21526b144568b608a0507674b076ec80d9f9
buildbot/stacktrace_translator/stacktrace_translator.py
python
translate_module_addresses
(module, debugarchive, addresses, debugfile)
return [fixup(addr, *line.split(':')) for addr, line in zip(addresses, stdout.splitlines())]
\ Translate addresses in a module to (module, address, filename, lineno) tuples by invoking addr2line exactly once on the debugging symbols for that module. >>> translate_module_addresses( 'spring.dbg', TESTFILE, ['0x0'], 'spring.dbg') [('spring.dbg', '0x0', '??', 0)]
\ Translate addresses in a module to (module, address, filename, lineno) tuples by invoking addr2line exactly once on the debugging symbols for that module. >>> translate_module_addresses( 'spring.dbg', TESTFILE, ['0x0'], 'spring.dbg') [('spring.dbg', '0x0', '??', 0)]
[ "\\", "Translate", "addresses", "in", "a", "module", "to", "(", "module", "address", "filename", "lineno", ")", "tuples", "by", "invoking", "addr2line", "exactly", "once", "on", "the", "debugging", "symbols", "for", "that", "module", ".", ">>>", "translate_mod...
def translate_module_addresses(module, debugarchive, addresses, debugfile): '''\ Translate addresses in a module to (module, address, filename, lineno) tuples by invoking addr2line exactly once on the debugging symbols for that module. >>> translate_module_addresses( 'spring.dbg', TESTFILE, ['0x0'], 'spring.dbg') [('spring.dbg', '0x0', '??', 0)] ''' with NamedTemporaryFile() as tempfile: log.info('\tExtracting debug symbols for module %s from archive %s...' % (module, os.path.basename(debugfile))) # e = extract without path, -so = write output to stdout, -y = yes to all questions sevenzip = Popen([SEVENZIP, 'e', '-so', '-y', debugfile, debugarchive], stdout = tempfile, stderr = PIPE, universal_newlines=True) stdout, stderr = sevenzip.communicate() if stderr: log.debug('%s stderr: %s' % (SEVENZIP, stderr)) if sevenzip.returncode != 0: fatal('%s exited with status %s' % (SEVENZIP, sevenzip.returncode)) log.info('\t\t[OK]') log.info('\tTranslating addresses for module %s...' % module) if module.endswith('.dll'): cmd = [ADDR2LINE, '-j', '.text', '-e', tempfile.name] else: cmd = [ADDR2LINE, '-e', tempfile.name] log.debug('\tCommand line: ' + ' '.join(cmd)) addr2line = Popen(cmd, stdin = PIPE, stdout = PIPE, stderr = PIPE, universal_newlines=True) if addr2line.poll() == None: stdout, stderr = addr2line.communicate('\n'.join(addresses)) else: stdout, stderr = addr2line.communicate() if stderr: log.debug('%s stderr: %s' % (ADDR2LINE, stderr)) if addr2line.returncode != 0: fatal('%s exited with status %s' % (ADDR2LINE, addr2line.returncode)) log.info('\t\t[OK]') def fixup(addr, file, line): for psu in PATH_STRIP_UNTIL: if psu in file: file = file[file.index(psu)+len(psu):] break return module, addr, file, line return [fixup(addr, *line.split(':')) for addr, line in zip(addresses, stdout.splitlines())]
[ "def", "translate_module_addresses", "(", "module", ",", "debugarchive", ",", "addresses", ",", "debugfile", ")", ":", "with", "NamedTemporaryFile", "(", ")", "as", "tempfile", ":", "log", ".", "info", "(", "'\\tExtracting debug symbols for module %s from archive %s...'...
https://github.com/spring/spring/blob/553a21526b144568b608a0507674b076ec80d9f9/buildbot/stacktrace_translator/stacktrace_translator.py#L276-L318
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
bindings/pyroot/pythonizations/python/ROOT/_pythonization/_tfile.py
python
pythonize_tfile
(klass)
TFile inherits from - TDirectory the pythonized attr syntax (__getattr__) and WriteObject method. - TDirectoryFile the pythonized Get method (pythonized only in Python)
TFile inherits from - TDirectory the pythonized attr syntax (__getattr__) and WriteObject method. - TDirectoryFile the pythonized Get method (pythonized only in Python)
[ "TFile", "inherits", "from", "-", "TDirectory", "the", "pythonized", "attr", "syntax", "(", "__getattr__", ")", "and", "WriteObject", "method", ".", "-", "TDirectoryFile", "the", "pythonized", "Get", "method", "(", "pythonized", "only", "in", "Python", ")" ]
def pythonize_tfile(klass): """ TFile inherits from - TDirectory the pythonized attr syntax (__getattr__) and WriteObject method. - TDirectoryFile the pythonized Get method (pythonized only in Python) """ # Pythonizations for TFile::Open AddFileOpenPyz(klass) klass._OriginalOpen = klass.Open klass.Open = classmethod(_TFileOpen) # Pythonization for TFile constructor klass._OriginalConstructor = klass.__init__ klass.__init__ = _TFileConstructor
[ "def", "pythonize_tfile", "(", "klass", ")", ":", "# Pythonizations for TFile::Open", "AddFileOpenPyz", "(", "klass", ")", "klass", ".", "_OriginalOpen", "=", "klass", ".", "Open", "klass", ".", "Open", "=", "classmethod", "(", "_TFileOpen", ")", "# Pythonization ...
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/pyroot/pythonizations/python/ROOT/_pythonization/_tfile.py#L72-L86
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/applications/workbench/workbench/widgets/about/presenter.py
python
AboutPresenter.should_show_on_startup
()
return current_version != lastVersion
Determines if the first time dialog should be shown :return: True if the dialog should be shown
Determines if the first time dialog should be shown :return: True if the dialog should be shown
[ "Determines", "if", "the", "first", "time", "dialog", "should", "be", "shown", ":", "return", ":", "True", "if", "the", "dialog", "should", "be", "shown" ]
def should_show_on_startup(): """ Determines if the first time dialog should be shown :return: True if the dialog should be shown """ # first check the facility and instrument facility = ConfigService.getString(AboutPresenter.FACILITY) instrument = ConfigService.getString(AboutPresenter.INSTRUMENT) if not facility: return True else: # check we can get the facility and instrument try: facilityInfo = ConfigService.getFacility(facility) instrumentInfo = ConfigService.getInstrument(instrument) logger.information("Default facility '{0}', instrument '{1}'\n".format(facilityInfo.name(), instrumentInfo.name())) except RuntimeError: # failed to find the facility or instrument logger.error("Could not find your default facility '{0}' or instrument '{1}' in facilities.xml, " + "showing please select again.\n".format(facility, instrument)) return True settings = QSettings() settings.beginGroup(AboutPresenter.DO_NOT_SHOW_GROUP) doNotShowUntilNextRelease = int(settings.value(AboutPresenter.DO_NOT_SHOW, '0')) lastVersion = settings.value(AboutPresenter.PREVIOUS_VERSION, "") current_version = version().major + "." + version().minor settings.endGroup() if not doNotShowUntilNextRelease: return True # Now check if the version has changed since last time return current_version != lastVersion
[ "def", "should_show_on_startup", "(", ")", ":", "# first check the facility and instrument", "facility", "=", "ConfigService", ".", "getString", "(", "AboutPresenter", ".", "FACILITY", ")", "instrument", "=", "ConfigService", ".", "getString", "(", "AboutPresenter", "."...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/widgets/about/presenter.py#L60-L93
alibaba/MNN
c4d9566171d589c3ded23aa18ffb197016995a12
pymnn/pip_package/MNN/expr/__init__.py
python
pow
(x, y)
return _F.pow(x, y)
pow(x, y) Return the ``x ** y``, element-wise. alias name: `power`. Parameters ---------- x : var_like, input value. y : var_like, input value. Returns ------- z : Var. The ``x ** y`` of `x` and `y`. Example: ------- >>> expr.pow([9., 0.5], [1.2, -3.0]) var([13.966612, 8.])
pow(x, y) Return the ``x ** y``, element-wise. alias name: `power`.
[ "pow", "(", "x", "y", ")", "Return", "the", "x", "**", "y", "element", "-", "wise", ".", "alias", "name", ":", "power", "." ]
def pow(x, y): ''' pow(x, y) Return the ``x ** y``, element-wise. alias name: `power`. Parameters ---------- x : var_like, input value. y : var_like, input value. Returns ------- z : Var. The ``x ** y`` of `x` and `y`. Example: ------- >>> expr.pow([9., 0.5], [1.2, -3.0]) var([13.966612, 8.]) ''' x = _to_var(x) y = _to_var(y) x, y = _match_dtype(x, y) return _F.pow(x, y)
[ "def", "pow", "(", "x", ",", "y", ")", ":", "x", "=", "_to_var", "(", "x", ")", "y", "=", "_to_var", "(", "y", ")", "x", ",", "y", "=", "_match_dtype", "(", "x", ",", "y", ")", "return", "_F", ".", "pow", "(", "x", ",", "y", ")" ]
https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/expr/__init__.py#L869-L892
microsoft/EdgeML
ef9f8a77f096acbdeb941014791f8eda1c1bc35b
tf/edgeml_tf/trainer/fastTrainer.py
python
FastTrainer.classifier
(self, feats)
return tf.matmul(feats, self.FC) + self.FCbias
Can be raplaced by any classifier TODO: Make this a separate class if needed
Can be raplaced by any classifier TODO: Make this a separate class if needed
[ "Can", "be", "raplaced", "by", "any", "classifier", "TODO", ":", "Make", "this", "a", "separate", "class", "if", "needed" ]
def classifier(self, feats): ''' Can be raplaced by any classifier TODO: Make this a separate class if needed ''' self.FC = tf.Variable(tf.random_normal( [self.FastObj.output_size, self.numClasses]), name='FC') self.FCbias = tf.Variable(tf.random_normal( [self.numClasses]), name='FCbias') return tf.matmul(feats, self.FC) + self.FCbias
[ "def", "classifier", "(", "self", ",", "feats", ")", ":", "self", ".", "FC", "=", "tf", ".", "Variable", "(", "tf", ".", "random_normal", "(", "[", "self", ".", "FastObj", ".", "output_size", ",", "self", ".", "numClasses", "]", ")", ",", "name", "...
https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/tf/edgeml_tf/trainer/fastTrainer.py#L87-L97
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
uCSIsYiRadicals
(code)
return ret
Check whether the character is part of YiRadicals UCS Block
Check whether the character is part of YiRadicals UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "YiRadicals", "UCS", "Block" ]
def uCSIsYiRadicals(code): """Check whether the character is part of YiRadicals UCS Block """ ret = libxml2mod.xmlUCSIsYiRadicals(code) return ret
[ "def", "uCSIsYiRadicals", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsYiRadicals", "(", "code", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L2193-L2196
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/urllib.py
python
FancyURLopener.http_error_301
(self, url, fp, errcode, errmsg, headers, data=None)
return self.http_error_302(url, fp, errcode, errmsg, headers, data)
Error 301 -- also relocated (permanently).
Error 301 -- also relocated (permanently).
[ "Error", "301", "--", "also", "relocated", "(", "permanently", ")", "." ]
def http_error_301(self, url, fp, errcode, errmsg, headers, data=None): """Error 301 -- also relocated (permanently).""" return self.http_error_302(url, fp, errcode, errmsg, headers, data)
[ "def", "http_error_301", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ",", "data", "=", "None", ")", ":", "return", "self", ".", "http_error_302", "(", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "heade...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/urllib.py#L663-L665
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/contrib/decoder/beam_search_decoder.py
python
StateCell.get_state
(self, state_name)
return self._cur_states[state_name]
The getter of state object. Find the state variable by its name. Args: state_name (str): A string of the state's name. Returns: The associated state object.
The getter of state object. Find the state variable by its name.
[ "The", "getter", "of", "state", "object", ".", "Find", "the", "state", "variable", "by", "its", "name", "." ]
def get_state(self, state_name): """ The getter of state object. Find the state variable by its name. Args: state_name (str): A string of the state's name. Returns: The associated state object. """ if self._in_decoder and not self._switched_decoder: self._switch_decoder() if state_name not in self._cur_states: raise ValueError( 'Unknown state %s. Please make sure _switch_decoder() ' 'invoked.' % state_name) return self._cur_states[state_name]
[ "def", "get_state", "(", "self", ",", "state_name", ")", ":", "if", "self", ".", "_in_decoder", "and", "not", "self", ".", "_switched_decoder", ":", "self", ".", "_switch_decoder", "(", ")", "if", "state_name", "not", "in", "self", ".", "_cur_states", ":",...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/decoder/beam_search_decoder.py#L269-L287
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/wizard.py
python
Wizard.SetPageSize
(*args, **kwargs)
return _wizard.Wizard_SetPageSize(*args, **kwargs)
SetPageSize(self, Size size)
SetPageSize(self, Size size)
[ "SetPageSize", "(", "self", "Size", "size", ")" ]
def SetPageSize(*args, **kwargs): """SetPageSize(self, Size size)""" return _wizard.Wizard_SetPageSize(*args, **kwargs)
[ "def", "SetPageSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_wizard", ".", "Wizard_SetPageSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/wizard.py#L382-L384
alibaba/MNN
c4d9566171d589c3ded23aa18ffb197016995a12
pymnn/pip_package/MNN/expr/__init__.py
python
logical_or
(x, y)
return _F.logical_or(x, y)
logical_or(x, y) The dtype of x, y must be same. Parameters ---------- x : var_like, input value, dtype just support int32. y : var_like, input value, dtype just support int32. Returns ------- z : Var. The ``x or y`` of `x` and `y`, dtype is int32. Example: ------- >>> expr.logical_or([2, 1], [4, 2]) var([1, 1])
logical_or(x, y) The dtype of x, y must be same.
[ "logical_or", "(", "x", "y", ")", "The", "dtype", "of", "x", "y", "must", "be", "same", "." ]
def logical_or(x, y): ''' logical_or(x, y) The dtype of x, y must be same. Parameters ---------- x : var_like, input value, dtype just support int32. y : var_like, input value, dtype just support int32. Returns ------- z : Var. The ``x or y`` of `x` and `y`, dtype is int32. Example: ------- >>> expr.logical_or([2, 1], [4, 2]) var([1, 1]) ''' x = _to_var(x) y = _to_var(y) x, y = _match_dtype(x, y) if x.dtype != _F.int or y.dtype != _F.int: raise ValueError('MNN.expr.logical_or just support int32') return _F.logical_or(x, y)
[ "def", "logical_or", "(", "x", ",", "y", ")", ":", "x", "=", "_to_var", "(", "x", ")", "y", "=", "_to_var", "(", "y", ")", "x", ",", "y", "=", "_match_dtype", "(", "x", ",", "y", ")", "if", "x", ".", "dtype", "!=", "_F", ".", "int", "or", ...
https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/expr/__init__.py#L1124-L1148
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/image_ops_impl.py
python
rgb_to_yuv
(images)
return math_ops.tensordot(images, kernel, axes=[[ndims - 1], [0]])
Converts one or more images from RGB to YUV. Outputs a tensor of the same shape as the `images` tensor, containing the YUV value of the pixels. The output is only well defined if the value in images are in [0, 1]. There are two ways of representing an image: [0, 255] pixel values range or [0, 1] (as float) pixel values range. Users need to convert the input image into a float [0, 1] range. Args: images: 2-D or higher rank. Image data to convert. Last dimension must be size 3. Returns: images: tensor with the same shape as `images`.
Converts one or more images from RGB to YUV.
[ "Converts", "one", "or", "more", "images", "from", "RGB", "to", "YUV", "." ]
def rgb_to_yuv(images): """Converts one or more images from RGB to YUV. Outputs a tensor of the same shape as the `images` tensor, containing the YUV value of the pixels. The output is only well defined if the value in images are in [0, 1]. There are two ways of representing an image: [0, 255] pixel values range or [0, 1] (as float) pixel values range. Users need to convert the input image into a float [0, 1] range. Args: images: 2-D or higher rank. Image data to convert. Last dimension must be size 3. Returns: images: tensor with the same shape as `images`. """ images = ops.convert_to_tensor(images, name='images') kernel = ops.convert_to_tensor( _rgb_to_yuv_kernel, dtype=images.dtype, name='kernel') ndims = images.get_shape().ndims return math_ops.tensordot(images, kernel, axes=[[ndims - 1], [0]])
[ "def", "rgb_to_yuv", "(", "images", ")", ":", "images", "=", "ops", ".", "convert_to_tensor", "(", "images", ",", "name", "=", "'images'", ")", "kernel", "=", "ops", ".", "convert_to_tensor", "(", "_rgb_to_yuv_kernel", ",", "dtype", "=", "images", ".", "dt...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/image_ops_impl.py#L3925-L3946
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/generator.py
python
_CppFileWriterBase._predicate
(self, check_str, use_else_if=False, constexpr=False)
return writer.IndentedScopedBlock(self._writer, '%s (%s) {' % (conditional, check_str), '}')
Generate an if block if the condition is not-empty. Generate 'else if' instead of use_else_if is True.
Generate an if block if the condition is not-empty.
[ "Generate", "an", "if", "block", "if", "the", "condition", "is", "not", "-", "empty", "." ]
def _predicate(self, check_str, use_else_if=False, constexpr=False): # type: (str, bool, bool) -> Union[writer.IndentedScopedBlock,writer.EmptyBlock] """ Generate an if block if the condition is not-empty. Generate 'else if' instead of use_else_if is True. """ if not check_str: return writer.EmptyBlock() conditional = 'if' if use_else_if: conditional = 'else if' if constexpr: conditional = conditional + ' constexpr' return writer.IndentedScopedBlock(self._writer, '%s (%s) {' % (conditional, check_str), '}')
[ "def", "_predicate", "(", "self", ",", "check_str", ",", "use_else_if", "=", "False", ",", "constexpr", "=", "False", ")", ":", "# type: (str, bool, bool) -> Union[writer.IndentedScopedBlock,writer.EmptyBlock]", "if", "not", "check_str", ":", "return", "writer", ".", ...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/generator.py#L390-L407
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/math_ops.py
python
accumulate_n
(inputs, shape=None, tensor_dtype=None, name=None)
Returns the element-wise sum of a list of tensors. Optionally, pass `shape` and `tensor_dtype` for shape and type checking, otherwise, these are inferred. For example: ```python # tensor 'a' is [[1, 2], [3, 4]] # tensor `b` is [[5, 0], [0, 6]] tf.accumulate_n([a, b, a]) ==> [[7, 4], [6, 14]] # Explicitly pass shape and type tf.accumulate_n([a, b, a], shape=[2, 2], tensor_dtype=tf.int32) ==> [[7, 4], [6, 14]] ``` Args: inputs: A list of `Tensor` objects, each with same shape and type. shape: Shape of elements of `inputs`. tensor_dtype: The type of `inputs`. name: A name for the operation (optional). Returns: A `Tensor` of same shape and type as the elements of `inputs`. Raises: ValueError: If `inputs` don't all have same shape and dtype or the shape cannot be inferred.
Returns the element-wise sum of a list of tensors.
[ "Returns", "the", "element", "-", "wise", "sum", "of", "a", "list", "of", "tensors", "." ]
def accumulate_n(inputs, shape=None, tensor_dtype=None, name=None): """Returns the element-wise sum of a list of tensors. Optionally, pass `shape` and `tensor_dtype` for shape and type checking, otherwise, these are inferred. For example: ```python # tensor 'a' is [[1, 2], [3, 4]] # tensor `b` is [[5, 0], [0, 6]] tf.accumulate_n([a, b, a]) ==> [[7, 4], [6, 14]] # Explicitly pass shape and type tf.accumulate_n([a, b, a], shape=[2, 2], tensor_dtype=tf.int32) ==> [[7, 4], [6, 14]] ``` Args: inputs: A list of `Tensor` objects, each with same shape and type. shape: Shape of elements of `inputs`. tensor_dtype: The type of `inputs`. name: A name for the operation (optional). Returns: A `Tensor` of same shape and type as the elements of `inputs`. Raises: ValueError: If `inputs` don't all have same shape and dtype or the shape cannot be inferred. """ if tensor_dtype is None: if not inputs or not isinstance(inputs, (list, tuple)): raise ValueError("inputs must be a list of at least one Tensor with the " "same dtype and shape") inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs) if not all(isinstance(x, ops.Tensor) for x in inputs): raise ValueError("inputs must be a list of at least one Tensor with the " "same dtype and shape") if not all(x.dtype == inputs[0].dtype for x in inputs): raise ValueError("inputs must be a list of at least one Tensor with the " "same dtype and shape") tensor_dtype = inputs[0].dtype if shape is not None: shape = tensor_shape.as_shape(shape) else: shape = tensor_shape.unknown_shape() for input_tensor in inputs: if isinstance(input_tensor, ops.Tensor): shape = shape.merge_with(input_tensor.get_shape()) if not shape.is_fully_defined(): # TODO(pbar): Make a version of assign_add that accepts an uninitialized # lvalue, and takes its shape from that? This would allow accumulate_n to # work in all situations that add_n currently works. raise ValueError("Cannot infer the shape of the accumulator for " "accumulate_n. Pass the shape argument, or set the shape " "of at least one of the inputs.") with ops.op_scope(inputs, name, "AccumulateN") as name: if len(inputs) == 1: return inputs[0] var = gen_state_ops._temporary_variable(shape=shape, dtype=tensor_dtype) var_name = var.op.name var = state_ops.assign(var, array_ops.zeros_like(inputs[0])) update_ops = [] for input_tensor in inputs: op = state_ops.assign_add(var, input_tensor, use_locking=True) update_ops.append(op) with ops.control_dependencies(update_ops): return gen_state_ops._destroy_temporary_variable(var, var_name=var_name, name=name)
[ "def", "accumulate_n", "(", "inputs", ",", "shape", "=", "None", ",", "tensor_dtype", "=", "None", ",", "name", "=", "None", ")", ":", "if", "tensor_dtype", "is", "None", ":", "if", "not", "inputs", "or", "not", "isinstance", "(", "inputs", ",", "(", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L1475-L1545
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/modes/emacs.py
python
EmacsMode.transpose_chars
(self, e)
Drag the character before the cursor forward over the character at the cursor, moving the cursor forward as well. If the insertion point is at the end of the line, then this transposes the last two characters of the line. Negative arguments have no effect.
Drag the character before the cursor forward over the character at the cursor, moving the cursor forward as well. If the insertion point is at the end of the line, then this transposes the last two characters of the line. Negative arguments have no effect.
[ "Drag", "the", "character", "before", "the", "cursor", "forward", "over", "the", "character", "at", "the", "cursor", "moving", "the", "cursor", "forward", "as", "well", ".", "If", "the", "insertion", "point", "is", "at", "the", "end", "of", "the", "line", ...
def transpose_chars(self, e): # (C-t) '''Drag the character before the cursor forward over the character at the cursor, moving the cursor forward as well. If the insertion point is at the end of the line, then this transposes the last two characters of the line. Negative arguments have no effect.''' self.l_buffer.transpose_chars()
[ "def", "transpose_chars", "(", "self", ",", "e", ")", ":", "# (C-t)", "self", ".", "l_buffer", ".", "transpose_chars", "(", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/modes/emacs.py#L285-L290
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/servers/local_server.py
python
LocalServer.LocalJsonSearchHandler
(self, handler)
Handle GET request for json search results.
Handle GET request for json search results.
[ "Handle", "GET", "request", "for", "json", "search", "results", "." ]
def LocalJsonSearchHandler(self, handler): """Handle GET request for json search results.""" if not handler.IsValidRequest(): raise tornado.web.HTTPError(404) cb = handler.request.arguments["cb"][0] service = handler.request.arguments["service"][0] try: self.search_services_[service].JsonSearch(handler, cb) return except KeyError: pass # Search service has not been defined; use default. if "displayKeys" in handler.request.arguments.keys(): key = handler.request.arguments["displayKeys"][0] if key in handler.request.arguments.keys(): search_term = handler.request.arguments[key][0].lower() handler.write(tornado.web.globe_.search_db_.JsonSearch(search_term, cb))
[ "def", "LocalJsonSearchHandler", "(", "self", ",", "handler", ")", ":", "if", "not", "handler", ".", "IsValidRequest", "(", ")", ":", "raise", "tornado", ".", "web", ".", "HTTPError", "(", "404", ")", "cb", "=", "handler", ".", "request", ".", "arguments...
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/local_server.py#L373-L390
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/msw/gizmos.py
python
TreeListCtrl.GetLineSpacing
(*args, **kwargs)
return _gizmos.TreeListCtrl_GetLineSpacing(*args, **kwargs)
GetLineSpacing(self) -> unsigned int
GetLineSpacing(self) -> unsigned int
[ "GetLineSpacing", "(", "self", ")", "-", ">", "unsigned", "int" ]
def GetLineSpacing(*args, **kwargs): """GetLineSpacing(self) -> unsigned int""" return _gizmos.TreeListCtrl_GetLineSpacing(*args, **kwargs)
[ "def", "GetLineSpacing", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListCtrl_GetLineSpacing", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/msw/gizmos.py#L511-L513
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/ma/core.py
python
is_masked
(x)
return False
Determine whether input has masked values. Accepts any object as input, but always returns False unless the input is a MaskedArray containing masked values. Parameters ---------- x : array_like Array to check for masked values. Returns ------- result : bool True if `x` is a MaskedArray with masked values, False otherwise. Examples -------- >>> import numpy.ma as ma >>> x = ma.masked_equal([0, 1, 0, 2, 3], 0) >>> x masked_array(data = [-- 1 -- 2 3], mask = [ True False True False False], fill_value=999999) >>> ma.is_masked(x) True >>> x = ma.masked_equal([0, 1, 0, 2, 3], 42) >>> x masked_array(data = [0 1 0 2 3], mask = False, fill_value=999999) >>> ma.is_masked(x) False Always returns False if `x` isn't a MaskedArray. >>> x = [False, True, False] >>> ma.is_masked(x) False >>> x = 'a string' >>> ma.is_masked(x) False
Determine whether input has masked values.
[ "Determine", "whether", "input", "has", "masked", "values", "." ]
def is_masked(x): """ Determine whether input has masked values. Accepts any object as input, but always returns False unless the input is a MaskedArray containing masked values. Parameters ---------- x : array_like Array to check for masked values. Returns ------- result : bool True if `x` is a MaskedArray with masked values, False otherwise. Examples -------- >>> import numpy.ma as ma >>> x = ma.masked_equal([0, 1, 0, 2, 3], 0) >>> x masked_array(data = [-- 1 -- 2 3], mask = [ True False True False False], fill_value=999999) >>> ma.is_masked(x) True >>> x = ma.masked_equal([0, 1, 0, 2, 3], 42) >>> x masked_array(data = [0 1 0 2 3], mask = False, fill_value=999999) >>> ma.is_masked(x) False Always returns False if `x` isn't a MaskedArray. >>> x = [False, True, False] >>> ma.is_masked(x) False >>> x = 'a string' >>> ma.is_masked(x) False """ m = getmask(x) if m is nomask: return False elif m.any(): return True return False
[ "def", "is_masked", "(", "x", ")", ":", "m", "=", "getmask", "(", "x", ")", "if", "m", "is", "nomask", ":", "return", "False", "elif", "m", ".", "any", "(", ")", ":", "return", "True", "return", "False" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/core.py#L6381-L6431
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TIntHI.IsEmpty
(self)
return _snap.TIntHI_IsEmpty(self)
IsEmpty(TIntHI self) -> bool Parameters: self: THashKeyDatI< TInt,TInt > const *
IsEmpty(TIntHI self) -> bool
[ "IsEmpty", "(", "TIntHI", "self", ")", "-", ">", "bool" ]
def IsEmpty(self): """ IsEmpty(TIntHI self) -> bool Parameters: self: THashKeyDatI< TInt,TInt > const * """ return _snap.TIntHI_IsEmpty(self)
[ "def", "IsEmpty", "(", "self", ")", ":", "return", "_snap", ".", "TIntHI_IsEmpty", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L19037-L19045