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
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Task.py
python
set_file_constraints
(tasks)
Adds tasks to the task 'run_after' attribute based on the task inputs and outputs :param tasks: tasks :type tasks: list of :py:class:`waflib.Task.TaskBase`
Adds tasks to the task 'run_after' attribute based on the task inputs and outputs
[ "Adds", "tasks", "to", "the", "task", "run_after", "attribute", "based", "on", "the", "task", "inputs", "and", "outputs" ]
def set_file_constraints(tasks): """ Adds tasks to the task 'run_after' attribute based on the task inputs and outputs :param tasks: tasks :type tasks: list of :py:class:`waflib.Task.TaskBase` """ ins = Utils.defaultdict(set) outs = Utils.defaultdict(set) for x in tasks: for a in getattr(x, 'inputs', []) + getattr(x, 'dep_nodes', []): ins[id(a)].add(x) for a in getattr(x, 'outputs', []): outs[id(a)].add(x) links = set(ins.keys()).intersection(outs.keys()) for k in links: for a in ins[k]: a.run_after.update(outs[k])
[ "def", "set_file_constraints", "(", "tasks", ")", ":", "ins", "=", "Utils", ".", "defaultdict", "(", "set", ")", "outs", "=", "Utils", ".", "defaultdict", "(", "set", ")", "for", "x", "in", "tasks", ":", "for", "a", "in", "getattr", "(", "x", ",", ...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Task.py#L951-L969
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/random.py
python
Random.gammavariate
(self, alpha, beta)
Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. The probability distribution function is: x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha
Gamma distribution. Not the gamma function!
[ "Gamma", "distribution", ".", "Not", "the", "gamma", "function!" ]
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. The probability distribution function is: x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha """ # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2 # Warning: a few older sources define the gamma distribution in terms # of alpha > -1.0 if alpha <= 0.0 or beta <= 0.0: raise ValueError('gammavariate: alpha and beta must be > 0.0') random = self.random if alpha > 1.0: # Uses R.C.H. Cheng, "The generation of Gamma # variables with non-integral shape parameters", # Applied Statistics, (1977), 26, No. 1, p71-74 ainv = _sqrt(2.0 * alpha - 1.0) bbb = alpha - LOG4 ccc = alpha + ainv while 1: u1 = random() if not 1e-7 < u1 < .9999999: continue u2 = 1.0 - random() v = _log(u1/(1.0-u1))/ainv x = alpha*_exp(v) z = u1*u1*u2 r = bbb+ccc*v-x if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z): return x * beta elif alpha == 1.0: # expovariate(1/beta) u = random() while u <= 1e-7: u = random() return -_log(u) * beta else: # alpha is between 0 and 1 (exclusive) # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle while 1: u = random() b = (_e + alpha)/_e p = b*u if p <= 1.0: x = p ** (1.0/alpha) else: x = -_log((b-p)/alpha) u1 = random() if p > 1.0: if u1 <= x ** (alpha - 1.0): break elif u1 <= _exp(-x): break return x * beta
[ "def", "gammavariate", "(", "self", ",", "alpha", ",", "beta", ")", ":", "# alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2", "# Warning: a few older sources define the gamma distribution in terms", "# of alpha > -1.0", "if", "alpha", "<=", "0.0", "or", "beta",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/random.py#L504-L572
mingchen/protobuf-ios
0958df34558cd54cb7b6e6ca5c8855bf3d475046
compiler/python/mox.py
python
MockMethod.AndReturn
(self, return_value)
return return_value
Set the value to return when this method is called. Args: # return_value can be anything.
Set the value to return when this method is called.
[ "Set", "the", "value", "to", "return", "when", "this", "method", "is", "called", "." ]
def AndReturn(self, return_value): """Set the value to return when this method is called. Args: # return_value can be anything. """ self._return_value = return_value return return_value
[ "def", "AndReturn", "(", "self", ",", "return_value", ")", ":", "self", ".", "_return_value", "=", "return_value", "return", "return_value" ]
https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/mox.py#L718-L726
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/customtreectrl.py
python
CustomTreeCtrl.CheckSameLevel
(self, item, checked=False)
Uncheck radio items which are on the same level of the checked one. Used internally. :param `item`: an instance of :class:`GenericTreeItem`; :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it. :note: This method is meaningful only for radiobutton-like items.
Uncheck radio items which are on the same level of the checked one. Used internally.
[ "Uncheck", "radio", "items", "which", "are", "on", "the", "same", "level", "of", "the", "checked", "one", ".", "Used", "internally", "." ]
def CheckSameLevel(self, item, checked=False): """ Uncheck radio items which are on the same level of the checked one. Used internally. :param `item`: an instance of :class:`GenericTreeItem`; :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it. :note: This method is meaningful only for radiobutton-like items. """ parent = item.GetParent() if not parent: return torefresh = False if parent.IsExpanded(): torefresh = True (child, cookie) = self.GetFirstChild(parent) while child: if child.GetType() == 2 and child != item: self.CheckItem2(child, checked, torefresh=torefresh) if child.GetType != 2 or (child.GetType() == 2 and child.IsChecked()): self.EnableChildren(child, checked) (child, cookie) = self.GetNextChild(parent, cookie)
[ "def", "CheckSameLevel", "(", "self", ",", "item", ",", "checked", "=", "False", ")", ":", "parent", "=", "item", ".", "GetParent", "(", ")", "if", "not", "parent", ":", "return", "torefresh", "=", "False", "if", "parent", ".", "IsExpanded", "(", ")", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L3361-L3387
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TBPGraph.GetRndLNId
(self, *args)
return _snap.TBPGraph_GetRndLNId(self, *args)
GetRndLNId(TBPGraph self, TRnd Rnd=Rnd) -> int Parameters: Rnd: TRnd & GetRndLNId(TBPGraph self) -> int Parameters: self: TBPGraph *
GetRndLNId(TBPGraph self, TRnd Rnd=Rnd) -> int
[ "GetRndLNId", "(", "TBPGraph", "self", "TRnd", "Rnd", "=", "Rnd", ")", "-", ">", "int" ]
def GetRndLNId(self, *args): """ GetRndLNId(TBPGraph self, TRnd Rnd=Rnd) -> int Parameters: Rnd: TRnd & GetRndLNId(TBPGraph self) -> int Parameters: self: TBPGraph * """ return _snap.TBPGraph_GetRndLNId(self, *args)
[ "def", "GetRndLNId", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TBPGraph_GetRndLNId", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L5165-L5178
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py
python
EC2Connection.get_all_instance_status
(self, instance_ids=None, max_results=None, next_token=None, filters=None, dry_run=False, include_all_instances=False)
return self.get_object('DescribeInstanceStatus', params, InstanceStatusSet, verb='POST')
Retrieve all the instances in your account scheduled for maintenance. :type instance_ids: list :param instance_ids: A list of strings of instance IDs :type max_results: int :param max_results: The maximum number of paginated instance items per response. :type next_token: str :param next_token: A string specifying the next paginated set of results to return. :type filters: dict :param filters: Optional filters that can be used to limit the results returned. Filters are provided in the form of a dictionary consisting of filter names as the key and filter values as the value. The set of allowable filter names/values is dependent on the request being performed. Check the EC2 API guide for details. :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :type include_all_instances: bool :param include_all_instances: Set to True if all instances should be returned. (Only running instances are included by default.) :rtype: list :return: A list of instances that have maintenance scheduled.
Retrieve all the instances in your account scheduled for maintenance.
[ "Retrieve", "all", "the", "instances", "in", "your", "account", "scheduled", "for", "maintenance", "." ]
def get_all_instance_status(self, instance_ids=None, max_results=None, next_token=None, filters=None, dry_run=False, include_all_instances=False): """ Retrieve all the instances in your account scheduled for maintenance. :type instance_ids: list :param instance_ids: A list of strings of instance IDs :type max_results: int :param max_results: The maximum number of paginated instance items per response. :type next_token: str :param next_token: A string specifying the next paginated set of results to return. :type filters: dict :param filters: Optional filters that can be used to limit the results returned. Filters are provided in the form of a dictionary consisting of filter names as the key and filter values as the value. The set of allowable filter names/values is dependent on the request being performed. Check the EC2 API guide for details. :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :type include_all_instances: bool :param include_all_instances: Set to True if all instances should be returned. (Only running instances are included by default.) :rtype: list :return: A list of instances that have maintenance scheduled. """ params = {} if instance_ids: self.build_list_params(params, instance_ids, 'InstanceId') if max_results: params['MaxResults'] = max_results if next_token: params['NextToken'] = next_token if filters: self.build_filter_params(params, filters) if dry_run: params['DryRun'] = 'true' if include_all_instances: params['IncludeAllInstances'] = 'true' return self.get_object('DescribeInstanceStatus', params, InstanceStatusSet, verb='POST')
[ "def", "get_all_instance_status", "(", "self", ",", "instance_ids", "=", "None", ",", "max_results", "=", "None", ",", "next_token", "=", "None", ",", "filters", "=", "None", ",", "dry_run", "=", "False", ",", "include_all_instances", "=", "False", ")", ":",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py#L683-L736
PyMesh/PyMesh
384ba882b7558ba6e8653ed263c419226c22bddf
python/pymesh/meshutils/generate_box_mesh.py
python
generate_box_mesh
(box_min, box_max, num_samples=1, keep_symmetry=False, subdiv_order=0, using_simplex=True)
return mesh
Generate axis-aligned box mesh. Each box is made of a number of cells (a square in 2D and cube in 3D), and each cell is made of triangles (2D) or tetrahedra (3D). Args: box_min (``numpy.ndarray``): min corner of the box. box_max (``numpy.ndarray``): max corner of the box. num_samples (``int``): (optional) Number of segments on each edge of the box. Default is 1. keep_symmetry (``bool``): (optional) If true, ensure mesh connectivity respect all reflective symmetries of the box. Default is true. subdiv_order (``int``): (optional) The subdivision order. Default is 0. using_simplex (``bool``): If true, build box using simplex elements (i.e. triangle or tets), otherwise, use quad or hex element. Returns: A box :py:class:`Mesh`. The following attributes are defined. * ``cell_index``: An :py:class:`numpy.ndarray` of size :math:`N_e` that maps each element to the index of the cell it belongs to. :math:`N_e` is the number of elements.
Generate axis-aligned box mesh.
[ "Generate", "axis", "-", "aligned", "box", "mesh", "." ]
def generate_box_mesh(box_min, box_max, num_samples=1, keep_symmetry=False, subdiv_order=0, using_simplex=True): """ Generate axis-aligned box mesh. Each box is made of a number of cells (a square in 2D and cube in 3D), and each cell is made of triangles (2D) or tetrahedra (3D). Args: box_min (``numpy.ndarray``): min corner of the box. box_max (``numpy.ndarray``): max corner of the box. num_samples (``int``): (optional) Number of segments on each edge of the box. Default is 1. keep_symmetry (``bool``): (optional) If true, ensure mesh connectivity respect all reflective symmetries of the box. Default is true. subdiv_order (``int``): (optional) The subdivision order. Default is 0. using_simplex (``bool``): If true, build box using simplex elements (i.e. triangle or tets), otherwise, use quad or hex element. Returns: A box :py:class:`Mesh`. The following attributes are defined. * ``cell_index``: An :py:class:`numpy.ndarray` of size :math:`N_e` that maps each element to the index of the cell it belongs to. :math:`N_e` is the number of elements. """ if not isinstance(box_min, np.ndarray): box_min = np.array(box_min) if not isinstance(box_max, np.ndarray): box_max = np.array(box_max) dim = len(box_min) if dim == 2: mesh, cell_index = generate_2D_box_mesh(box_min, box_max, num_samples, keep_symmetry, subdiv_order, using_simplex) elif dim == 3: mesh, cell_index = generate_3D_box_mesh(box_min, box_max, num_samples, keep_symmetry, subdiv_order, using_simplex) mesh.add_attribute("cell_index") mesh.set_attribute("cell_index", cell_index) return mesh
[ "def", "generate_box_mesh", "(", "box_min", ",", "box_max", ",", "num_samples", "=", "1", ",", "keep_symmetry", "=", "False", ",", "subdiv_order", "=", "0", ",", "using_simplex", "=", "True", ")", ":", "if", "not", "isinstance", "(", "box_min", ",", "np", ...
https://github.com/PyMesh/PyMesh/blob/384ba882b7558ba6e8653ed263c419226c22bddf/python/pymesh/meshutils/generate_box_mesh.py#L10-L49
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/ops.py
python
RegisterStatistics.__init__
(self, op_type, statistic_type)
Saves the `op_type` as the `Operation` type.
Saves the `op_type` as the `Operation` type.
[ "Saves", "the", "op_type", "as", "the", "Operation", "type", "." ]
def __init__(self, op_type, statistic_type): """Saves the `op_type` as the `Operation` type.""" if not isinstance(op_type, six.string_types): raise TypeError("op_type must be a string.") if "," in op_type: raise TypeError("op_type must not contain a comma.") self._op_type = op_type if not isinstance(statistic_type, six.string_types): raise TypeError("statistic_type must be a string.") if "," in statistic_type: raise TypeError("statistic_type must not contain a comma.") self._statistic_type = statistic_type
[ "def", "__init__", "(", "self", ",", "op_type", ",", "statistic_type", ")", ":", "if", "not", "isinstance", "(", "op_type", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "\"op_type must be a string.\"", ")", "if", "\",\"", "in", "op_t...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/ops.py#L2026-L2037
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/util/process_statistic_timeline_data.py
python
ProcessStatisticTimelineData.__sub__
(self, other)
return ret
The results of subtraction is an object holding only the pids contained in |self|. The motivation is that some processes may have died between two consecutive measurements. The desired behavior is to only make calculations based on the processes that are alive at the end of the second measurement.
The results of subtraction is an object holding only the pids contained in |self|.
[ "The", "results", "of", "subtraction", "is", "an", "object", "holding", "only", "the", "pids", "contained", "in", "|self|", "." ]
def __sub__(self, other): """The results of subtraction is an object holding only the pids contained in |self|. The motivation is that some processes may have died between two consecutive measurements. The desired behavior is to only make calculations based on the processes that are alive at the end of the second measurement.""" # pylint: disable=protected-access ret = self.__class__(0, 0) my_dict = self._value_by_pid ret._value_by_pid = ( {k: my_dict[k] - other._value_by_pid.get(k, 0) for k in my_dict.keys()}) return ret
[ "def", "__sub__", "(", "self", ",", "other", ")", ":", "# pylint: disable=protected-access", "ret", "=", "self", ".", "__class__", "(", "0", ",", "0", ")", "my_dict", "=", "self", ".", "_value_by_pid", "ret", ".", "_value_by_pid", "=", "(", "{", "k", ":"...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/util/process_statistic_timeline_data.py#L17-L31
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/demos/quotas/backend/quotas/services.py
python
QuotaState.abort_transaction
(self)
Roll back transaction ignoring quota changes.
Roll back transaction ignoring quota changes.
[ "Roll", "back", "transaction", "ignoring", "quota", "changes", "." ]
def abort_transaction(self): """Roll back transaction ignoring quota changes.""" assert self.in_transaction() self.__transaction.changes = None self.__lock.release()
[ "def", "abort_transaction", "(", "self", ")", ":", "assert", "self", ".", "in_transaction", "(", ")", "self", ".", "__transaction", ".", "changes", "=", "None", "self", ".", "__lock", ".", "release", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/demos/quotas/backend/quotas/services.py#L264-L268
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
PseudoDC.DrawPolygon
(*args, **kwargs)
return _gdi_.PseudoDC_DrawPolygon(*args, **kwargs)
DrawPolygon(self, List points, int xoffset=0, int yoffset=0, wxPolygonFillMode fillStyle=ODDEVEN_RULE) Draws a filled polygon using a sequence of `wx.Point` objects, adding the optional offset coordinate. The last argument specifies the fill rule: ``wx.ODDEVEN_RULE`` (the default) or ``wx.WINDING_RULE``. The current pen is used for drawing the outline, and the current brush for filling the shape. Using a transparent brush suppresses filling. Note that wxWidgets automatically closes the first and last points.
DrawPolygon(self, List points, int xoffset=0, int yoffset=0, wxPolygonFillMode fillStyle=ODDEVEN_RULE)
[ "DrawPolygon", "(", "self", "List", "points", "int", "xoffset", "=", "0", "int", "yoffset", "=", "0", "wxPolygonFillMode", "fillStyle", "=", "ODDEVEN_RULE", ")" ]
def DrawPolygon(*args, **kwargs): """ DrawPolygon(self, List points, int xoffset=0, int yoffset=0, wxPolygonFillMode fillStyle=ODDEVEN_RULE) Draws a filled polygon using a sequence of `wx.Point` objects, adding the optional offset coordinate. The last argument specifies the fill rule: ``wx.ODDEVEN_RULE`` (the default) or ``wx.WINDING_RULE``. The current pen is used for drawing the outline, and the current brush for filling the shape. Using a transparent brush suppresses filling. Note that wxWidgets automatically closes the first and last points. """ return _gdi_.PseudoDC_DrawPolygon(*args, **kwargs)
[ "def", "DrawPolygon", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "PseudoDC_DrawPolygon", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L8322-L8336
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/entrypoints/train.py
python
_do_work
(jdata: Dict[str, Any], run_opt: RunOptions, is_compress: bool = False)
Run serial model training. Parameters ---------- jdata : Dict[str, Any] arguments read form json/yaml control file run_opt : RunOptions object with run configuration is_compress : Bool indicates whether in model compress mode Raises ------ RuntimeError If unsupported modifier type is selected for model
Run serial model training.
[ "Run", "serial", "model", "training", "." ]
def _do_work(jdata: Dict[str, Any], run_opt: RunOptions, is_compress: bool = False): """Run serial model training. Parameters ---------- jdata : Dict[str, Any] arguments read form json/yaml control file run_opt : RunOptions object with run configuration is_compress : Bool indicates whether in model compress mode Raises ------ RuntimeError If unsupported modifier type is selected for model """ # make necessary checks assert "training" in jdata # init the model model = DPTrainer(jdata, run_opt=run_opt, is_compress = is_compress) rcut = model.model.get_rcut() type_map = model.model.get_type_map() if len(type_map) == 0: ipt_type_map = None else: ipt_type_map = type_map # init random seed of data systems seed = jdata["training"].get("seed", None) if seed is not None: # avoid the same batch sequence among workers seed += run_opt.my_rank seed = seed % (2 ** 32) dp_random.seed(seed) # setup data modifier modifier = get_modifier(jdata["model"].get("modifier", None)) # decouple the training data from the model compress process train_data = None valid_data = None if not is_compress: # init data train_data = get_data(jdata["training"]["training_data"], rcut, ipt_type_map, modifier) train_data.print_summary("training") if jdata["training"].get("validation_data", None) is not None: valid_data = get_data(jdata["training"]["validation_data"], rcut, ipt_type_map, modifier) valid_data.print_summary("validation") # get training info stop_batch = j_must_have(jdata["training"], "numb_steps") model.build(train_data, stop_batch) if not is_compress: # train the model with the provided systems in a cyclic way start_time = time.time() model.train(train_data, valid_data) end_time = time.time() log.info("finished training") log.info(f"wall time: {(end_time - start_time):.3f} s") else: model.save_compressed() log.info("finished compressing")
[ "def", "_do_work", "(", "jdata", ":", "Dict", "[", "str", ",", "Any", "]", ",", "run_opt", ":", "RunOptions", ",", "is_compress", ":", "bool", "=", "False", ")", ":", "# make necessary checks", "assert", "\"training\"", "in", "jdata", "# init the model", "mo...
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/entrypoints/train.py#L106-L170
vmware/concord-bft
ec036a384b4c81be0423d4b429bd37900b13b864
util/pyclient/bft_metrics_client.py
python
MetricsClient._req
(self)
return req
Return a get request to the metrics server
Return a get request to the metrics server
[ "Return", "a", "get", "request", "to", "the", "metrics", "server" ]
def _req(self): """Return a get request to the metrics server""" self.seq_num += 1 req = struct.pack(HEADER_FMT, REQUEST_TYPE, self.seq_num) return req
[ "def", "_req", "(", "self", ")", ":", "self", ".", "seq_num", "+=", "1", "req", "=", "struct", ".", "pack", "(", "HEADER_FMT", ",", "REQUEST_TYPE", ",", "self", ".", "seq_num", ")", "return", "req" ]
https://github.com/vmware/concord-bft/blob/ec036a384b4c81be0423d4b429bd37900b13b864/util/pyclient/bft_metrics_client.py#L43-L47
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_tensor_shape.py
python
RaggedTensorDynamicShape._broadcast_inner_dimension_to_uniform
(self, axis, length)
return RaggedTensorDynamicShape(partitioned_sizes, inner_sizes)
Broadcasts the inner dimension `axis` to match `lengths`.
Broadcasts the inner dimension `axis` to match `lengths`.
[ "Broadcasts", "the", "inner", "dimension", "axis", "to", "match", "lengths", "." ]
def _broadcast_inner_dimension_to_uniform(self, axis, length): """Broadcasts the inner dimension `axis` to match `lengths`.""" dim_size = self.dimension_size(axis) axis_in_inner_dims = axis - self.num_partitioned_dimensions partitioned_sizes = self._partitioned_dim_sizes inner_sizes = array_ops.concat([ self._inner_dim_sizes[:axis_in_inner_dims], [array_ops.where(math_ops.equal(dim_size, 1), length, dim_size)], self._inner_dim_sizes[axis_in_inner_dims + 1:] ], axis=0) return RaggedTensorDynamicShape(partitioned_sizes, inner_sizes)
[ "def", "_broadcast_inner_dimension_to_uniform", "(", "self", ",", "axis", ",", "length", ")", ":", "dim_size", "=", "self", ".", "dimension_size", "(", "axis", ")", "axis_in_inner_dims", "=", "axis", "-", "self", ".", "num_partitioned_dimensions", "partitioned_sizes...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_tensor_shape.py#L412-L423
CGRU/cgru
1881a4128530e3d31ac6c25314c18314fc50c2c7
afanasy/python/af.py
python
checkRegExp
(pattern)
return result
Missing DocString :param pattern: :return:
Missing DocString
[ "Missing", "DocString" ]
def checkRegExp(pattern): """Missing DocString :param pattern: :return: """ if len(pattern) == 0: return False result = True try: re.compile(pattern) except re.error: print('Error: Invalid regular expression pattern "%s"' % pattern) print(str(sys.exc_info()[1])) result = False return result
[ "def", "checkRegExp", "(", "pattern", ")", ":", "if", "len", "(", "pattern", ")", "==", "0", ":", "return", "False", "result", "=", "True", "try", ":", "re", ".", "compile", "(", "pattern", ")", "except", "re", ".", "error", ":", "print", "(", "'Er...
https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/af.py#L19-L35
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/series.py
python
Series.axes
(self)
return [self.index]
Return a list of the row axis labels.
Return a list of the row axis labels.
[ "Return", "a", "list", "of", "the", "row", "axis", "labels", "." ]
def axes(self): """ Return a list of the row axis labels. """ return [self.index]
[ "def", "axes", "(", "self", ")", ":", "return", "[", "self", ".", "index", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/series.py#L797-L801
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/_pslinux.py
python
boot_time
()
Return the system boot time expressed in seconds since the epoch.
Return the system boot time expressed in seconds since the epoch.
[ "Return", "the", "system", "boot", "time", "expressed", "in", "seconds", "since", "the", "epoch", "." ]
def boot_time(): """Return the system boot time expressed in seconds since the epoch.""" global BOOT_TIME f = open('/proc/stat', 'rb') try: BTIME = b('btime') for line in f: if line.startswith(BTIME): ret = float(line.strip().split()[1]) BOOT_TIME = ret return ret raise RuntimeError("line 'btime' not found") finally: f.close()
[ "def", "boot_time", "(", ")", ":", "global", "BOOT_TIME", "f", "=", "open", "(", "'/proc/stat'", ",", "'rb'", ")", "try", ":", "BTIME", "=", "b", "(", "'btime'", ")", "for", "line", "in", "f", ":", "if", "line", ".", "startswith", "(", "BTIME", ")"...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/_pslinux.py#L332-L345
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/data_flow_ops.py
python
BaseStagingArea.dtypes
(self)
return self._dtypes
The list of dtypes for each component of a staging area element.
The list of dtypes for each component of a staging area element.
[ "The", "list", "of", "dtypes", "for", "each", "component", "of", "a", "staging", "area", "element", "." ]
def dtypes(self): """The list of dtypes for each component of a staging area element.""" return self._dtypes
[ "def", "dtypes", "(", "self", ")", ":", "return", "self", ".", "_dtypes" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/data_flow_ops.py#L1438-L1440
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/dist.py
python
fix_help_options
(options)
return new_options
Convert a 4-tuple 'help_options' list as found in various command classes to the 3-tuple form required by FancyGetopt.
Convert a 4-tuple 'help_options' list as found in various command classes to the 3-tuple form required by FancyGetopt.
[ "Convert", "a", "4", "-", "tuple", "help_options", "list", "as", "found", "in", "various", "command", "classes", "to", "the", "3", "-", "tuple", "form", "required", "by", "FancyGetopt", "." ]
def fix_help_options(options): """Convert a 4-tuple 'help_options' list as found in various command classes to the 3-tuple form required by FancyGetopt. """ new_options = [] for help_tuple in options: new_options.append(help_tuple[0:3]) return new_options
[ "def", "fix_help_options", "(", "options", ")", ":", "new_options", "=", "[", "]", "for", "help_tuple", "in", "options", ":", "new_options", ".", "append", "(", "help_tuple", "[", "0", ":", "3", "]", ")", "return", "new_options" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/dist.py#L1249-L1256
weichengkuo/DeepBox
c4f8c065b6a51cf296540cc453a44f0519aaacc9
src/datasets/coco_imdb.py
python
coco_imdb.proposals_roidb
(self)
return roidb
Return the database of Edge box regions of interest. Ground-truth ROIs are also included. This function loads/saves from/to a cache file to speed up future calls.
Return the database of Edge box regions of interest. Ground-truth ROIs are also included.
[ "Return", "the", "database", "of", "Edge", "box", "regions", "of", "interest", ".", "Ground", "-", "truth", "ROIs", "are", "also", "included", "." ]
def proposals_roidb(self): """ Return the database of Edge box regions of interest. Ground-truth ROIs are also included. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path,self.name + '_'+self._obj_proposer+'_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{} eb roidb loaded from {}'.format(self.name, cache_file) return roidb if self._image_set in ['train','val']: gt_roidb = self.gt_roidb() proposals_roidb = self._load_proposals_roidb(gt_roidb) roidb = datasets.imdb.merge_roidbs(gt_roidb, proposals_roidb) else: roidb = self._load_image_info_roidb() with open(cache_file, 'wb') as fid: cPickle.dump(roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote {} roidb to {}'.format(self._obj_proposer,cache_file) return roidb
[ "def", "proposals_roidb", "(", "self", ")", ":", "cache_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cache_path", ",", "self", ".", "name", "+", "'_'", "+", "self", ".", "_obj_proposer", "+", "'_roidb.pkl'", ")", "if", "os", ".", "p...
https://github.com/weichengkuo/DeepBox/blob/c4f8c065b6a51cf296540cc453a44f0519aaacc9/src/datasets/coco_imdb.py#L122-L147
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
Type.get_result
(self)
return conf.lib.clang_getResultType(self)
Retrieve the result type associated with a function type.
Retrieve the result type associated with a function type.
[ "Retrieve", "the", "result", "type", "associated", "with", "a", "function", "type", "." ]
def get_result(self): """ Retrieve the result type associated with a function type. """ return conf.lib.clang_getResultType(self)
[ "def", "get_result", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getResultType", "(", "self", ")" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1610-L1614
GoSSIP-SJTU/Armariris
ad5d868482956b2194a77b39c8d543c7c2318200
bindings/python/llvm/object.py
python
Section.size
(self)
return lib.LLVMGetSectionSize(self)
The size of the section, in long bytes.
The size of the section, in long bytes.
[ "The", "size", "of", "the", "section", "in", "long", "bytes", "." ]
def size(self): """The size of the section, in long bytes.""" if self.expired: raise Exception('Section instance has expired.') return lib.LLVMGetSectionSize(self)
[ "def", "size", "(", "self", ")", ":", "if", "self", ".", "expired", ":", "raise", "Exception", "(", "'Section instance has expired.'", ")", "return", "lib", ".", "LLVMGetSectionSize", "(", "self", ")" ]
https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/bindings/python/llvm/object.py#L205-L210
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/third_party/jinja2/filters.py
python
do_upper
(s)
return soft_unicode(s).upper()
Convert a value to uppercase.
Convert a value to uppercase.
[ "Convert", "a", "value", "to", "uppercase", "." ]
def do_upper(s): """Convert a value to uppercase.""" return soft_unicode(s).upper()
[ "def", "do_upper", "(", "s", ")", ":", "return", "soft_unicode", "(", "s", ")", ".", "upper", "(", ")" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/filters.py#L129-L131
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/utils/cli_parser.py
python
get_tf_cli_parser
(parser: argparse.ArgumentParser = None)
return parser
Specifies cli arguments for Model Optimizer for TF Returns ------- ArgumentParser instance
Specifies cli arguments for Model Optimizer for TF
[ "Specifies", "cli", "arguments", "for", "Model", "Optimizer", "for", "TF" ]
def get_tf_cli_parser(parser: argparse.ArgumentParser = None): """ Specifies cli arguments for Model Optimizer for TF Returns ------- ArgumentParser instance """ if not parser: parser = argparse.ArgumentParser(usage='%(prog)s [options]') get_common_cli_parser(parser=parser) tf_group = parser.add_argument_group('TensorFlow*-specific parameters') tf_group.add_argument('--input_model_is_text', help='TensorFlow*: treat the input model file as a text protobuf format. If not specified, ' + 'the Model Optimizer treats it as a binary file by default.', action='store_true') tf_group.add_argument('--input_checkpoint', type=str, default=None, help="TensorFlow*: variables file to load.", action=CanonicalizePathCheckExistenceAction) tf_group.add_argument('--input_meta_graph', help='Tensorflow*: a file with a meta-graph of the model before freezing', action=CanonicalizePathCheckExistenceAction, type=readable_file) tf_group.add_argument('--saved_model_dir', default=None, help='TensorFlow*: directory with a model in SavedModel format ' 'of TensorFlow 1.x or 2.x version.', action=CanonicalizePathCheckExistenceAction, type=readable_dirs) tf_group.add_argument('--saved_model_tags', type=str, default=None, help="Group of tag(s) of the MetaGraphDef to load, in string format, separated by ','. " "For tag-set contains multiple tags, all tags must be passed in.") tf_group.add_argument('--tensorflow_custom_operations_config_update', help='TensorFlow*: update the configuration file with node name patterns with input/output ' 'nodes information.', action=CanonicalizePathCheckExistenceAction) tf_group.add_argument('--tensorflow_use_custom_operations_config', help='Use the configuration file with custom operation description.', action=DeprecatedCanonicalizePathCheckExistenceAction) tf_group.add_argument('--tensorflow_object_detection_api_pipeline_config', help='TensorFlow*: path to the pipeline configuration file used to generate model created ' 'with help of Object Detection API.', action=CanonicalizePathCheckExistenceAction) tf_group.add_argument('--tensorboard_logdir', help='TensorFlow*: dump the input graph to a given directory that should be used with TensorBoard.', default=None, action=CanonicalizePathCheckExistenceAction) tf_group.add_argument('--tensorflow_custom_layer_libraries', help='TensorFlow*: comma separated list of shared libraries with TensorFlow* custom ' 'operations implementation.', default=None, action=CanonicalizePathCheckExistenceAction) tf_group.add_argument('--disable_nhwc_to_nchw', help='[DEPRECATED] Disables the default translation from NHWC to NCHW. Since 2022.1 this option ' 'is deprecated and used only to maintain backward compatibility with previous releases.', action='store_true') return parser
[ "def", "get_tf_cli_parser", "(", "parser", ":", "argparse", ".", "ArgumentParser", "=", "None", ")", ":", "if", "not", "parser", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "usage", "=", "'%(prog)s [options]'", ")", "get_common_cli_parser", "(", ...
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/utils/cli_parser.py#L604-L659
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/datetime.py
python
date.strftime
(self, fmt)
return _wrap_strftime(self, fmt, self.timetuple())
Format using strftime().
Format using strftime().
[ "Format", "using", "strftime", "()", "." ]
def strftime(self, fmt): "Format using strftime()." return _wrap_strftime(self, fmt, self.timetuple())
[ "def", "strftime", "(", "self", ",", "fmt", ")", ":", "return", "_wrap_strftime", "(", "self", ",", "fmt", ",", "self", ".", "timetuple", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/datetime.py#L905-L907
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/filepost.py
python
choose_boundary
()
return boundary
Our embarrassingly-simple replacement for mimetools.choose_boundary.
Our embarrassingly-simple replacement for mimetools.choose_boundary.
[ "Our", "embarrassingly", "-", "simple", "replacement", "for", "mimetools", ".", "choose_boundary", "." ]
def choose_boundary(): """ Our embarrassingly-simple replacement for mimetools.choose_boundary. """ boundary = binascii.hexlify(os.urandom(16)) if not six.PY2: boundary = boundary.decode("ascii") return boundary
[ "def", "choose_boundary", "(", ")", ":", "boundary", "=", "binascii", ".", "hexlify", "(", "os", ".", "urandom", "(", "16", ")", ")", "if", "not", "six", ".", "PY2", ":", "boundary", "=", "boundary", ".", "decode", "(", "\"ascii\"", ")", "return", "b...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/filepost.py#L15-L22
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/cephadm/module.py
python
CephadmOrchestrator.config_notify
(self)
This method is called whenever one of our config options is changed. TODO: this method should be moved into mgr_module.py
This method is called whenever one of our config options is changed.
[ "This", "method", "is", "called", "whenever", "one", "of", "our", "config", "options", "is", "changed", "." ]
def config_notify(self) -> None: """ This method is called whenever one of our config options is changed. TODO: this method should be moved into mgr_module.py """ for opt in self.MODULE_OPTIONS: setattr(self, opt['name'], # type: ignore self.get_module_option(opt['name'])) # type: ignore self.log.debug(' mgr option %s = %s', opt['name'], getattr(self, opt['name'])) # type: ignore for opt in self.NATIVE_OPTIONS: setattr(self, opt, # type: ignore self.get_ceph_option(opt)) self.log.debug(' native option %s = %s', opt, getattr(self, opt)) # type: ignore self.event.set()
[ "def", "config_notify", "(", "self", ")", "->", "None", ":", "for", "opt", "in", "self", ".", "MODULE_OPTIONS", ":", "setattr", "(", "self", ",", "opt", "[", "'name'", "]", ",", "# type: ignore", "self", ".", "get_module_option", "(", "opt", "[", "'name'...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/cephadm/module.py#L579-L597
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/python_gflags/gflags.py
python
DEFINE_multistring
(name, default, help, flag_values=FLAGS, **args)
Registers a flag whose value can be a list of any strings. Use the flag on the command line multiple times to place multiple string values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings.
Registers a flag whose value can be a list of any strings.
[ "Registers", "a", "flag", "whose", "value", "can", "be", "a", "list", "of", "any", "strings", "." ]
def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of any strings. Use the flag on the command line multiple times to place multiple string values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings. """ parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
[ "def", "DEFINE_multistring", "(", "name", ",", "default", ",", "help", ",", "flag_values", "=", "FLAGS", ",", "*", "*", "args", ")", ":", "parser", "=", "ArgumentParser", "(", ")", "serializer", "=", "ArgumentSerializer", "(", ")", "DEFINE_multi", "(", "pa...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/python_gflags/gflags.py#L2799-L2809
openmm/openmm
cb293447c4fc8b03976dfe11399f107bab70f3d9
wrappers/python/openmm/app/topology.py
python
Topology.setPeriodicBoxVectors
(self, vectors)
Set the vectors defining the periodic box.
Set the vectors defining the periodic box.
[ "Set", "the", "vectors", "defining", "the", "periodic", "box", "." ]
def setPeriodicBoxVectors(self, vectors): """Set the vectors defining the periodic box.""" if vectors is not None: if not is_quantity(vectors[0][0]): vectors = vectors*nanometers if vectors[0][1] != 0*nanometers or vectors[0][2] != 0*nanometers: raise ValueError("First periodic box vector must be parallel to x."); if vectors[1][2] != 0*nanometers: raise ValueError("Second periodic box vector must be in the x-y plane."); if vectors[0][0] <= 0*nanometers or vectors[1][1] <= 0*nanometers or vectors[2][2] <= 0*nanometers or vectors[0][0] < 2*abs(vectors[1][0]) or vectors[0][0] < 2*abs(vectors[2][0]) or vectors[1][1] < 2*abs(vectors[2][1]): raise ValueError("Periodic box vectors must be in reduced form."); self._periodicBoxVectors = deepcopy(vectors)
[ "def", "setPeriodicBoxVectors", "(", "self", ",", "vectors", ")", ":", "if", "vectors", "is", "not", "None", ":", "if", "not", "is_quantity", "(", "vectors", "[", "0", "]", "[", "0", "]", ")", ":", "vectors", "=", "vectors", "*", "nanometers", "if", ...
https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/topology.py#L242-L253
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/tpu/tpu_embedding.py
python
TPUEmbedding.num_cores_per_host
(self)
return self._num_cores_per_host
Number of TPU cores on a CPU host. Returns: Number of TPU cores on a CPU host.
Number of TPU cores on a CPU host.
[ "Number", "of", "TPU", "cores", "on", "a", "CPU", "host", "." ]
def num_cores_per_host(self): """Number of TPU cores on a CPU host. Returns: Number of TPU cores on a CPU host. """ return self._num_cores_per_host
[ "def", "num_cores_per_host", "(", "self", ")", ":", "return", "self", ".", "_num_cores_per_host" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/tpu_embedding.py#L1480-L1486
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
DPGAnalysis/HcalTools/scripts/cmt/das_client.py
python
prim_value
(row)
Extract primary key value from DAS record
Extract primary key value from DAS record
[ "Extract", "primary", "key", "value", "from", "DAS", "record" ]
def prim_value(row): """Extract primary key value from DAS record""" prim_key = row['das']['primary_key'] if prim_key == 'summary': return row.get(prim_key, None) key, att = prim_key.split('.') if isinstance(row[key], list): for item in row[key]: if att in item: return item[att] else: if key in row: if att in row[key]: return row[key][att]
[ "def", "prim_value", "(", "row", ")", ":", "prim_key", "=", "row", "[", "'das'", "]", "[", "'primary_key'", "]", "if", "prim_key", "==", "'summary'", ":", "return", "row", ".", "get", "(", "prim_key", ",", "None", ")", "key", ",", "att", "=", "prim_k...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DPGAnalysis/HcalTools/scripts/cmt/das_client.py#L350-L363
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/ao/quantization/quantize.py
python
_convert
( module, mapping=None, inplace=False, convert_custom_config_dict=None)
return module
r"""Converts submodules in input module to a different module according to `mapping` by calling `from_float` method on the target module class Args: module: input module mapping: a dictionary that maps from source module type to target module type, can be overwritten to allow swapping user defined Modules inplace: carry out model transformations in-place, the original module is mutated
r"""Converts submodules in input module to a different module according to `mapping` by calling `from_float` method on the target module class
[ "r", "Converts", "submodules", "in", "input", "module", "to", "a", "different", "module", "according", "to", "mapping", "by", "calling", "from_float", "method", "on", "the", "target", "module", "class" ]
def _convert( module, mapping=None, inplace=False, convert_custom_config_dict=None): r"""Converts submodules in input module to a different module according to `mapping` by calling `from_float` method on the target module class Args: module: input module mapping: a dictionary that maps from source module type to target module type, can be overwritten to allow swapping user defined Modules inplace: carry out model transformations in-place, the original module is mutated """ if mapping is None: mapping = get_default_static_quant_module_mappings() if convert_custom_config_dict is None: convert_custom_config_dict = {} custom_module_class_mapping = convert_custom_config_dict.get("observed_to_quantized_custom_module_class", {}) if not inplace: module = copy.deepcopy(module) reassign = {} for name, mod in module.named_children(): # both fused modules and observed custom modules are # swapped as one unit if not isinstance(mod, _FusedModule) and \ type(mod) not in custom_module_class_mapping: _convert(mod, mapping, True, # inplace convert_custom_config_dict) reassign[name] = swap_module(mod, mapping, custom_module_class_mapping) for key, value in reassign.items(): module._modules[key] = value return module
[ "def", "_convert", "(", "module", ",", "mapping", "=", "None", ",", "inplace", "=", "False", ",", "convert_custom_config_dict", "=", "None", ")", ":", "if", "mapping", "is", "None", ":", "mapping", "=", "get_default_static_quant_module_mappings", "(", ")", "if...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/quantize.py#L512-L548
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
ToolBarBase.GetToolByPos
(*args, **kwargs)
return _controls_.ToolBarBase_GetToolByPos(*args, **kwargs)
GetToolByPos(self, int pos) -> ToolBarToolBase
GetToolByPos(self, int pos) -> ToolBarToolBase
[ "GetToolByPos", "(", "self", "int", "pos", ")", "-", ">", "ToolBarToolBase" ]
def GetToolByPos(*args, **kwargs): """GetToolByPos(self, int pos) -> ToolBarToolBase""" return _controls_.ToolBarBase_GetToolByPos(*args, **kwargs)
[ "def", "GetToolByPos", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ToolBarBase_GetToolByPos", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L3923-L3925
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/code_coverage/coverage_posix.py
python
Coverage.AfterRunOneTest
(self, testname)
Do things right after running each test.
Do things right after running each test.
[ "Do", "things", "right", "after", "running", "each", "test", "." ]
def AfterRunOneTest(self, testname): """Do things right after running each test.""" if not self.IsWindows(): return # Stop counters cmdlist = [self.perf, '-shutdown'] self.Run(cmdlist) full_output = self.vsts_output + '.coverage' shutil.move(full_output, self.vsts_output) # generate lcov! self.GenerateLcovWindows(testname)
[ "def", "AfterRunOneTest", "(", "self", ",", "testname", ")", ":", "if", "not", "self", ".", "IsWindows", "(", ")", ":", "return", "# Stop counters", "cmdlist", "=", "[", "self", ".", "perf", ",", "'-shutdown'", "]", "self", ".", "Run", "(", "cmdlist", ...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/code_coverage/coverage_posix.py#L717-L727
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/serial/serialposix.py
python
Serial.write
(self, data)
return length - len(d)
Output the given byte string over the serial port.
Output the given byte string over the serial port.
[ "Output", "the", "given", "byte", "string", "over", "the", "serial", "port", "." ]
def write(self, data): """Output the given byte string over the serial port.""" if not self.is_open: raise portNotOpenError d = to_bytes(data) tx_len = length = len(d) timeout = Timeout(self._write_timeout) while tx_len > 0: try: n = os.write(self.fd, d) if timeout.is_non_blocking: # Zero timeout indicates non-blocking - simply return the # number of bytes of data actually written return n elif not timeout.is_infinite: # when timeout is set, use select to wait for being ready # with the time left as timeout if timeout.expired(): raise writeTimeoutError abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], timeout.time_left()) if abort: os.read(self.pipe_abort_write_r, 1000) break if not ready: raise writeTimeoutError else: assert timeout.time_left() is None # wait for write operation abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], None) if abort: os.read(self.pipe_abort_write_r, 1) break if not ready: raise SerialException('write failed (select)') d = d[n:] tx_len -= n except SerialException: raise except OSError as e: # this is for Python 3.x where select.error is a subclass of # OSError ignore BlockingIOErrors and EINTR. other errors are shown # https://www.python.org/dev/peps/pep-0475. if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR): raise SerialException('write failed: {}'.format(e)) except select.error as e: # this is for Python 2.x # ignore BlockingIOErrors and EINTR. all errors are shown # see also http://www.python.org/dev/peps/pep-3151/#select if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR): raise SerialException('write failed: {}'.format(e)) if not timeout.is_non_blocking and timeout.expired(): raise writeTimeoutError return length - len(d)
[ "def", "write", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "is_open", ":", "raise", "portNotOpenError", "d", "=", "to_bytes", "(", "data", ")", "tx_len", "=", "length", "=", "len", "(", "d", ")", "timeout", "=", "Timeout", "(", "...
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialposix.py#L528-L580
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/msvs_emulation.py
python
GetGlobalVSMacroEnv
(vs_version)
return env
Get a dict of variables mapping internal VS macro names to their gyp equivalents. Returns all variables that are independent of the target.
Get a dict of variables mapping internal VS macro names to their gyp equivalents. Returns all variables that are independent of the target.
[ "Get", "a", "dict", "of", "variables", "mapping", "internal", "VS", "macro", "names", "to", "their", "gyp", "equivalents", ".", "Returns", "all", "variables", "that", "are", "independent", "of", "the", "target", "." ]
def GetGlobalVSMacroEnv(vs_version): """Get a dict of variables mapping internal VS macro names to their gyp equivalents. Returns all variables that are independent of the target.""" env = {} # '$(VSInstallDir)' and '$(VCInstallDir)' are available when and only when # Visual Studio is actually installed. if vs_version.Path(): env['$(VSInstallDir)'] = vs_version.Path() env['$(VCInstallDir)'] = os.path.join(vs_version.Path(), 'VC') + '\\' # Chromium uses DXSDK_DIR in include/lib paths, but it may or may not be # set. This happens when the SDK is sync'd via src-internal, rather than # by typical end-user installation of the SDK. If it's not set, we don't # want to leave the unexpanded variable in the path, so simply strip it. dxsdk_dir = _FindDirectXInstallation() env['$(DXSDK_DIR)'] = dxsdk_dir if dxsdk_dir else '' # Try to find an installation location for the Windows DDK by checking # the WDK_DIR environment variable, may be None. env['$(WDK_DIR)'] = os.environ.get('WDK_DIR', '') return env
[ "def", "GetGlobalVSMacroEnv", "(", "vs_version", ")", ":", "env", "=", "{", "}", "# '$(VSInstallDir)' and '$(VCInstallDir)' are available when and only when", "# Visual Studio is actually installed.", "if", "vs_version", ".", "Path", "(", ")", ":", "env", "[", "'$(VSInstall...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/msvs_emulation.py#L146-L164
nasa/meshNetwork
ff4bd66e0ca6bd424fd8897a97252bb3925d8b3c
python/mesh/generic/cmdDict.py
python
serialize_NodeCmds_CmdResponse
(cmdData, timestamp)
return pack(NodeCmdDict[NodeCmds['CmdResponse']].packFormat, cmdData['cmdId'], cmdData['cmdCounter'], cmdData['cmdResponse'])
Method for serializing NodeCmds['CmdReponse'] command for serial transmission.
Method for serializing NodeCmds['CmdReponse'] command for serial transmission.
[ "Method", "for", "serializing", "NodeCmds", "[", "CmdReponse", "]", "command", "for", "serial", "transmission", "." ]
def serialize_NodeCmds_CmdResponse(cmdData, timestamp): """Method for serializing NodeCmds['CmdReponse'] command for serial transmission.""" return pack(NodeCmdDict[NodeCmds['CmdResponse']].packFormat, cmdData['cmdId'], cmdData['cmdCounter'], cmdData['cmdResponse'])
[ "def", "serialize_NodeCmds_CmdResponse", "(", "cmdData", ",", "timestamp", ")", ":", "return", "pack", "(", "NodeCmdDict", "[", "NodeCmds", "[", "'CmdResponse'", "]", "]", ".", "packFormat", ",", "cmdData", "[", "'cmdId'", "]", ",", "cmdData", "[", "'cmdCounte...
https://github.com/nasa/meshNetwork/blob/ff4bd66e0ca6bd424fd8897a97252bb3925d8b3c/python/mesh/generic/cmdDict.py#L10-L12
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
uCSIsCatPd
(code)
return ret
Check whether the character is part of Pd UCS Category
Check whether the character is part of Pd UCS Category
[ "Check", "whether", "the", "character", "is", "part", "of", "Pd", "UCS", "Category" ]
def uCSIsCatPd(code): """Check whether the character is part of Pd UCS Category """ ret = libxml2mod.xmlUCSIsCatPd(code) return ret
[ "def", "uCSIsCatPd", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsCatPd", "(", "code", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L2349-L2352
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
python/benchmarks/common.py
python
BuiltinsGenerator.generate_float_list
(self, n, none_prob=DEFAULT_NONE_PROB, use_nan=False)
return data
Generate a list of Python floats with *none_prob* probability of an entry being None (or NaN if *use_nan* is true).
Generate a list of Python floats with *none_prob* probability of an entry being None (or NaN if *use_nan* is true).
[ "Generate", "a", "list", "of", "Python", "floats", "with", "*", "none_prob", "*", "probability", "of", "an", "entry", "being", "None", "(", "or", "NaN", "if", "*", "use_nan", "*", "is", "true", ")", "." ]
def generate_float_list(self, n, none_prob=DEFAULT_NONE_PROB, use_nan=False): """ Generate a list of Python floats with *none_prob* probability of an entry being None (or NaN if *use_nan* is true). """ # Make sure we get Python floats, not np.float64 data = list(map(float, self.rnd.uniform(0.0, 1.0, n))) assert len(data) == n self.sprinkle(data, none_prob, value=float('nan') if use_nan else None) return data
[ "def", "generate_float_list", "(", "self", ",", "n", ",", "none_prob", "=", "DEFAULT_NONE_PROB", ",", "use_nan", "=", "False", ")", ":", "# Make sure we get Python floats, not np.float64", "data", "=", "list", "(", "map", "(", "float", ",", "self", ".", "rnd", ...
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/benchmarks/common.py#L136-L146
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pyedbglib/protocols/cmsisdap.py
python
CmsisDapDebugger.read_word
(self, address)
return self.dap_read_reg(self.SWD_AP_DRW | self.DAP_TRANSFER_APnDP)
Reads a word from the device memory bus :param address: address to read
Reads a word from the device memory bus
[ "Reads", "a", "word", "from", "the", "device", "memory", "bus" ]
def read_word(self, address): """ Reads a word from the device memory bus :param address: address to read """ self.logger.debug("read word at 0x%08X", address) self.dap_write_reg(self.SWD_AP_TAR | self.DAP_TRANSFER_APnDP, address) return self.dap_read_reg(self.SWD_AP_DRW | self.DAP_TRANSFER_APnDP)
[ "def", "read_word", "(", "self", ",", "address", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"read word at 0x%08X\"", ",", "address", ")", "self", ".", "dap_write_reg", "(", "self", ".", "SWD_AP_TAR", "|", "self", ".", "DAP_TRANSFER_APnDP", ",", ...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/protocols/cmsisdap.py#L316-L324
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_pydecimal.py
python
_sqrt_nearest
(n, a)
return a
Closest integer to the square root of the positive integer n. a is an initial approximation to the square root. Any positive integer will do for a, but the closer a is to the square root of n the faster convergence will be.
Closest integer to the square root of the positive integer n. a is an initial approximation to the square root. Any positive integer will do for a, but the closer a is to the square root of n the faster convergence will be.
[ "Closest", "integer", "to", "the", "square", "root", "of", "the", "positive", "integer", "n", ".", "a", "is", "an", "initial", "approximation", "to", "the", "square", "root", ".", "Any", "positive", "integer", "will", "do", "for", "a", "but", "the", "clo...
def _sqrt_nearest(n, a): """Closest integer to the square root of the positive integer n. a is an initial approximation to the square root. Any positive integer will do for a, but the closer a is to the square root of n the faster convergence will be. """ if n <= 0 or a <= 0: raise ValueError("Both arguments to _sqrt_nearest should be positive.") b=0 while a != b: b, a = a, a--n//a>>1 return a
[ "def", "_sqrt_nearest", "(", "n", ",", "a", ")", ":", "if", "n", "<=", "0", "or", "a", "<=", "0", ":", "raise", "ValueError", "(", "\"Both arguments to _sqrt_nearest should be positive.\"", ")", "b", "=", "0", "while", "a", "!=", "b", ":", "b", ",", "a...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pydecimal.py#L5693-L5706
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/perf/profile_creators/profile_safe_url_generator.py
python
GenerateSafeUrls
()
Prints a list of safe urls. Generates a safe list of urls from a seed list. Each href in the HTML fetched from the url from the seed list is placed into the safe list. The safe list contains unsanitized urls.
Prints a list of safe urls.
[ "Prints", "a", "list", "of", "safe", "urls", "." ]
def GenerateSafeUrls(): """Prints a list of safe urls. Generates a safe list of urls from a seed list. Each href in the HTML fetched from the url from the seed list is placed into the safe list. The safe list contains unsanitized urls. """ # A list of websites whose hrefs are unlikely to link to sites that contain # malware. seed_urls = [ "http://www.cnn.com", "https://www.youtube.com", "https://www.facebook.com", "https://www.twitter.com", "https://www.yahoo.com", "https://www.amazon.com", "https://www.wikipedia.com", "https://www.bing.com", "https://www.dailymotion.com", "https://www.stackoverflow.com", "https://www.google.com/#q=dumpling", "http://www.baidu.com/s?wd=rice", "http://www.baidu.com/s?wd=cow", "https://www.google.com/#q=fox", "http://www.yahoo.co.jp/", "http://www.yandex.ru/", "https://www.imdb.com/", "http://www.huffingtonpost.com/", "https://www.deviantart.com/", "http://www.wsj.com/", ] safe_urls = set() for url in seed_urls: try: # Fetch and parse the HTML. response = urllib2.urlopen(url) encoding = response.headers.getparam("charset") html = response.read() if encoding: html = html.decode(encoding) parser = _HRefParser() parser.feed(html) except: logging.exception("Error fetching or parsing url: %s", url) raise # Looks for all hrefs. for relative_url in parser.hrefs: if not relative_url: continue absolute_url = urlparse.urljoin(url, relative_url) if not _AbsoluteUrlHasSaneScheme(absolute_url): continue safe_urls.add(absolute_url) # Sort the urls, to make them easier to view in bulk. safe_urls_list = list(safe_urls) safe_urls_list.sort() print json.dumps(safe_urls_list, indent=2, separators=(",", ":"))
[ "def", "GenerateSafeUrls", "(", ")", ":", "# A list of websites whose hrefs are unlikely to link to sites that contain", "# malware.", "seed_urls", "=", "[", "\"http://www.cnn.com\"", ",", "\"https://www.youtube.com\"", ",", "\"https://www.facebook.com\"", ",", "\"https://www.twitter...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/perf/profile_creators/profile_safe_url_generator.py#L31-L94
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/pytables.py
python
Table.set_attrs
(self)
set our table type & indexables
set our table type & indexables
[ "set", "our", "table", "type", "&", "indexables" ]
def set_attrs(self): """set our table type & indexables""" self.attrs.table_type = str(self.table_type) self.attrs.index_cols = self.index_cols() self.attrs.values_cols = self.values_cols() self.attrs.non_index_axes = self.non_index_axes self.attrs.data_columns = self.data_columns self.attrs.nan_rep = self.nan_rep self.attrs.encoding = self.encoding self.attrs.errors = self.errors self.attrs.levels = self.levels self.attrs.info = self.info
[ "def", "set_attrs", "(", "self", ")", ":", "self", ".", "attrs", ".", "table_type", "=", "str", "(", "self", ".", "table_type", ")", "self", ".", "attrs", ".", "index_cols", "=", "self", ".", "index_cols", "(", ")", "self", ".", "attrs", ".", "values...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/pytables.py#L3493-L3504
randombit/botan
e068d80953469fc8a3ec1715d0f64756d972daba
src/scripts/ci_build.py
python
main
(args=None)
return 0
Parse options, do the things
Parse options, do the things
[ "Parse", "options", "do", "the", "things" ]
def main(args=None): # pylint: disable=too-many-branches,too-many-statements,too-many-locals,too-many-return-statements,too-many-locals """ Parse options, do the things """ if os.getenv('COVERITY_SCAN_BRANCH') == '1': print('Skipping build COVERITY_SCAN_BRANCH set in environment') return 0 if args is None: args = sys.argv print("Invoked as '%s'" % (' '.join(args))) (options, args) = parse_args(args) if len(args) != 2: print('Usage: %s [options] target' % (args[0])) return 1 target = args[1] if target not in known_targets(): print("Unknown target '%s'" % (target)) return 2 if options.use_python3 is None: use_python3 = have_prog('python3') else: use_python3 = options.use_python3 py_interp = 'python' if use_python3: py_interp = 'python3' if options.cc_bin is None: if options.cc == 'gcc': options.cc_bin = 'g++' elif options.cc == 'clang': options.cc_bin = 'clang++' elif options.cc == 'msvc': options.cc_bin = 'cl' elif options.cc == "emcc": options.cc_bin = "em++" else: print('Error unknown compiler %s' % (options.cc)) return 1 if options.compiler_cache is None and options.cc != 'msvc': # Autodetect ccache if have_prog('ccache'): options.compiler_cache = 'ccache' if options.compiler_cache not in [None, 'ccache', 'sccache']: raise Exception("Don't know about %s as a compiler cache" % (options.compiler_cache)) root_dir = options.root_dir if not os.access(root_dir, os.R_OK): raise Exception('Bad root dir setting, dir %s not readable' % (root_dir)) cmds = [] if target == 'lint': pylint_rc = '--rcfile=%s' % (os.path.join(root_dir, 'src/configs/pylint.rc')) pylint_flags = [pylint_rc, '--reports=no'] # Some disabled rules specific to Python3 # useless-object-inheritance: complains about code still useful in Python2 py3_flags = '--disable=useless-object-inheritance' py_scripts = [ 'configure.py', 'src/python/botan2.py', 'src/scripts/ci_build.py', 'src/scripts/install.py', 'src/scripts/ci_check_install.py', 'src/scripts/dist.py', 'src/scripts/cleanup.py', 'src/scripts/check.py', 'src/scripts/build_docs.py', 'src/scripts/website.py', 'src/scripts/bench.py', 'src/scripts/test_python.py', 'src/scripts/test_fuzzers.py', 'src/scripts/test_cli.py', 'src/scripts/python_unittests.py', 'src/scripts/python_unittests_unix.py'] full_paths = [os.path.join(root_dir, s) for s in py_scripts] if use_python3 and options.use_pylint3: cmds.append(['python3', '-m', 'pylint'] + pylint_flags + [py3_flags] + full_paths) else: config_flags, run_test_command, make_prefix = determine_flags( target, options.os, options.cpu, options.cc, options.cc_bin, options.compiler_cache, root_dir, options.pkcs11_lib, options.use_gdb, options.disable_werror, options.extra_cxxflags, options.disabled_tests) cmds.append([py_interp, os.path.join(root_dir, 'configure.py')] + config_flags) make_cmd = [options.make_tool] if root_dir != '.': make_cmd += ['-C', root_dir] if options.build_jobs > 1 and options.make_tool != 'nmake': make_cmd += ['-j%d' % (options.build_jobs)] make_cmd += ['-k'] if target == 'docs': cmds.append(make_cmd + ['docs']) else: if options.compiler_cache is not None: cmds.append([options.compiler_cache, '--show-stats']) make_targets = ['libs', 'tests', 'cli'] if target in ['coverage', 'fuzzers']: make_targets += ['fuzzer_corpus_zip', 'fuzzers'] if target in ['coverage']: make_targets += ['bogo_shim'] cmds.append(make_prefix + make_cmd + make_targets) if options.compiler_cache is not None: cmds.append([options.compiler_cache, '--show-stats']) if run_test_command is not None: cmds.append(run_test_command) if target == 'coverage': runner_dir = os.path.abspath(os.path.join(root_dir, 'boringssl', 'ssl', 'test', 'runner')) cmds.append(['indir:%s' % (runner_dir), 'go', 'test', '-pipe', '-num-workers', str(4*get_concurrency()), '-shim-path', os.path.abspath(os.path.join(root_dir, 'botan_bogo_shim')), '-shim-config', os.path.abspath(os.path.join(root_dir, 'src', 'bogo_shim', 'config.json'))]) if target in ['coverage', 'fuzzers']: cmds.append([py_interp, os.path.join(root_dir, 'src/scripts/test_fuzzers.py'), os.path.join(root_dir, 'fuzzer_corpus'), os.path.join(root_dir, 'build/fuzzer')]) if target in ['shared', 'coverage'] and options.os != 'windows': botan_exe = os.path.join(root_dir, 'botan-cli.exe' if options.os == 'windows' else 'botan') args = ['--threads=%d' % (options.build_jobs)] if target == 'coverage': args.append('--run-slow-tests') test_scripts = ['test_cli.py', 'test_cli_crypt.py'] for script in test_scripts: cmds.append([py_interp, os.path.join(root_dir, 'src/scripts', script)] + args + [botan_exe]) python_tests = os.path.join(root_dir, 'src/scripts/test_python.py') if target in ['shared', 'coverage']: if options.os == 'windows': if options.cpu == 'x86': # Python on AppVeyor is a 32-bit binary so only test for 32-bit cmds.append([py_interp, '-b', python_tests]) else: if use_python3: cmds.append(['python3', '-b', python_tests]) if target in ['shared', 'static', 'bsi', 'nist']: cmds.append(make_cmd + ['install']) build_config = os.path.join(root_dir, 'build', 'build_config.json') cmds.append([py_interp, os.path.join(root_dir, 'src/scripts/ci_check_install.py'), build_config]) if target in ['coverage']: if not have_prog('lcov'): print('Error: lcov not found in PATH (%s)' % (os.getenv('PATH'))) return 1 if not have_prog('gcov'): print('Error: gcov not found in PATH (%s)' % (os.getenv('PATH'))) return 1 cov_file = 'coverage.info' raw_cov_file = 'coverage.info.raw' cmds.append(['lcov', '--capture', '--directory', options.root_dir, '--output-file', raw_cov_file]) cmds.append(['lcov', '--remove', raw_cov_file, '/usr/*', '--output-file', cov_file]) cmds.append(['lcov', '--list', cov_file]) if have_prog('coverage'): cmds.append(['coverage', 'run', '--branch', '--rcfile', os.path.join(root_dir, 'src/configs/coverage.rc'), python_tests]) if have_prog('codecov'): # If codecov exists assume we are in CI and report to codecov.io cmds.append(['codecov', '>', 'codecov_stdout.log']) else: # Otherwise generate a local HTML report cmds.append(['genhtml', cov_file, '--output-directory', 'lcov-out']) cmds.append(make_cmd + ['clean']) cmds.append(make_cmd + ['distclean']) for cmd in cmds: if options.dry_run: print('$ ' + ' '.join(cmd)) else: run_cmd(cmd, root_dir) return 0
[ "def", "main", "(", "args", "=", "None", ")", ":", "# pylint: disable=too-many-branches,too-many-statements,too-many-locals,too-many-return-statements,too-many-locals", "if", "os", ".", "getenv", "(", "'COVERITY_SCAN_BRANCH'", ")", "==", "'1'", ":", "print", "(", "'Skipping...
https://github.com/randombit/botan/blob/e068d80953469fc8a3ec1715d0f64756d972daba/src/scripts/ci_build.py#L437-L651
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiToolBarItem.GetDisabledBitmap
(*args, **kwargs)
return _aui.AuiToolBarItem_GetDisabledBitmap(*args, **kwargs)
GetDisabledBitmap(self) -> Bitmap
GetDisabledBitmap(self) -> Bitmap
[ "GetDisabledBitmap", "(", "self", ")", "-", ">", "Bitmap" ]
def GetDisabledBitmap(*args, **kwargs): """GetDisabledBitmap(self) -> Bitmap""" return _aui.AuiToolBarItem_GetDisabledBitmap(*args, **kwargs)
[ "def", "GetDisabledBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiToolBarItem_GetDisabledBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L1789-L1791
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
MULAN_universal_lesion_analysis/maskrcnn/modeling/poolers.py
python
Pooler.__init__
(self, output_size, scales, sampling_ratio)
Arguments: output_size (list[tuple[int]] or list[int]): output size for the pooled region scales (list[float]): scales for each Pooler sampling_ratio (int): sampling ratio for ROIAlign
Arguments: output_size (list[tuple[int]] or list[int]): output size for the pooled region scales (list[float]): scales for each Pooler sampling_ratio (int): sampling ratio for ROIAlign
[ "Arguments", ":", "output_size", "(", "list", "[", "tuple", "[", "int", "]]", "or", "list", "[", "int", "]", ")", ":", "output", "size", "for", "the", "pooled", "region", "scales", "(", "list", "[", "float", "]", ")", ":", "scales", "for", "each", ...
def __init__(self, output_size, scales, sampling_ratio): """ Arguments: output_size (list[tuple[int]] or list[int]): output size for the pooled region scales (list[float]): scales for each Pooler sampling_ratio (int): sampling ratio for ROIAlign """ super(Pooler, self).__init__() poolers = [] for scale in scales: poolers.append( ROIAlign( output_size, spatial_scale=scale, sampling_ratio=sampling_ratio ) ) self.poolers = nn.ModuleList(poolers) self.output_size = output_size # get the levels in the feature map by leveraging the fact that the network always # downsamples by a factor of 2 at each level. lvl_min = -torch.log2(torch.tensor(scales[0], dtype=torch.float32)).item() lvl_max = -torch.log2(torch.tensor(scales[-1], dtype=torch.float32)).item() self.map_levels = LevelMapper(lvl_min, lvl_max)
[ "def", "__init__", "(", "self", ",", "output_size", ",", "scales", ",", "sampling_ratio", ")", ":", "super", "(", "Pooler", ",", "self", ")", ".", "__init__", "(", ")", "poolers", "=", "[", "]", "for", "scale", "in", "scales", ":", "poolers", ".", "a...
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/MULAN_universal_lesion_analysis/maskrcnn/modeling/poolers.py#L63-L84
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/training/input.py
python
_deserialize_sparse_tensors
(serialized_list, sparse_info_list)
return tensors if received_sequence else tensors[0]
Deserialize SparseTensors after dequeue in batch, batch_join, etc.
Deserialize SparseTensors after dequeue in batch, batch_join, etc.
[ "Deserialize", "SparseTensors", "after", "dequeue", "in", "batch", "batch_join", "etc", "." ]
def _deserialize_sparse_tensors(serialized_list, sparse_info_list): """Deserialize SparseTensors after dequeue in batch, batch_join, etc.""" received_sequence = isinstance(serialized_list, collections.Sequence) if not received_sequence: serialized_list = (serialized_list,) tensors = [ sparse_ops.deserialize_many_sparse(s, info.dtype, (info.rank + 1).value) if info.sparse else s for (s, info) in zip(serialized_list, sparse_info_list)] return tensors if received_sequence else tensors[0]
[ "def", "_deserialize_sparse_tensors", "(", "serialized_list", ",", "sparse_info_list", ")", ":", "received_sequence", "=", "isinstance", "(", "serialized_list", ",", "collections", ".", "Sequence", ")", "if", "not", "received_sequence", ":", "serialized_list", "=", "(...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/input.py#L399-L409
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/genericmessagedialog.py
python
GenericMessageDialog.GetCustomNoBitmap
(self)
return (self._noBitmap and [self._noBitmap] or [self.GetDefaultNoBitmap()])[0]
If a custom icon has been used for the ``No`` button, this method will return it as an instance of :class:`Bitmap`. Otherwise, the default one (as defined in :meth:`~GenericMessageDialog.GetDefaultNoBitmap`) is returned. .. versionadded:: 0.9.3
If a custom icon has been used for the ``No`` button, this method will return it as an instance of :class:`Bitmap`. Otherwise, the default one (as defined in :meth:`~GenericMessageDialog.GetDefaultNoBitmap`) is returned.
[ "If", "a", "custom", "icon", "has", "been", "used", "for", "the", "No", "button", "this", "method", "will", "return", "it", "as", "an", "instance", "of", ":", "class", ":", "Bitmap", ".", "Otherwise", "the", "default", "one", "(", "as", "defined", "in"...
def GetCustomNoBitmap(self): """ If a custom icon has been used for the ``No`` button, this method will return it as an instance of :class:`Bitmap`. Otherwise, the default one (as defined in :meth:`~GenericMessageDialog.GetDefaultNoBitmap`) is returned. .. versionadded:: 0.9.3 """ return (self._noBitmap and [self._noBitmap] or [self.GetDefaultNoBitmap()])[0]
[ "def", "GetCustomNoBitmap", "(", "self", ")", ":", "return", "(", "self", ".", "_noBitmap", "and", "[", "self", ".", "_noBitmap", "]", "or", "[", "self", ".", "GetDefaultNoBitmap", "(", ")", "]", ")", "[", "0", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/genericmessagedialog.py#L1331-L1340
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
ToolBarBase.GetToolSeparation
(*args, **kwargs)
return _controls_.ToolBarBase_GetToolSeparation(*args, **kwargs)
GetToolSeparation(self) -> int
GetToolSeparation(self) -> int
[ "GetToolSeparation", "(", "self", ")", "-", ">", "int" ]
def GetToolSeparation(*args, **kwargs): """GetToolSeparation(self) -> int""" return _controls_.ToolBarBase_GetToolSeparation(*args, **kwargs)
[ "def", "GetToolSeparation", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ToolBarBase_GetToolSeparation", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L3867-L3869
toggl-open-source/toggldesktop
91865205885531cc8fd9e8d613dad49d625d56e7
third_party/cpplint/cpplint.py
python
ReverseCloseExpression
(clean_lines, linenum, pos)
return (line, 0, -1)
If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening 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 *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. 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 opens it.
[ "If", "input", "points", "to", ")", "or", "}", "or", "]", "or", ">", "finds", "the", "position", "that", "opens", "it", "." ]
def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening 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 *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if line[pos] not in ')}]>': return (line, 0, -1) # Check last line (start_pos, stack) = FindStartOfExpressionInLine(line, pos, []) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while stack and linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack) if start_pos > -1: return (line, linenum, start_pos) # Did not find start of expression before beginning of file, give up return (line, 0, -1)
[ "def", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "line", "[", "pos", "]", "not", "in", "')}]>'", ":", "return", "(", "line", ",", "0", ",", ...
https://github.com/toggl-open-source/toggldesktop/blob/91865205885531cc8fd9e8d613dad49d625d56e7/third_party/cpplint/cpplint.py#L1584-L1619
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
clip
(x, min=None, max=None)
return Clip(min, max)(x)[0]
Clip operator limits the given input within an interval. The interval is specified by the inputs 'min' and 'max'. Args: x (Tensor): input tensor min (float): Minimum value, under which element is replaced by min. max (float): Maximum value, above which element is replaced by max. Returns: a new Tensor with np.clip(x,min,max).
Clip operator limits the given input within an interval. The interval is specified by the inputs 'min' and 'max'. Args: x (Tensor): input tensor min (float): Minimum value, under which element is replaced by min. max (float): Maximum value, above which element is replaced by max. Returns: a new Tensor with np.clip(x,min,max).
[ "Clip", "operator", "limits", "the", "given", "input", "within", "an", "interval", ".", "The", "interval", "is", "specified", "by", "the", "inputs", "min", "and", "max", ".", "Args", ":", "x", "(", "Tensor", ")", ":", "input", "tensor", "min", "(", "fl...
def clip(x, min=None, max=None): """ Clip operator limits the given input within an interval. The interval is specified by the inputs 'min' and 'max'. Args: x (Tensor): input tensor min (float): Minimum value, under which element is replaced by min. max (float): Maximum value, above which element is replaced by max. Returns: a new Tensor with np.clip(x,min,max). """ return Clip(min, max)(x)[0]
[ "def", "clip", "(", "x", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "return", "Clip", "(", "min", ",", "max", ")", "(", "x", ")", "[", "0", "]" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L543-L554
nlohmann/json
eb2182414749825be086c825edb5229e5c28503d
third_party/cpplint/cpplint.py
python
Search
(pattern, s)
return _regexp_compile_cache[pattern].search(s)
Searches the string for the pattern, caching the compiled regexp.
Searches the string for the pattern, caching the compiled regexp.
[ "Searches", "the", "string", "for", "the", "pattern", "caching", "the", "compiled", "regexp", "." ]
def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s)
[ "def", "Search", "(", "pattern", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pat...
https://github.com/nlohmann/json/blob/eb2182414749825be086c825edb5229e5c28503d/third_party/cpplint/cpplint.py#L1057-L1061
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/linear_model/stochastic_gradient.py
python
BaseSGD._allocate_parameter_mem
(self, n_classes, n_features, coef_init=None, intercept_init=None)
Allocate mem for parameters; initialize if provided.
Allocate mem for parameters; initialize if provided.
[ "Allocate", "mem", "for", "parameters", ";", "initialize", "if", "provided", "." ]
def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None, intercept_init=None): """Allocate mem for parameters; initialize if provided.""" if n_classes > 2: # allocate coef_ for multi-class if coef_init is not None: coef_init = np.asarray(coef_init, order="C") if coef_init.shape != (n_classes, n_features): raise ValueError("Provided ``coef_`` does not match " "dataset. ") self.coef_ = coef_init else: self.coef_ = np.zeros((n_classes, n_features), dtype=np.float64, order="C") # allocate intercept_ for multi-class if intercept_init is not None: intercept_init = np.asarray(intercept_init, order="C") if intercept_init.shape != (n_classes, ): raise ValueError("Provided intercept_init " "does not match dataset.") self.intercept_ = intercept_init else: self.intercept_ = np.zeros(n_classes, dtype=np.float64, order="C") else: # allocate coef_ for binary problem if coef_init is not None: coef_init = np.asarray(coef_init, dtype=np.float64, order="C") coef_init = coef_init.ravel() if coef_init.shape != (n_features,): raise ValueError("Provided coef_init does not " "match dataset.") self.coef_ = coef_init else: self.coef_ = np.zeros(n_features, dtype=np.float64, order="C") # allocate intercept_ for binary problem if intercept_init is not None: intercept_init = np.asarray(intercept_init, dtype=np.float64) if intercept_init.shape != (1,) and intercept_init.shape != (): raise ValueError("Provided intercept_init " "does not match dataset.") self.intercept_ = intercept_init.reshape(1,) else: self.intercept_ = np.zeros(1, dtype=np.float64, order="C") # initialize average parameters if self.average > 0: self.standard_coef_ = self.coef_ self.standard_intercept_ = self.intercept_ self.average_coef_ = np.zeros(self.coef_.shape, dtype=np.float64, order="C") self.average_intercept_ = np.zeros(self.standard_intercept_.shape, dtype=np.float64, order="C")
[ "def", "_allocate_parameter_mem", "(", "self", ",", "n_classes", ",", "n_features", ",", "coef_init", "=", "None", ",", "intercept_init", "=", "None", ")", ":", "if", "n_classes", ">", "2", ":", "# allocate coef_ for multi-class", "if", "coef_init", "is", "not",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/stochastic_gradient.py#L155-L214
choasup/caffe-yolo9000
e8a476c4c23d756632f7a26c681a96e3ab672544
scripts/cpp_lint.py
python
IsBlankLine
(line)
return not line or line.isspace()
Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank.
Returns true if the given line is blank.
[ "Returns", "true", "if", "the", "given", "line", "is", "blank", "." ]
def IsBlankLine(line): """Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank. """ return not line or line.isspace()
[ "def", "IsBlankLine", "(", "line", ")", ":", "return", "not", "line", "or", "line", ".", "isspace", "(", ")" ]
https://github.com/choasup/caffe-yolo9000/blob/e8a476c4c23d756632f7a26c681a96e3ab672544/scripts/cpp_lint.py#L2373-L2385
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/xrc.py
python
XmlResourceHandler.CreateChildren
(*args, **kwargs)
return _xrc.XmlResourceHandler_CreateChildren(*args, **kwargs)
CreateChildren(self, Object parent, bool this_hnd_only=False)
CreateChildren(self, Object parent, bool this_hnd_only=False)
[ "CreateChildren", "(", "self", "Object", "parent", "bool", "this_hnd_only", "=", "False", ")" ]
def CreateChildren(*args, **kwargs): """CreateChildren(self, Object parent, bool this_hnd_only=False)""" return _xrc.XmlResourceHandler_CreateChildren(*args, **kwargs)
[ "def", "CreateChildren", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_xrc", ".", "XmlResourceHandler_CreateChildren", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/xrc.py#L721-L723
zhuli19901106/leetcode-zhuli
0f8fc29ccb8c33ea91149ecb2d4e961024c11db7
explore/fun-with-arrays/3245_duplicate-zeros_1_AC.py
python
Solution.duplicateZeros
(self, arr: List[int])
Do not return anything, modify arr in-place instead.
Do not return anything, modify arr in-place instead.
[ "Do", "not", "return", "anything", "modify", "arr", "in", "-", "place", "instead", "." ]
def duplicateZeros(self, arr: List[int]) -> None: """ Do not return anything, modify arr in-place instead. """ a = arr n = len(a) z = 0 for i in range(n): if a[i] == 0: z += 1 for i in range(n - 1, -1, -1): if a[i] == 0: z -= 1 j = i + z if j < n: a[j] = a[i] if a[i] == 0 and j + 1 < n: a[j + 1] = a[i]
[ "def", "duplicateZeros", "(", "self", ",", "arr", ":", "List", "[", "int", "]", ")", "->", "None", ":", "a", "=", "arr", "n", "=", "len", "(", "a", ")", "z", "=", "0", "for", "i", "in", "range", "(", "n", ")", ":", "if", "a", "[", "i", "]...
https://github.com/zhuli19901106/leetcode-zhuli/blob/0f8fc29ccb8c33ea91149ecb2d4e961024c11db7/explore/fun-with-arrays/3245_duplicate-zeros_1_AC.py#L3-L20
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Scanner/Dir.py
python
scan_on_disk
(node, env, path=())
return scan_in_memory(node, env, path)
Scans a directory for on-disk files and directories therein. Looking up the entries will add these to the in-memory Node tree representation of the file system, so all we have to do is just that and then call the in-memory scanning function.
Scans a directory for on-disk files and directories therein.
[ "Scans", "a", "directory", "for", "on", "-", "disk", "files", "and", "directories", "therein", "." ]
def scan_on_disk(node, env, path=()): """ Scans a directory for on-disk files and directories therein. Looking up the entries will add these to the in-memory Node tree representation of the file system, so all we have to do is just that and then call the in-memory scanning function. """ try: flist = node.fs.listdir(node.get_abspath()) except (IOError, OSError): return [] e = node.Entry for f in filter(do_not_scan, flist): # Add ./ to the beginning of the file name so if it begins with a # '#' we don't look it up relative to the top-level directory. e('./' + f) return scan_in_memory(node, env, path)
[ "def", "scan_on_disk", "(", "node", ",", "env", ",", "path", "=", "(", ")", ")", ":", "try", ":", "flist", "=", "node", ".", "fs", ".", "listdir", "(", "node", ".", "get_abspath", "(", ")", ")", "except", "(", "IOError", ",", "OSError", ")", ":",...
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Scanner/Dir.py#L71-L88
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/graph_kernel/model/graph_split.py
python
GraphSplitByPattern.set_area_map
(self, ops, area)
update area_map after op fused to area
update area_map after op fused to area
[ "update", "area_map", "after", "op", "fused", "to", "area" ]
def set_area_map(self, ops, area): """update area_map after op fused to area""" for op in ops: self.area_map[op] = area
[ "def", "set_area_map", "(", "self", ",", "ops", ",", "area", ")", ":", "for", "op", "in", "ops", ":", "self", ".", "area_map", "[", "op", "]", "=", "area" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/graph_kernel/model/graph_split.py#L334-L337
geemaple/leetcode
68bc5032e1ee52c22ef2f2e608053484c487af54
leetcode/173.binary-search-tree-iterator.py
python
BSTIterator.hasNext
(self)
return self.cur is not None or len(self.stack) > 0
:rtype: bool
:rtype: bool
[ ":", "rtype", ":", "bool" ]
def hasNext(self): """ :rtype: bool """ return self.cur is not None or len(self.stack) > 0
[ "def", "hasNext", "(", "self", ")", ":", "return", "self", ".", "cur", "is", "not", "None", "or", "len", "(", "self", ".", "stack", ")", ">", "0" ]
https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/173.binary-search-tree-iterator.py#L17-L21
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/ply_info/example/ansic/cparse.py
python
p_declaration_1
(t)
declaration : declaration_specifiers init_declarator_list SEMI
declaration : declaration_specifiers init_declarator_list SEMI
[ "declaration", ":", "declaration_specifiers", "init_declarator_list", "SEMI" ]
def p_declaration_1(t): 'declaration : declaration_specifiers init_declarator_list SEMI' pass
[ "def", "p_declaration_1", "(", "t", ")", ":", "pass" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L54-L56
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/idl/idl/generator.py
python
_CppFileWriterBase._block
(self, opening, closing)
return writer.IndentedScopedBlock(self._writer, opening, closing)
Generate an indented block if opening is not empty.
Generate an indented block if opening is not empty.
[ "Generate", "an", "indented", "block", "if", "opening", "is", "not", "empty", "." ]
def _block(self, opening, closing): # type: (unicode, unicode) -> Union[writer.IndentedScopedBlock,writer.EmptyBlock] """Generate an indented block if opening is not empty.""" if not opening: return writer.EmptyBlock() return writer.IndentedScopedBlock(self._writer, opening, closing)
[ "def", "_block", "(", "self", ",", "opening", ",", "closing", ")", ":", "# type: (unicode, unicode) -> Union[writer.IndentedScopedBlock,writer.EmptyBlock]", "if", "not", "opening", ":", "return", "writer", ".", "EmptyBlock", "(", ")", "return", "writer", ".", "Indente...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/generator.py#L323-L329
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
modules/tools/sensor_calibration/ins_stat_publisher.py
python
InsStat.shutdown
(self)
shutdown rosnode
shutdown rosnode
[ "shutdown", "rosnode" ]
def shutdown(self): """ shutdown rosnode """ self.terminating = True #self.logger.info("Shutting Down...") time.sleep(0.2)
[ "def", "shutdown", "(", "self", ")", ":", "self", ".", "terminating", "=", "True", "#self.logger.info(\"Shutting Down...\")", "time", ".", "sleep", "(", "0.2", ")" ]
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/sensor_calibration/ins_stat_publisher.py#L51-L57
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/so2.py
python
matrix
(a : float)
return [[c,-s],[s,c]]
Returns the 2x2 rotation matrix representing a rotation about the angle a.
Returns the 2x2 rotation matrix representing a rotation about the angle a.
[ "Returns", "the", "2x2", "rotation", "matrix", "representing", "a", "rotation", "about", "the", "angle", "a", "." ]
def matrix(a : float) -> List[List[float]]: """Returns the 2x2 rotation matrix representing a rotation about the angle a.""" c = math.cos(a) s = math.sin(a) return [[c,-s],[s,c]]
[ "def", "matrix", "(", "a", ":", "float", ")", "->", "List", "[", "List", "[", "float", "]", "]", ":", "c", "=", "math", ".", "cos", "(", "a", ")", "s", "=", "math", ".", "sin", "(", "a", ")", "return", "[", "[", "c", ",", "-", "s", "]", ...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/so2.py#L50-L55
KhronosGroup/Vulkan-Headers
b32da5329b50e3cb96229aaecba9ded032fe29cc
registry/generator.py
python
OutputGenerator.getMaxCParamTypeLength
(self, info)
return max(lengths)
Return the length of the longest type field for a member/parameter. - info - TypeInfo or CommandInfo.
Return the length of the longest type field for a member/parameter.
[ "Return", "the", "length", "of", "the", "longest", "type", "field", "for", "a", "member", "/", "parameter", "." ]
def getMaxCParamTypeLength(self, info): """Return the length of the longest type field for a member/parameter. - info - TypeInfo or CommandInfo. """ lengths = (self.getCParamTypeLength(member) for member in info.getMembers()) return max(lengths)
[ "def", "getMaxCParamTypeLength", "(", "self", ",", "info", ")", ":", "lengths", "=", "(", "self", ".", "getCParamTypeLength", "(", "member", ")", "for", "member", "in", "info", ".", "getMembers", "(", ")", ")", "return", "max", "(", "lengths", ")" ]
https://github.com/KhronosGroup/Vulkan-Headers/blob/b32da5329b50e3cb96229aaecba9ded032fe29cc/registry/generator.py#L1015-L1022
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/rev_block_lib.py
python
_rev_layer_forward
(xs, f, g, f_side_input, g_side_input, gate_outputs=False)
Forward for 1 reversible layer.
Forward for 1 reversible layer.
[ "Forward", "for", "1", "reversible", "layer", "." ]
def _rev_layer_forward(xs, f, g, f_side_input, g_side_input, gate_outputs=False): """Forward for 1 reversible layer.""" x1, x2 = xs y1 = x1 + (f(x2, f_side_input) if f_side_input else f(x2)) y2 = x2 + (g(y1, g_side_input) if g_side_input else g(y1)) if gate_outputs: return control_flow_ops.tuple([y1, y2]) else: return (y1, y2)
[ "def", "_rev_layer_forward", "(", "xs", ",", "f", ",", "g", ",", "f_side_input", ",", "g_side_input", ",", "gate_outputs", "=", "False", ")", ":", "x1", ",", "x2", "=", "xs", "y1", "=", "x1", "+", "(", "f", "(", "x2", ",", "f_side_input", ")", "if"...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/rev_block_lib.py#L78-L87
apple/swift-clang
d7403439fc6641751840b723e7165fb02f52db95
tools/scan-build-py/libscanbuild/report.py
python
read_bugs
(output_dir, html)
Generate a unique sequence of bugs from given output directory. Duplicates can be in a project if the same module was compiled multiple times with different compiler options. These would be better to show in the final report (cover) only once.
Generate a unique sequence of bugs from given output directory.
[ "Generate", "a", "unique", "sequence", "of", "bugs", "from", "given", "output", "directory", "." ]
def read_bugs(output_dir, html): # type: (str, bool) -> Generator[Dict[str, Any], None, None] """ Generate a unique sequence of bugs from given output directory. Duplicates can be in a project if the same module was compiled multiple times with different compiler options. These would be better to show in the final report (cover) only once. """ def empty(file_name): return os.stat(file_name).st_size == 0 duplicate = duplicate_check( lambda bug: '{bug_line}.{bug_path_length}:{bug_file}'.format(**bug)) # get the right parser for the job. parser = parse_bug_html if html else parse_bug_plist # get the input files, which are not empty. pattern = os.path.join(output_dir, '*.html' if html else '*.plist') bug_files = (file for file in glob.iglob(pattern) if not empty(file)) for bug_file in bug_files: for bug in parser(bug_file): if not duplicate(bug): yield bug
[ "def", "read_bugs", "(", "output_dir", ",", "html", ")", ":", "# type: (str, bool) -> Generator[Dict[str, Any], None, None]", "def", "empty", "(", "file_name", ")", ":", "return", "os", ".", "stat", "(", "file_name", ")", ".", "st_size", "==", "0", "duplicate", ...
https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/tools/scan-build-py/libscanbuild/report.py#L255-L278
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetLdflags
(self, configname, product_dir, gyp_to_build_path)
return ldflags
Returns flags that need to be passed to the linker. Args: configname: The name of the configuration to get ld flags for. product_dir: The directory where products such static and dynamic libraries are placed. This is added to the library search path. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build direcotry.
Returns flags that need to be passed to the linker.
[ "Returns", "flags", "that", "need", "to", "be", "passed", "to", "the", "linker", "." ]
def GetLdflags(self, configname, product_dir, gyp_to_build_path): """Returns flags that need to be passed to the linker. Args: configname: The name of the configuration to get ld flags for. product_dir: The directory where products such static and dynamic libraries are placed. This is added to the library search path. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build direcotry. """ self.configname = configname ldflags = [] # The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS # can contain entries that depend on this. Explicitly absolutify these. for ldflag in self._Settings().get('OTHER_LDFLAGS', []): ldflags.append(self._MapLinkerFlagFilename(ldflag, gyp_to_build_path)) if self._Test('DEAD_CODE_STRIPPING', 'YES', default='NO'): ldflags.append('-Wl,-dead_strip') if self._Test('PREBINDING', 'YES', default='NO'): ldflags.append('-Wl,-prebind') self._Appendf( ldflags, 'DYLIB_COMPATIBILITY_VERSION', '-compatibility_version %s') self._Appendf( ldflags, 'DYLIB_CURRENT_VERSION', '-current_version %s') self._Appendf( ldflags, 'MACOSX_DEPLOYMENT_TARGET', '-mmacosx-version-min=%s') if 'SDKROOT' in self._Settings(): ldflags.append('-isysroot ' + self._SdkPath()) for library_path in self._Settings().get('LIBRARY_SEARCH_PATHS', []): ldflags.append('-L' + gyp_to_build_path(library_path)) if 'ORDER_FILE' in self._Settings(): ldflags.append('-Wl,-order_file ' + '-Wl,' + gyp_to_build_path( self._Settings()['ORDER_FILE'])) archs = self._Settings().get('ARCHS', ['i386']) if len(archs) != 1: # TODO: Supporting fat binaries will be annoying. self._WarnUnimplemented('ARCHS') archs = ['i386'] ldflags.append('-arch ' + archs[0]) # Xcode adds the product directory by default. ldflags.append('-L' + product_dir) install_name = self.GetInstallName() if install_name: ldflags.append('-install_name ' + install_name.replace(' ', r'\ ')) for rpath in self._Settings().get('LD_RUNPATH_SEARCH_PATHS', []): ldflags.append('-Wl,-rpath,' + rpath) config = self.spec['configurations'][self.configname] framework_dirs = config.get('mac_framework_dirs', []) for directory in framework_dirs: ldflags.append('-F' + directory.replace('$(SDKROOT)', self._SdkPath())) self.configname = None return ldflags
[ "def", "GetLdflags", "(", "self", ",", "configname", ",", "product_dir", ",", "gyp_to_build_path", ")", ":", "self", ".", "configname", "=", "configname", "ldflags", "=", "[", "]", "# The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS", "# can contai...
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/xcode_emulation.py#L499-L563
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/preprocessing/_data.py
python
MaxAbsScaler.fit
(self, X, y=None)
return self.partial_fit(X, y)
Compute the maximum absolute value to be used for later scaling. Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
Compute the maximum absolute value to be used for later scaling.
[ "Compute", "the", "maximum", "absolute", "value", "to", "be", "used", "for", "later", "scaling", "." ]
def fit(self, X, y=None): """Compute the maximum absolute value to be used for later scaling. Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data used to compute the per-feature minimum and maximum used for later scaling along the features axis. """ # Reset internal state before fitting self._reset() return self.partial_fit(X, y)
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "# Reset internal state before fitting", "self", ".", "_reset", "(", ")", "return", "self", ".", "partial_fit", "(", "X", ",", "y", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/preprocessing/_data.py#L932-L944
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/filelist.py
python
FileList.debug_print
(self, msg)
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
[ "Print", "msg", "to", "stdout", "if", "the", "global", "DEBUG", "(", "taken", "from", "the", "DISTUTILS_DEBUG", "environment", "variable", ")", "flag", "is", "true", "." ]
def debug_print(self, msg): """Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true. """ from distutils.debug import DEBUG if DEBUG: print msg
[ "def", "debug_print", "(", "self", ",", "msg", ")", ":", "from", "distutils", ".", "debug", "import", "DEBUG", "if", "DEBUG", ":", "print", "msg" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/filelist.py#L42-L48
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Misc.grid_slaves
(self, row=None, column=None)
return map(self._nametowidget, self.tk.splitlist(self.tk.call( ('grid', 'slaves', self._w) + args)))
Return a list of all slaves of this widget in its packing order.
Return a list of all slaves of this widget in its packing order.
[ "Return", "a", "list", "of", "all", "slaves", "of", "this", "widget", "in", "its", "packing", "order", "." ]
def grid_slaves(self, row=None, column=None): """Return a list of all slaves of this widget in its packing order.""" args = () if row is not None: args = args + ('-row', row) if column is not None: args = args + ('-column', column) return map(self._nametowidget, self.tk.splitlist(self.tk.call( ('grid', 'slaves', self._w) + args)))
[ "def", "grid_slaves", "(", "self", ",", "row", "=", "None", ",", "column", "=", "None", ")", ":", "args", "=", "(", ")", "if", "row", "is", "not", "None", ":", "args", "=", "args", "+", "(", "'-row'", ",", "row", ")", "if", "column", "is", "not...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1404-L1414
line/stellite
5bd1c1f5f0cdc22a65319068f4f8b2ca7769bfa1
tools/build.py
python
BuildObject.fetch_toolchain
(self)
return True
fetch build toolchain
fetch build toolchain
[ "fetch", "build", "toolchain" ]
def fetch_toolchain(self): """fetch build toolchain""" return True
[ "def", "fetch_toolchain", "(", "self", ")", ":", "return", "True" ]
https://github.com/line/stellite/blob/5bd1c1f5f0cdc22a65319068f4f8b2ca7769bfa1/tools/build.py#L762-L764
TGAC/KAT
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
deps/boost/tools/build/src/build/generators.py
python
Generator.target_types
(self)
return self.target_types_
Returns the list of target types that this generator produces. It is assumed to be always the same -- i.e. it cannot change depending list of sources.
Returns the list of target types that this generator produces. It is assumed to be always the same -- i.e. it cannot change depending list of sources.
[ "Returns", "the", "list", "of", "target", "types", "that", "this", "generator", "produces", ".", "It", "is", "assumed", "to", "be", "always", "the", "same", "--", "i", ".", "e", ".", "it", "cannot", "change", "depending", "list", "of", "sources", "." ]
def target_types (self): """ Returns the list of target types that this generator produces. It is assumed to be always the same -- i.e. it cannot change depending list of sources. """ return self.target_types_
[ "def", "target_types", "(", "self", ")", ":", "return", "self", ".", "target_types_" ]
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/generators.py#L286-L291
runtimejs/runtime
0a6e84c30823d35a4548d6634166784260ae7b74
deps/v8/tools/grokdump.py
python
InspectionShell.do_lm
(self, arg)
List details for all loaded modules in the minidump. An argument can be passed to limit the output to only those modules that contain the argument as a substring (case insensitive match).
List details for all loaded modules in the minidump. An argument can be passed to limit the output to only those modules that contain the argument as a substring (case insensitive match).
[ "List", "details", "for", "all", "loaded", "modules", "in", "the", "minidump", ".", "An", "argument", "can", "be", "passed", "to", "limit", "the", "output", "to", "only", "those", "modules", "that", "contain", "the", "argument", "as", "a", "substring", "("...
def do_lm(self, arg): """ List details for all loaded modules in the minidump. An argument can be passed to limit the output to only those modules that contain the argument as a substring (case insensitive match). """ for module in self.reader.module_list.modules: if arg: name = GetModuleName(self.reader, module).lower() if name.find(arg.lower()) >= 0: PrintModuleDetails(self.reader, module) else: PrintModuleDetails(self.reader, module) print
[ "def", "do_lm", "(", "self", ",", "arg", ")", ":", "for", "module", "in", "self", ".", "reader", ".", "module_list", ".", "modules", ":", "if", "arg", ":", "name", "=", "GetModuleName", "(", "self", ".", "reader", ",", "module", ")", ".", "lower", ...
https://github.com/runtimejs/runtime/blob/0a6e84c30823d35a4548d6634166784260ae7b74/deps/v8/tools/grokdump.py#L3030-L3043
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/mox.py
python
MockAnything._Reset
(self)
Reset the state of this mock to record mode with an empty queue.
Reset the state of this mock to record mode with an empty queue.
[ "Reset", "the", "state", "of", "this", "mock", "to", "record", "mode", "with", "an", "empty", "queue", "." ]
def _Reset(self): """Reset the state of this mock to record mode with an empty queue.""" # Maintain a list of method calls we are expecting self._expected_calls_queue = deque() # Make sure we are in setup mode, not replay mode self._replay_mode = False
[ "def", "_Reset", "(", "self", ")", ":", "# Maintain a list of method calls we are expecting", "self", ".", "_expected_calls_queue", "=", "deque", "(", ")", "# Make sure we are in setup mode, not replay mode", "self", ".", "_replay_mode", "=", "False" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/mox.py#L349-L356
javafxports/openjdk-jfx
6eabc8c84f698c04548395826a8bb738087666b5
modules/javafx.web/src/main/native/Source/JavaScriptCore/disassembler/udis86/ud_opcode.py
python
UdOpcodeTables.getMnemonicsList
(self)
return sorted(self._mnemonics.keys())
Returns a sorted list of mnemonics
Returns a sorted list of mnemonics
[ "Returns", "a", "sorted", "list", "of", "mnemonics" ]
def getMnemonicsList(self): """Returns a sorted list of mnemonics""" return sorted(self._mnemonics.keys())
[ "def", "getMnemonicsList", "(", "self", ")", ":", "return", "sorted", "(", "self", ".", "_mnemonics", ".", "keys", "(", ")", ")" ]
https://github.com/javafxports/openjdk-jfx/blob/6eabc8c84f698c04548395826a8bb738087666b5/modules/javafx.web/src/main/native/Source/JavaScriptCore/disassembler/udis86/ud_opcode.py#L543-L545
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/debug/cli/analyzer_cli.py
python
DebugAnalyzer.print_source
(self, args, screen_info=None)
return output
Print the content of a source file.
Print the content of a source file.
[ "Print", "the", "content", "of", "a", "source", "file", "." ]
def print_source(self, args, screen_info=None): """Print the content of a source file.""" del screen_info # Unused. parsed = self._arg_parsers["print_source"].parse_args(args) source_annotation = source_utils.annotate_source( self._debug_dump, parsed.source_file_path, do_dumped_tensors=parsed.tensors) source_lines, line_num_width = source_utils.load_source( parsed.source_file_path) labeled_source_lines = [] actual_initial_scroll_target = 0 for i, line in enumerate(source_lines): annotated_line = RL("L%d" % (i + 1), cli_shared.COLOR_YELLOW) annotated_line += " " * (line_num_width - len(annotated_line)) annotated_line += line labeled_source_lines.append(annotated_line) if i + 1 == parsed.line_begin: actual_initial_scroll_target = len(labeled_source_lines) - 1 if i + 1 in source_annotation: sorted_elements = sorted(source_annotation[i + 1]) for k, element in enumerate(sorted_elements): if k >= parsed.max_elements_per_line: omitted_info_line = RL(" (... Omitted %d of %d %s ...) " % ( len(sorted_elements) - parsed.max_elements_per_line, len(sorted_elements), "tensor(s)" if parsed.tensors else "op(s)")) omitted_info_line += RL( "+5", debugger_cli_common.MenuItem( None, self._reconstruct_print_source_command( parsed, i + 1, max_elements_per_line_increase=5))) labeled_source_lines.append(omitted_info_line) break label = RL(" " * 4) if self._debug_dump.debug_watch_keys( debug_graphs.get_node_name(element)): attribute = debugger_cli_common.MenuItem("", "pt %s" % element) else: attribute = cli_shared.COLOR_BLUE label += RL(element, attribute) labeled_source_lines.append(label) output = debugger_cli_common.rich_text_lines_from_rich_line_list( labeled_source_lines, annotations={debugger_cli_common.INIT_SCROLL_POS_KEY: actual_initial_scroll_target}) _add_main_menu(output, node_name=None) return output
[ "def", "print_source", "(", "self", ",", "args", ",", "screen_info", "=", "None", ")", ":", "del", "screen_info", "# Unused.", "parsed", "=", "self", ".", "_arg_parsers", "[", "\"print_source\"", "]", ".", "parse_args", "(", "args", ")", "source_annotation", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/cli/analyzer_cli.py#L1107-L1164
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/eslint.py
python
get_base_dir
()
Get the base directory for mongo repo. This script assumes that it is running in buildscripts/, and uses that to find the base directory.
Get the base directory for mongo repo. This script assumes that it is running in buildscripts/, and uses that to find the base directory.
[ "Get", "the", "base", "directory", "for", "mongo", "repo", ".", "This", "script", "assumes", "that", "it", "is", "running", "in", "buildscripts", "/", "and", "uses", "that", "to", "find", "the", "base", "directory", "." ]
def get_base_dir(): """Get the base directory for mongo repo. This script assumes that it is running in buildscripts/, and uses that to find the base directory. """ try: return subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).rstrip() except: # We are not in a valid git directory. Use the script path instead. return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
[ "def", "get_base_dir", "(", ")", ":", "try", ":", "return", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'rev-parse'", ",", "'--show-toplevel'", "]", ")", ".", "rstrip", "(", ")", "except", ":", "# We are not in a valid git directory. Use the script...
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/eslint.py#L313-L322
ndrplz/self-driving-car
2bdcc7c822e8f03adc0a7490f1ae29a658720713
project_5_vehicle_detection/functions_utils.py
python
normalize_image
(img)
return np.uint8(img)
Normalize image between 0 and 255 and cast to uint8 (useful for visualization)
Normalize image between 0 and 255 and cast to uint8 (useful for visualization)
[ "Normalize", "image", "between", "0", "and", "255", "and", "cast", "to", "uint8", "(", "useful", "for", "visualization", ")" ]
def normalize_image(img): """ Normalize image between 0 and 255 and cast to uint8 (useful for visualization) """ img = np.float32(img) img = img / img.max() * 255 return np.uint8(img)
[ "def", "normalize_image", "(", "img", ")", ":", "img", "=", "np", ".", "float32", "(", "img", ")", "img", "=", "img", "/", "img", ".", "max", "(", ")", "*", "255", "return", "np", ".", "uint8", "(", "img", ")" ]
https://github.com/ndrplz/self-driving-car/blob/2bdcc7c822e8f03adc0a7490f1ae29a658720713/project_5_vehicle_detection/functions_utils.py#L4-L13
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/tools/grokdump.py
python
InspectionShell.do_do
(self, address)
return self.do_display_object(address)
see display_object
see display_object
[ "see", "display_object" ]
def do_do(self, address): """ see display_object """ return self.do_display_object(address)
[ "def", "do_do", "(", "self", ",", "address", ")", ":", "return", "self", ".", "do_display_object", "(", "address", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/tools/grokdump.py#L3543-L3545
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py
python
obj_analysis.has_name
(self)
return (not self.name is None)
Returns true if a name value exists.
Returns true if a name value exists.
[ "Returns", "true", "if", "a", "name", "value", "exists", "." ]
def has_name(self): """ Returns true if a name value exists. """ return (not self.name is None)
[ "def", "has_name", "(", "self", ")", ":", "return", "(", "not", "self", ".", "name", "is", "None", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py#L1729-L1731
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
RobotModelLink.getPositionJacobian
(self, plocal: "double const [3]")
return _robotsim.RobotModelLink_getPositionJacobian(self, plocal)
r""" getPositionJacobian(RobotModelLink self, double const [3] plocal) Computes the position jacobian of a point on this link w.r.t. the robot's configuration q. This matrix J gives the point's velocity (in world coordinates) via np.dot(J,dq), where dq is the robot's joint velocities. Returns: ndarray: the 3xn Jacobian matrix of the point given by local coordinates plocal.
r""" getPositionJacobian(RobotModelLink self, double const [3] plocal)
[ "r", "getPositionJacobian", "(", "RobotModelLink", "self", "double", "const", "[", "3", "]", "plocal", ")" ]
def getPositionJacobian(self, plocal: "double const [3]") -> "void": r""" getPositionJacobian(RobotModelLink self, double const [3] plocal) Computes the position jacobian of a point on this link w.r.t. the robot's configuration q. This matrix J gives the point's velocity (in world coordinates) via np.dot(J,dq), where dq is the robot's joint velocities. Returns: ndarray: the 3xn Jacobian matrix of the point given by local coordinates plocal. """ return _robotsim.RobotModelLink_getPositionJacobian(self, plocal)
[ "def", "getPositionJacobian", "(", "self", ",", "plocal", ":", "\"double const [3]\"", ")", "->", "\"void\"", ":", "return", "_robotsim", ".", "RobotModelLink_getPositionJacobian", "(", "self", ",", "plocal", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L4401-L4418
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/parsers/python_parser.py
python
PythonParser._buffered_line
(self)
Return a line from buffer, filling buffer if required.
Return a line from buffer, filling buffer if required.
[ "Return", "a", "line", "from", "buffer", "filling", "buffer", "if", "required", "." ]
def _buffered_line(self): """ Return a line from buffer, filling buffer if required. """ if len(self.buf) > 0: return self.buf[0] else: return self._next_line()
[ "def", "_buffered_line", "(", "self", ")", ":", "if", "len", "(", "self", ".", "buf", ")", ">", "0", ":", "return", "self", ".", "buf", "[", "0", "]", "else", ":", "return", "self", ".", "_next_line", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/parsers/python_parser.py#L577-L584
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/graph_kernel/model/model_builder.py
python
GraphBuilder.emit
(self, prim, inputs, name=None, attrs=None)
return output
Emit a new operation
Emit a new operation
[ "Emit", "a", "new", "operation" ]
def emit(self, prim, inputs, name=None, attrs=None): """Emit a new operation""" if attrs is None: attrs = {} if isinstance(inputs, (Tensor, Value)): inputs = [inputs] tensor_inputs = [t for t in inputs if isinstance(t, (Tensor, Value))] out_shape, out_dtype, out_format = op_infer.infer(prim, tensor_inputs, attrs) output = self.tensor(out_shape, out_dtype, out_format, name) self.op(prim, output, inputs, attrs) return output
[ "def", "emit", "(", "self", ",", "prim", ",", "inputs", ",", "name", "=", "None", ",", "attrs", "=", "None", ")", ":", "if", "attrs", "is", "None", ":", "attrs", "=", "{", "}", "if", "isinstance", "(", "inputs", ",", "(", "Tensor", ",", "Value", ...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/graph_kernel/model/model_builder.py#L98-L108
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PGProperty.RefreshChildren
(*args, **kwargs)
return _propgrid.PGProperty_RefreshChildren(*args, **kwargs)
RefreshChildren(self)
RefreshChildren(self)
[ "RefreshChildren", "(", "self", ")" ]
def RefreshChildren(*args, **kwargs): """RefreshChildren(self)""" return _propgrid.PGProperty_RefreshChildren(*args, **kwargs)
[ "def", "RefreshChildren", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGProperty_RefreshChildren", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L413-L415
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/rulerctrl.py
python
RulerCtrl.AddIndicator
(self, id, value)
Adds an indicator to :class:`RulerCtrl`. You should pass a unique `id` and a starting `value` for the indicator. :param `id`: the indicator identifier; :param `value`: the indicator initial value.
Adds an indicator to :class:`RulerCtrl`. You should pass a unique `id` and a starting `value` for the indicator.
[ "Adds", "an", "indicator", "to", ":", "class", ":", "RulerCtrl", ".", "You", "should", "pass", "a", "unique", "id", "and", "a", "starting", "value", "for", "the", "indicator", "." ]
def AddIndicator(self, id, value): """ Adds an indicator to :class:`RulerCtrl`. You should pass a unique `id` and a starting `value` for the indicator. :param `id`: the indicator identifier; :param `value`: the indicator initial value. """ self._indicators.append(Indicator(self, id, value)) self.Refresh()
[ "def", "AddIndicator", "(", "self", ",", "id", ",", "value", ")", ":", "self", ".", "_indicators", ".", "append", "(", "Indicator", "(", "self", ",", "id", ",", "value", ")", ")", "self", ".", "Refresh", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/rulerctrl.py#L1183-L1193
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/cephfs/mount.py
python
CephFSMount.setup_netns
(self)
Setup the netns for the mountpoint.
Setup the netns for the mountpoint.
[ "Setup", "the", "netns", "for", "the", "mountpoint", "." ]
def setup_netns(self): """ Setup the netns for the mountpoint. """ log.info("Setting the '{0}' netns for '{1}'".format(self._netns_name, self.mountpoint)) self._setup_brx_and_nat() self._setup_netns()
[ "def", "setup_netns", "(", "self", ")", ":", "log", ".", "info", "(", "\"Setting the '{0}' netns for '{1}'\"", ".", "format", "(", "self", ".", "_netns_name", ",", "self", ".", "mountpoint", ")", ")", "self", ".", "_setup_brx_and_nat", "(", ")", "self", ".",...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/cephfs/mount.py#L394-L400
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/sparse_ops.py
python
sparse_fill_empty_rows
(sp_input, default_value, name=None)
Fills empty rows in the input 2-D `SparseTensor` with a default value. This op adds entries with the specified `default_value` at index `[row, 0]` for any row in the input that does not already have a value. For example, suppose `sp_input` has shape `[5, 6]` and non-empty values: [0, 1]: a [0, 3]: b [2, 0]: c [3, 1]: d Rows 1 and 4 are empty, so the output will be of shape `[5, 6]` with values: [0, 1]: a [0, 3]: b [1, 0]: default_value [2, 0]: c [3, 1]: d [4, 0]: default_value Note that the input may have empty columns at the end, with no effect on this op. The output `SparseTensor` will be in row-major order and will have the same shape as the input. This op also returns an indicator vector such that empty_row_indicator[i] = True iff row i was an empty row. Args: sp_input: A `SparseTensor` with shape `[N, M]`. default_value: The value to fill for empty rows, with the same type as `sp_input.` name: A name prefix for the returned tensors (optional) Returns: sp_ordered_output: A `SparseTensor` with shape `[N, M]`, and with all empty rows filled in with `default_value`. empty_row_indicator: A bool vector of length `N` indicating whether each input row was empty. Raises: TypeError: If `sp_input` is not a `SparseTensor`.
Fills empty rows in the input 2-D `SparseTensor` with a default value.
[ "Fills", "empty", "rows", "in", "the", "input", "2", "-", "D", "SparseTensor", "with", "a", "default", "value", "." ]
def sparse_fill_empty_rows(sp_input, default_value, name=None): """Fills empty rows in the input 2-D `SparseTensor` with a default value. This op adds entries with the specified `default_value` at index `[row, 0]` for any row in the input that does not already have a value. For example, suppose `sp_input` has shape `[5, 6]` and non-empty values: [0, 1]: a [0, 3]: b [2, 0]: c [3, 1]: d Rows 1 and 4 are empty, so the output will be of shape `[5, 6]` with values: [0, 1]: a [0, 3]: b [1, 0]: default_value [2, 0]: c [3, 1]: d [4, 0]: default_value Note that the input may have empty columns at the end, with no effect on this op. The output `SparseTensor` will be in row-major order and will have the same shape as the input. This op also returns an indicator vector such that empty_row_indicator[i] = True iff row i was an empty row. Args: sp_input: A `SparseTensor` with shape `[N, M]`. default_value: The value to fill for empty rows, with the same type as `sp_input.` name: A name prefix for the returned tensors (optional) Returns: sp_ordered_output: A `SparseTensor` with shape `[N, M]`, and with all empty rows filled in with `default_value`. empty_row_indicator: A bool vector of length `N` indicating whether each input row was empty. Raises: TypeError: If `sp_input` is not a `SparseTensor`. """ if not isinstance(sp_input, ops.SparseTensor): raise TypeError("Input must be a SparseTensor") with ops.op_scope([sp_input], name, "SparseFillEmptyRows"): default_value = ops.convert_to_tensor(default_value, dtype=sp_input.values.dtype) num_rows = math_ops.cast(sp_input.shape[0], dtypes.int32) all_row_indices = math_ops.cast(math_ops.range(num_rows), dtypes.int64) empty_row_indices, _ = array_ops.list_diff(all_row_indices, sp_input.indices[:, 0]) empty_row_indicator = sparse_to_dense( empty_row_indices, array_ops.expand_dims(sp_input.shape[0], -1), True, False) empty_row_indices_as_column = array_ops.reshape(empty_row_indices, [-1, 1]) additional_indices = array_ops.concat( 1, [empty_row_indices_as_column, array_ops.zeros_like(empty_row_indices_as_column)]) additional_values = array_ops.fill( array_ops.shape(empty_row_indices), default_value) all_indices_unordered = array_ops.concat(0, [sp_input.indices, additional_indices]) all_values_unordered = array_ops.concat(0, [sp_input.values, additional_values]) sp_unordered_output = ops.SparseTensor(all_indices_unordered, all_values_unordered, sp_input.shape) sp_ordered_output = sparse_reorder(sp_unordered_output) return sp_ordered_output, empty_row_indicator
[ "def", "sparse_fill_empty_rows", "(", "sp_input", ",", "default_value", ",", "name", "=", "None", ")", ":", "if", "not", "isinstance", "(", "sp_input", ",", "ops", ".", "SparseTensor", ")", ":", "raise", "TypeError", "(", "\"Input must be a SparseTensor\"", ")",...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/sparse_ops.py#L1014-L1091
nyuwireless-unipd/ns3-mmwave
4ff9e87e8079764e04cbeccd8e85bff15ae16fb3
src/visualizer/visualizer/ipython_view.py
python
IPythonView.raw_input
(self, prompt='')
return self.getCurrentLine()
! Custom raw_input() replacement. Gets current line from console buffer. @param prompt: Prompt to print. Here for compatibility as replacement. @return The current command line text.
! Custom raw_input() replacement. Gets current line from console buffer.
[ "!", "Custom", "raw_input", "()", "replacement", ".", "Gets", "current", "line", "from", "console", "buffer", "." ]
def raw_input(self, prompt=''): """! Custom raw_input() replacement. Gets current line from console buffer. @param prompt: Prompt to print. Here for compatibility as replacement. @return The current command line text. """ if self.interrupt: self.interrupt = False raise KeyboardInterrupt return self.getCurrentLine()
[ "def", "raw_input", "(", "self", ",", "prompt", "=", "''", ")", ":", "if", "self", ".", "interrupt", ":", "self", ".", "interrupt", "=", "False", "raise", "KeyboardInterrupt", "return", "self", ".", "getCurrentLine", "(", ")" ]
https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/src/visualizer/visualizer/ipython_view.py#L599-L609
BVLC/caffe
9b891540183ddc834a02b2bd81b31afae71b2153
python/caffe/coord_map.py
python
inverse
(coord_map)
return ax, 1 / a, -b / a
Invert a coord map by de-scaling and un-shifting; this gives the backward mapping for the gradient.
Invert a coord map by de-scaling and un-shifting; this gives the backward mapping for the gradient.
[ "Invert", "a", "coord", "map", "by", "de", "-", "scaling", "and", "un", "-", "shifting", ";", "this", "gives", "the", "backward", "mapping", "for", "the", "gradient", "." ]
def inverse(coord_map): """ Invert a coord map by de-scaling and un-shifting; this gives the backward mapping for the gradient. """ ax, a, b = coord_map return ax, 1 / a, -b / a
[ "def", "inverse", "(", "coord_map", ")", ":", "ax", ",", "a", ",", "b", "=", "coord_map", "return", "ax", ",", "1", "/", "a", ",", "-", "b", "/", "a" ]
https://github.com/BVLC/caffe/blob/9b891540183ddc834a02b2bd81b31afae71b2153/python/caffe/coord_map.py#L106-L112
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/avr8target.py
python
TinyXAvrTarget.activate_physical
(self, use_reset=False, user_interaction_callback=None)
Override function for high-voltage activation for UPDI :param use_reset: Use external reset line during activation (only used for Mega JTAG interface) :param user_interaction_callback: Callback to be called when user interaction is required, for example when doing UPDI high-voltage activation with user target power toggle. This function could ask the user to toggle power and halt execution waiting for the user to respond (this is default behavior if the callback is None), or if the user is another script it could toggle power automatically and then return.
Override function for high-voltage activation for UPDI
[ "Override", "function", "for", "high", "-", "voltage", "activation", "for", "UPDI" ]
def activate_physical(self, use_reset=False, user_interaction_callback=None): """ Override function for high-voltage activation for UPDI :param use_reset: Use external reset line during activation (only used for Mega JTAG interface) :param user_interaction_callback: Callback to be called when user interaction is required, for example when doing UPDI high-voltage activation with user target power toggle. This function could ask the user to toggle power and halt execution waiting for the user to respond (this is default behavior if the callback is None), or if the user is another script it could toggle power automatically and then return. """ try: return self.protocol.activate_physical(use_reset) except Jtagice3ResponseError as error: if error.code == Avr8Protocol.AVR8_FAILURE_PLEASE_TOGGLE_POWER: if self.use_hv == Avr8Protocol.UPDI_HV_USER_POWER_TOGGLE: if user_interaction_callback is None: # Default behavior is to wait for the user to toggle power input("Toggle power now") else: user_interaction_callback() # During pounce, or at window timeout, firmware clears the "user power toggle" flag # However MPLAB will always set this before each activate, so the parameter is set again here # to most-accurately reflect front-end behaviour for test purposes self.protocol.set_byte(Avr8Protocol.AVR8_CTXT_OPTIONS, Avr8Protocol.AVR8_OPT_HV_UPDI_ENABLE, self.use_hv) return self.protocol.activate_physical(use_reset) raise
[ "def", "activate_physical", "(", "self", ",", "use_reset", "=", "False", ",", "user_interaction_callback", "=", "None", ")", ":", "try", ":", "return", "self", ".", "protocol", ".", "activate_physical", "(", "use_reset", ")", "except", "Jtagice3ResponseError", "...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/avr8target.py#L347-L374
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
TextEntryBase.GetMargins
(*args, **kwargs)
return _core_.TextEntryBase_GetMargins(*args, **kwargs)
GetMargins(self) -> Point
GetMargins(self) -> Point
[ "GetMargins", "(", "self", ")", "-", ">", "Point" ]
def GetMargins(*args, **kwargs): """GetMargins(self) -> Point""" return _core_.TextEntryBase_GetMargins(*args, **kwargs)
[ "def", "GetMargins", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "TextEntryBase_GetMargins", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13357-L13359
pytorch/ELF
e851e786ced8d26cf470f08a6b9bf7e413fc63f7
src_py/rlpytorch/utils/fp16_utils.py
python
apply_nonrecursive
(module, fn)
return module
Applies a given function only to parameters and buffers of a module. Adapted from torch.nn.Module._apply.
Applies a given function only to parameters and buffers of a module.
[ "Applies", "a", "given", "function", "only", "to", "parameters", "and", "buffers", "of", "a", "module", "." ]
def apply_nonrecursive(module, fn): """Applies a given function only to parameters and buffers of a module. Adapted from torch.nn.Module._apply. """ for param in module._parameters.values(): if param is not None: # Tensors stored in modules are graph leaves, and we don't # want to create copy nodes, so we have to unpack the data. param.data = fn(param.data) if param._grad is not None: param._grad.data = fn(param._grad.data) for key, buf in module._buffers.items(): if buf is not None: module._buffers[key] = fn(buf) return module
[ "def", "apply_nonrecursive", "(", "module", ",", "fn", ")", ":", "for", "param", "in", "module", ".", "_parameters", ".", "values", "(", ")", ":", "if", "param", "is", "not", "None", ":", "# Tensors stored in modules are graph leaves, and we don't", "# want to cre...
https://github.com/pytorch/ELF/blob/e851e786ced8d26cf470f08a6b9bf7e413fc63f7/src_py/rlpytorch/utils/fp16_utils.py#L11-L28
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/sunf95.py
python
generate
(env)
Add Builders and construction variables for sunf95 to an Environment.
Add Builders and construction variables for sunf95 to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "sunf95", "to", "an", "Environment", "." ]
def generate(env): """Add Builders and construction variables for sunf95 to an Environment.""" add_all_to_env(env) fcomp = env.Detect(compilers) or 'f95' env['FORTRAN'] = fcomp env['F95'] = fcomp env['SHFORTRAN'] = '$FORTRAN' env['SHF95'] = '$F95' env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC') env['SHF95FLAGS'] = SCons.Util.CLVar('$F95FLAGS -KPIC')
[ "def", "generate", "(", "env", ")", ":", "add_all_to_env", "(", "env", ")", "fcomp", "=", "env", ".", "Detect", "(", "compilers", ")", "or", "'f95'", "env", "[", "'FORTRAN'", "]", "=", "fcomp", "env", "[", "'F95'", "]", "=", "fcomp", "env", "[", "'...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/sunf95.py#L42-L55
modm-io/modm
845840ec08566a3aa9c04167b1a18a56255afa4f
tools/xpcc_generator/xmlparser/type.py
python
BaseType.create_hierarchy
(self)
Create the type hierarchy This method calculates the values for self.size and self.level. Must not be called before all types are fully created.
Create the type hierarchy
[ "Create", "the", "type", "hierarchy" ]
def create_hierarchy(self): """ Create the type hierarchy This method calculates the values for self.size and self.level. Must not be called before all types are fully created. """ pass
[ "def", "create_hierarchy", "(", "self", ")", ":", "pass" ]
https://github.com/modm-io/modm/blob/845840ec08566a3aa9c04167b1a18a56255afa4f/tools/xpcc_generator/xmlparser/type.py#L77-L83
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/Maya_AnimationRiggingTools/MayaTools/General/Scripts/ART_skeletonBuilder_UI.py
python
SkeletonBuilder_UI.publish
(self, project, characterName, handCtrlSpace, *args)
cmds.select("root", hi = True) joints = cmds.ls(sl = True) for joint in joints: cmds.setAttr(joint + ".rx", 0) cmds.setAttr(joint + ".ry", 0) cmds.setAttr(joint + ".rz", 0)
cmds.select("root", hi = True) joints = cmds.ls(sl = True) for joint in joints: cmds.setAttr(joint + ".rx", 0) cmds.setAttr(joint + ".ry", 0) cmds.setAttr(joint + ".rz", 0)
[ "cmds", ".", "select", "(", "root", "hi", "=", "True", ")", "joints", "=", "cmds", ".", "ls", "(", "sl", "=", "True", ")", "for", "joint", "in", "joints", ":", "cmds", ".", "setAttr", "(", "joint", "+", ".", "rx", "0", ")", "cmds", ".", "setAtt...
def publish(self, project, characterName, handCtrlSpace, *args): sourceControl = False #unlock joints cmds.select("root", hi = True) joints = cmds.ls(sl = True) for joint in joints: cmds.lockNode(joint, lock = False) #clear any keys on the joints cmds.select("root", hi = True) cmds.cutKey() #add the icon attr to the SceneLocked node if cmds.objExists("SceneLocked.iconPath"): cmds.setAttr("SceneLocked.iconPath", self.mayaToolsDir + "/General/Icons/ART/Thumbnails/" + project + "/" + characterName + ".bmp", type = 'string') else: cmds.select("SceneLocked") cmds.lockNode("SceneLocked", lock = False) cmds.addAttr(ln = "iconPath", dt = 'string') cmds.setAttr("SceneLocked.iconPath", self.mayaToolsDir + "/General/Icons/ART/Thumbnails/" + project + "/" + characterName + ".bmp", type = 'string') cmds.lockNode("SceneLocked", lock = True) #set the model and joint mover back to rig pose #old code """ cmds.select("root", hi = True) joints = cmds.ls(sl = True) for joint in joints: cmds.setAttr(joint + ".rx", 0) cmds.setAttr(joint + ".ry", 0) cmds.setAttr(joint + ".rz", 0) """ self.setRigPose_Skel() self.setRigPose_JM() cmds.select("root") cmds.setToolTo( 'moveSuperContext' ) cmds.refresh(force = True) cmds.select(clear = True) #check if a pre script is loaded, and if so, save path in scene if not cmds.objExists("SkeletonSettings_Cache.preScriptPath"): cmds.addAttr("SkeletonSettings_Cache", ln = "preScriptPath", dt = 'string') scriptPath = cmds.textField(self.widgets["publishUIPreScriptField"], q = True, text = True) if scriptPath.find(".py") != -1 or scriptPath.find(".mel") != -1: cmds.setAttr("SkeletonSettings_Cache.preScriptPath", scriptPath, type = 'string') cmds.setAttr("SkeletonSettings_Cache.preScriptPath", keyable = False) #check if a post script is loaded, and if so, save path in scene if not cmds.objExists("SkeletonSettings_Cache.postScriptPath"): cmds.addAttr("SkeletonSettings_Cache", ln = "postScriptPath", dt = 'string') scriptPath = cmds.textField(self.widgets["publishUIPostScriptField"], q = True, text = True) if scriptPath.find(".py") != -1 or scriptPath.find(".mel") != -1: cmds.setAttr("SkeletonSettings_Cache.postScriptPath", scriptPath, type = 'string') cmds.setAttr("SkeletonSettings_Cache.postScriptPath", keyable = False) #save out "export" file exportPath = self.mayaToolsDir + "/General/ART/Projects/" + project + "/ExportFiles/" if not os.path.exists(exportPath): os.makedirs(exportPath) #check if source control is on settingsLocation = self.mayaToolsDir + "/General/Scripts/projectSettings.txt" if os.path.exists(settingsLocation): f = open(settingsLocation, 'r') settings = cPickle.load(f) f.close() sourceControl = settings.get("UseSourceControl") #save the export file out cmds.file(rename = exportPath + characterName + "_Export.mb") #try to save the file try: cmds.file(save = True, type = "mayaBinary", force = True, prompt = True) except Exception, e: if sourceControl == False: cmds.confirmDialog(title = "Publish", icon = "critical", message = str(e)) return else: #if using source control, check to see if we can check out the file result = cmds.confirmDialog(title = "Publish", icon = "critical", message = "Could not save Export file. File may exist already and be marked as read only.", button = ["Check Out File", "Cancel"]) if result == "Check Out File": import perforceUtils reload(perforceUtils) writeable = perforceUtils.p4_checkOutCurrentFile(exportPath + characterName + "_Export.mb") if writeable: #now that it is checked out, try saving again try: cmds.file(save = True, type = "mayaBinary", force = True, prompt = True) except: cmds.confirmDialog(title = "Publish", icon = "critical", message = "Perforce operation unsucessful. Could not save file. Aborting operation.") return else: cmds.warning("Operation Aborted") return else: cmds.warning("Operation Aborted.") return #Execute Pre Build Script if present script = cmds.textField(self.widgets["publishUIPreScriptField"], q = True, text = True) sourceType = "" preScriptStatus = None if script.find(".py") != -1: sourceType = "python" if script.find(".mel") != -1: sourceType = "mel" if sourceType == "mel": try: command = "" #open the file, and for each line in the file, add it to our command string. f = open(script, 'r') lines = f.readlines() for line in lines: command += line import maya.mel as mel mel.eval(command) #try to save out the export file try: cmds.file(save = True, type = "mayaBinary", force = True, prompt = True) preScriptStatus = True except: preScriptStatus = False except: preScriptStatus = False if sourceType == "python": try: execfile("" + script + "") #try to save out the export file try: cmds.file(save = True, type = "mayaBinary", force = True, prompt = True) preScriptStatus = True except: preScriptStatus = False except: preScriptStatus = False #create new file cmds.file( force=True, new=True ) #reference in export file with no namespace cmds.file(exportPath + characterName + "_Export.mb", r = True, type = "mayaBinary", loadReferenceDepth = "all", mergeNamespacesOnClash = True, namespace = ":", options = "v=0") #clear selection and fit view cmds.select(clear = True) cmds.viewFit() panels = cmds.getPanel(type = 'modelPanel') #turn on smooth shading for panel in panels: editor = cmds.modelPanel(panel, q = True, modelEditor = True) cmds.modelEditor(editor, edit = True, displayAppearance = "smoothShaded", displayTextures = True, textures = True ) self.setRigPose_JM() cmds.select("root") cmds.setToolTo( 'moveSuperContext' ) cmds.refresh(force = True) cmds.select(clear = True) #Import Auto Rig Class to build rig on skeleton import ART_autoRigger reload(ART_autoRigger) ART_autoRigger.AutoRigger(handCtrlSpace, self.widgets["publishUI_ProgressBar"]) #find all skeleton mesh geo and add to a layer and hide the layer if cmds.objExists("skeleton_skin_mesh*"): cmds.select("skeleton_skin_mesh_*") skelGeo = cmds.ls(sl = True, type = "transform") cmds.select(clear = True) #add skelGeo to a display layer cmds.select(skelGeo) cmds.createDisplayLayer(name = "skeleton_geometry_layer", nr = True) cmds.setAttr("skeleton_geometry_layer.enabled", 1) cmds.setAttr("skeleton_geometry_layer.displayType", 2) cmds.setAttr("skeleton_geometry_layer.visibility", 0) cmds.select(clear = True) cmds.select(clear = True) #Save out anim rig file rigPath = self.mayaToolsDir + "/General/ART/Projects/" + project + "/AnimRigs/" if not os.path.exists(rigPath): os.makedirs(rigPath) cmds.file(rename = rigPath + characterName + ".mb") #try to save out the anim rig file try: cmds.file(save = True, type = "mayaBinary", force = True, prompt = True) except: if sourceControl == False: cmds.confirmDialog(title = "Publish", icon = "critical", message = "Could not save file: " + str(rigPath + characterName) + ".mb not a valid file.\n File may exist already and be marked as read only. Aborting operation.") return else: #check to see if the file is currently checked out result = cmds.confirmDialog(title = "Publish", icon = "critical", message = "Could not save Animation Rig file. File may exist already and be marked as read only.", button = ["Check Out File", "Cancel"]) if result == "Check Out File": import perforceUtils reload(perforceUtils) writeable = perforceUtils.p4_checkOutCurrentFile(rigPath + characterName + ".mb") if writeable: #try to save the file again now that it is checked out try: cmds.file(save = True, type = "mayaBinary", force = True) except: cmds.confirmDialog(title = "Publish", icon = "critical", message = "Perforce operation unsucessful. Could not save file. Aborting operation.") else: cmds.confirmDialog(title = "Publish", icon = "critical", message = "Perforce operation unsucessful. Could not save file. Aborting operation.") return else: cmds.confirmDialog(title = "Publish", icon = "critical", message = "Perforce operation unsucessful. Could not save file. Aborting operation.") return #check to see if there was a post script to execute script = cmds.textField(self.widgets["publishUIPostScriptField"], q = True, text = True) sourceType = "" postScriptStatus = None if script.find(".py") != -1: sourceType = "python" if script.find(".mel") != -1: sourceType = "mel" if sourceType == "mel": try: command = "" #open the file, and for each line in the file, add it to our command string. f = open(script, 'r') lines = f.readlines() for line in lines: command += line import maya.mel as mel mel.eval(command) #try to save out the anim rig file try: cmds.file(save = True, type = "mayaBinary", force = True, prompt = True) postScriptStatus = True except: postScriptStatus = False except: postScriptStatus = False if sourceType == "python": try: execfile("" + script + "") #try to save out the anim rig file try: cmds.file(save = True, type = "mayaBinary", force = True, prompt = True) postScriptStatus = True except: postScriptStatus = False except Exception as e: postScriptStatus = False cmds.confirmDialog(m=str(e)) #delete publish UI cmds.deleteUI(self.widgets["publishUIWindow"]) #show results UI if sourceControl == False: self.publishUI_Results(False, preScriptStatus, postScriptStatus, self.mayaToolsDir + "/General/ART/Projects/" + project + "/ExportFiles/" + characterName + "_Export.mb", self.mayaToolsDir + "/General/ART/Projects/" + project + "/AnimRigs/" + characterName + ".mb", self.mayaToolsDir + "/General/Icons/ART/Thumbnails/" + project + "/" + characterName + ".bmp", self.mayaToolsDir + "/General/Icons/ART/Thumbnails/" + project + "/" + characterName + "_small.bmp") if sourceControl == True: self.publishUI_Results(True, preScriptStatus, postScriptStatus, self.mayaToolsDir + "/General/ART/Projects/" + project + "/ExportFiles/" + characterName + "_Export.mb", self.mayaToolsDir + "/General/ART/Projects/" + project + "/AnimRigs/" + characterName + ".mb", self.mayaToolsDir + "/General/Icons/ART/Thumbnails/" + project + "/" + characterName + ".bmp", self.mayaToolsDir + "/General/Icons/ART/Thumbnails/" + project + "/" + characterName + "_small.bmp")
[ "def", "publish", "(", "self", ",", "project", ",", "characterName", ",", "handCtrlSpace", ",", "*", "args", ")", ":", "sourceControl", "=", "False", "#unlock joints", "cmds", ".", "select", "(", "\"root\"", ",", "hi", "=", "True", ")", "joints", "=", "c...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/Maya_AnimationRiggingTools/MayaTools/General/Scripts/ART_skeletonBuilder_UI.py#L7358-L7692
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
External/pymol/modules/pymol/rpc.py
python
rpcIdentify
(what='all', mode=0)
return cmd.identify(what, mode=mode)
returns the results of cmd.identify(what,mode)
returns the results of cmd.identify(what,mode)
[ "returns", "the", "results", "of", "cmd", ".", "identify", "(", "what", "mode", ")" ]
def rpcIdentify(what='all', mode=0): """ returns the results of cmd.identify(what,mode) """ return cmd.identify(what, mode=mode)
[ "def", "rpcIdentify", "(", "what", "=", "'all'", ",", "mode", "=", "0", ")", ":", "return", "cmd", ".", "identify", "(", "what", ",", "mode", "=", "mode", ")" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/External/pymol/modules/pymol/rpc.py#L519-L521
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/python_version/optimization.py
python
GradientDescentOptimizer.__init__
(self, domain, optimizable, optimizer_parameters, num_random_samples=None)
Construct a GradientDescentOptimizer. :param domain: the domain that this optimizer operates over :type domain: interfaces.domain_interface.DomainInterface subclass :param optimizable: object representing the objective function being optimized :type optimizable: interfaces.optimization_interface.OptimizableInterface subclass :param optimizer_parameters: parameters describing how to perform optimization (tolerances, iterations, etc.) :type optimizer_parameters: python_version.optimization.GradientDescentParameters object
Construct a GradientDescentOptimizer.
[ "Construct", "a", "GradientDescentOptimizer", "." ]
def __init__(self, domain, optimizable, optimizer_parameters, num_random_samples=None): """Construct a GradientDescentOptimizer. :param domain: the domain that this optimizer operates over :type domain: interfaces.domain_interface.DomainInterface subclass :param optimizable: object representing the objective function being optimized :type optimizable: interfaces.optimization_interface.OptimizableInterface subclass :param optimizer_parameters: parameters describing how to perform optimization (tolerances, iterations, etc.) :type optimizer_parameters: python_version.optimization.GradientDescentParameters object """ self.domain = domain self.objective_function = optimizable self.optimizer_parameters = optimizer_parameters
[ "def", "__init__", "(", "self", ",", "domain", ",", "optimizable", ",", "optimizer_parameters", ",", "num_random_samples", "=", "None", ")", ":", "self", ".", "domain", "=", "domain", "self", ".", "objective_function", "=", "optimizable", "self", ".", "optimiz...
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/python_version/optimization.py#L400-L413
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
EncodeRspFileList
(args)
return program + ' ' + ' '.join(QuoteForRspFile(arg) for arg in args[1:])
Process a list of arguments using QuoteCmdExeArgument.
Process a list of arguments using QuoteCmdExeArgument.
[ "Process", "a", "list", "of", "arguments", "using", "QuoteCmdExeArgument", "." ]
def EncodeRspFileList(args): """Process a list of arguments using QuoteCmdExeArgument.""" # Note that the first argument is assumed to be the command. Don't add # quotes around it because then built-ins like 'echo', etc. won't work. # Take care to normpath only the path in the case of 'call ../x.bat' because # otherwise the whole thing is incorrectly interpreted as a path and not # normalized correctly. if not args: return '' if args[0].startswith('call '): call, program = args[0].split(' ', 1) program = call + ' ' + os.path.normpath(program) else: program = os.path.normpath(args[0]) return program + ' ' + ' '.join(QuoteForRspFile(arg) for arg in args[1:])
[ "def", "EncodeRspFileList", "(", "args", ")", ":", "# Note that the first argument is assumed to be the command. Don't add", "# quotes around it because then built-ins like 'echo', etc. won't work.", "# Take care to normpath only the path in the case of 'call ../x.bat' because", "# otherwise the w...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L53-L66
openmm/openmm
cb293447c4fc8b03976dfe11399f107bab70f3d9
wrappers/python/openmm/app/internal/amber_file_parser.py
python
PrmtopLoader.getUreyBradleys
(self)
return self._ureyBradleyList
Return list of atom pairs, K, and Rmin for each Urey-Bradley term
Return list of atom pairs, K, and Rmin for each Urey-Bradley term
[ "Return", "list", "of", "atom", "pairs", "K", "and", "Rmin", "for", "each", "Urey", "-", "Bradley", "term" ]
def getUreyBradleys(self): """Return list of atom pairs, K, and Rmin for each Urey-Bradley term""" try: return self._ureyBradleyList except AttributeError: pass self._ureyBradleyList = [] if 'CHARMM_UREY_BRADLEY' in self._raw_data: ureyBradleyPointers = self._raw_data["CHARMM_UREY_BRADLEY"] forceConstant = self._raw_data["CHARMM_UREY_BRADLEY_FORCE_CONSTANT"] equilValue = self._raw_data["CHARMM_UREY_BRADLEY_EQUIL_VALUE"] forceConstConversionFactor = (units.kilocalorie_per_mole/(units.angstrom*units.angstrom)).conversion_factor_to(units.kilojoule_per_mole/(units.nanometer*units.nanometer)) lengthConversionFactor = units.angstrom.conversion_factor_to(units.nanometer) for ii in range(0, len(ureyBradleyPointers), 3): if int(ureyBradleyPointers[ii]) < 0 or int(ureyBradleyPointers[ii+1]) < 0: raise Exception("Found negative Urey-Bradley atom pointers %s" % ((ureyBradleyPointers[ii], ureyBradleyPointers[ii+1]))) iType = int(ureyBradleyPointers[ii+2])-1 self._ureyBradleyList.append((int(ureyBradleyPointers[ii])-1, int(ureyBradleyPointers[ii+1])-1, float(forceConstant[iType])*forceConstConversionFactor, float(equilValue[iType])*lengthConversionFactor)) return self._ureyBradleyList
[ "def", "getUreyBradleys", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_ureyBradleyList", "except", "AttributeError", ":", "pass", "self", ".", "_ureyBradleyList", "=", "[", "]", "if", "'CHARMM_UREY_BRADLEY'", "in", "self", ".", "_raw_data", ":",...
https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/internal/amber_file_parser.py#L432-L454
apache/madlib
be297fe6beada0640f93317e8948834032718e32
src/madpack/madpack.py
python
_db_rename_schema
(from_schema, to_schema)
Rename schema @param from_schema name of the schema to rename @param to_schema new name for the schema
Rename schema
[ "Rename", "schema" ]
def _db_rename_schema(from_schema, to_schema): """ Rename schema @param from_schema name of the schema to rename @param to_schema new name for the schema """ info_(this, "> Renaming schema %s to %s" % (from_schema, to_schema), True) try: _internal_run_query("ALTER SCHEMA %s RENAME TO %s;" % (from_schema, to_schema), True) except: error_(this, 'Cannot rename schema. Stopping installation...', False) raise Exception
[ "def", "_db_rename_schema", "(", "from_schema", ",", "to_schema", ")", ":", "info_", "(", "this", ",", "\"> Renaming schema %s to %s\"", "%", "(", "from_schema", ",", "to_schema", ")", ",", "True", ")", "try", ":", "_internal_run_query", "(", "\"ALTER SCHEMA %s RE...
https://github.com/apache/madlib/blob/be297fe6beada0640f93317e8948834032718e32/src/madpack/madpack.py#L577-L589