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
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/elb/__init__.py
python
ELBConnection.set_lb_policies_of_listener
(self, lb_name, lb_port, policies)
return self.get_status('SetLoadBalancerPoliciesOfListener', params)
Associates, updates, or disables a policy with a listener on the load balancer. Currently only zero (0) or one (1) policy can be associated with a listener.
Associates, updates, or disables a policy with a listener on the load balancer. Currently only zero (0) or one (1) policy can be associated with a listener.
[ "Associates", "updates", "or", "disables", "a", "policy", "with", "a", "listener", "on", "the", "load", "balancer", ".", "Currently", "only", "zero", "(", "0", ")", "or", "one", "(", "1", ")", "policy", "can", "be", "associated", "with", "a", "listener", "." ]
def set_lb_policies_of_listener(self, lb_name, lb_port, policies): """ Associates, updates, or disables a policy with a listener on the load balancer. Currently only zero (0) or one (1) policy can be associated with a listener. """ params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port} if len(policies): self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesOfListener', params)
[ "def", "set_lb_policies_of_listener", "(", "self", ",", "lb_name", ",", "lb_port", ",", "policies", ")", ":", "params", "=", "{", "'LoadBalancerName'", ":", "lb_name", ",", "'LoadBalancerPort'", ":", "lb_port", "}", "if", "len", "(", "policies", ")", ":", "self", ".", "build_list_params", "(", "params", ",", "policies", ",", "'PolicyNames.member.%d'", ")", "else", ":", "params", "[", "'PolicyNames'", "]", "=", "''", "return", "self", ".", "get_status", "(", "'SetLoadBalancerPoliciesOfListener'", ",", "params", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/elb/__init__.py#L667-L679
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/ndimage/interpolation.py
python
zoom
(input, zoom, output=None, order=3, mode='constant', cval=0.0, prefilter=True)
return return_value
Zoom an array. The array is zoomed using spline interpolation of the requested order. Parameters ---------- input : ndarray The input array. zoom : float or sequence, optional The zoom factor along the axes. If a float, `zoom` is the same for each axis. If a sequence, `zoom` should contain one value for each axis. output : ndarray or dtype, optional The array in which to place the output, or the dtype of the returned array. order : int, optional The order of the spline interpolation, default is 3. The order has to be in the range 0-5. mode : str, optional Points outside the boundaries of the input are filled according to the given mode ('constant', 'nearest', 'reflect' or 'wrap'). Default is 'constant'. cval : scalar, optional Value used for points outside the boundaries of the input if ``mode='constant'``. Default is 0.0 prefilter : bool, optional The parameter prefilter determines if the input is pre-filtered with `spline_filter` before interpolation (necessary for spline interpolation of order > 1). If False, it is assumed that the input is already filtered. Default is True. Returns ------- zoom : ndarray or None The zoomed input. If `output` is given as a parameter, None is returned.
Zoom an array.
[ "Zoom", "an", "array", "." ]
def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0, prefilter=True): """ Zoom an array. The array is zoomed using spline interpolation of the requested order. Parameters ---------- input : ndarray The input array. zoom : float or sequence, optional The zoom factor along the axes. If a float, `zoom` is the same for each axis. If a sequence, `zoom` should contain one value for each axis. output : ndarray or dtype, optional The array in which to place the output, or the dtype of the returned array. order : int, optional The order of the spline interpolation, default is 3. The order has to be in the range 0-5. mode : str, optional Points outside the boundaries of the input are filled according to the given mode ('constant', 'nearest', 'reflect' or 'wrap'). Default is 'constant'. cval : scalar, optional Value used for points outside the boundaries of the input if ``mode='constant'``. Default is 0.0 prefilter : bool, optional The parameter prefilter determines if the input is pre-filtered with `spline_filter` before interpolation (necessary for spline interpolation of order > 1). If False, it is assumed that the input is already filtered. Default is True. Returns ------- zoom : ndarray or None The zoomed input. If `output` is given as a parameter, None is returned. """ if order < 0 or order > 5: raise RuntimeError('spline order not supported') input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') if input.ndim < 1: raise RuntimeError('input and output rank must be > 0') mode = _extend_mode_to_code(mode) if prefilter and order > 1: filtered = spline_filter(input, order, output=numpy.float64) else: filtered = input zoom = _ni_support._normalize_sequence(zoom, input.ndim) output_shape = tuple( [int(round(ii * jj)) for ii, jj in zip(input.shape, zoom)]) output_shape_old = tuple( [int(ii * jj) for ii, jj in zip(input.shape, zoom)]) if output_shape != output_shape_old: warnings.warn( "From scipy 0.13.0, the output shape of zoom() is calculated " "with round() instead of int() - for these inputs the size of " "the returned array has changed.", UserWarning) zoom_div = numpy.array(output_shape, float) - 1 zoom = (numpy.array(input.shape) - 1) / zoom_div # Zooming to non-finite values is unpredictable, so just choose # zoom factor 1 instead zoom[~numpy.isfinite(zoom)] = 1 output, return_value = _ni_support._get_output(output, input, shape=output_shape) zoom = numpy.asarray(zoom, dtype=numpy.float64) zoom = numpy.ascontiguousarray(zoom) _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval) return return_value
[ "def", "zoom", "(", "input", ",", "zoom", ",", "output", "=", "None", ",", "order", "=", "3", ",", "mode", "=", "'constant'", ",", "cval", "=", "0.0", ",", "prefilter", "=", "True", ")", ":", "if", "order", "<", "0", "or", "order", ">", "5", ":", "raise", "RuntimeError", "(", "'spline order not supported'", ")", "input", "=", "numpy", ".", "asarray", "(", "input", ")", "if", "numpy", ".", "iscomplexobj", "(", "input", ")", ":", "raise", "TypeError", "(", "'Complex type not supported'", ")", "if", "input", ".", "ndim", "<", "1", ":", "raise", "RuntimeError", "(", "'input and output rank must be > 0'", ")", "mode", "=", "_extend_mode_to_code", "(", "mode", ")", "if", "prefilter", "and", "order", ">", "1", ":", "filtered", "=", "spline_filter", "(", "input", ",", "order", ",", "output", "=", "numpy", ".", "float64", ")", "else", ":", "filtered", "=", "input", "zoom", "=", "_ni_support", ".", "_normalize_sequence", "(", "zoom", ",", "input", ".", "ndim", ")", "output_shape", "=", "tuple", "(", "[", "int", "(", "round", "(", "ii", "*", "jj", ")", ")", "for", "ii", ",", "jj", "in", "zip", "(", "input", ".", "shape", ",", "zoom", ")", "]", ")", "output_shape_old", "=", "tuple", "(", "[", "int", "(", "ii", "*", "jj", ")", "for", "ii", ",", "jj", "in", "zip", "(", "input", ".", "shape", ",", "zoom", ")", "]", ")", "if", "output_shape", "!=", "output_shape_old", ":", "warnings", ".", "warn", "(", "\"From scipy 0.13.0, the output shape of zoom() is calculated \"", "\"with round() instead of int() - for these inputs the size of \"", "\"the returned array has changed.\"", ",", "UserWarning", ")", "zoom_div", "=", "numpy", ".", "array", "(", "output_shape", ",", "float", ")", "-", "1", "zoom", "=", "(", "numpy", ".", "array", "(", "input", ".", "shape", ")", "-", "1", ")", "/", "zoom_div", "# Zooming to non-finite values is unpredictable, so just choose", "# zoom factor 1 instead", "zoom", "[", "~", "numpy", ".", "isfinite", "(", "zoom", ")", "]", "=", "1", "output", ",", "return_value", "=", "_ni_support", ".", "_get_output", "(", "output", ",", "input", ",", "shape", "=", "output_shape", ")", "zoom", "=", "numpy", ".", "asarray", "(", "zoom", ",", "dtype", "=", "numpy", ".", "float64", ")", "zoom", "=", "numpy", ".", "ascontiguousarray", "(", "zoom", ")", "_nd_image", ".", "zoom_shift", "(", "filtered", ",", "zoom", ",", "None", ",", "output", ",", "order", ",", "mode", ",", "cval", ")", "return", "return_value" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/ndimage/interpolation.py#L506-L582
mickem/nscp
79f89fdbb6da63f91bc9dedb7aea202fe938f237
scripts/python/lib/google/protobuf/internal/python_message.py
python
_AddPropertiesForFields
(descriptor, cls)
Adds properties for all fields in this protocol message type.
Adds properties for all fields in this protocol message type.
[ "Adds", "properties", "for", "all", "fields", "in", "this", "protocol", "message", "type", "." ]
def _AddPropertiesForFields(descriptor, cls): """Adds properties for all fields in this protocol message type.""" for field in descriptor.fields: _AddPropertiesForField(field, cls) if descriptor.is_extendable: # _ExtensionDict is just an adaptor with no state so we allocate a new one # every time it is accessed. cls.Extensions = property(lambda self: _ExtensionDict(self))
[ "def", "_AddPropertiesForFields", "(", "descriptor", ",", "cls", ")", ":", "for", "field", "in", "descriptor", ".", "fields", ":", "_AddPropertiesForField", "(", "field", ",", "cls", ")", "if", "descriptor", ".", "is_extendable", ":", "# _ExtensionDict is just an adaptor with no state so we allocate a new one", "# every time it is accessed.", "cls", ".", "Extensions", "=", "property", "(", "lambda", "self", ":", "_ExtensionDict", "(", "self", ")", ")" ]
https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/internal/python_message.py#L333-L341
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/xcodeproj_file.py
python
XCObject.Comment
(self)
return self.Name()
Return a comment string for the object. Most objects just use their name as the comment, but PBXProject uses different values. The returned comment is not escaped and does not have any comment marker strings applied to it.
Return a comment string for the object.
[ "Return", "a", "comment", "string", "for", "the", "object", "." ]
def Comment(self): """Return a comment string for the object. Most objects just use their name as the comment, but PBXProject uses different values. The returned comment is not escaped and does not have any comment marker strings applied to it. """ return self.Name()
[ "def", "Comment", "(", "self", ")", ":", "return", "self", ".", "Name", "(", ")" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/xcodeproj_file.py#L371-L381
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/inspector_protocol/jinja2/bccache.py
python
BytecodeCache.load_bytecode
(self, bucket)
Subclasses have to override this method to load bytecode into a bucket. If they are not able to find code in the cache for the bucket, it must not do anything.
Subclasses have to override this method to load bytecode into a bucket. If they are not able to find code in the cache for the bucket, it must not do anything.
[ "Subclasses", "have", "to", "override", "this", "method", "to", "load", "bytecode", "into", "a", "bucket", ".", "If", "they", "are", "not", "able", "to", "find", "code", "in", "the", "cache", "for", "the", "bucket", "it", "must", "not", "do", "anything", "." ]
def load_bytecode(self, bucket): """Subclasses have to override this method to load bytecode into a bucket. If they are not able to find code in the cache for the bucket, it must not do anything. """ raise NotImplementedError()
[ "def", "load_bytecode", "(", "self", ",", "bucket", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/bccache.py#L146-L151
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
unicycler/assembly_graph.py
python
AssemblyGraph.get_path_availability
(self, path)
Given a path, this function returns the fraction that is available. A segment is considered fully available it has a depth of above 0.5. Below that, availability drops towards 0. A single segment can have negative availability (if it has negative depth), but this function will only return a number from 0 to 1.
Given a path, this function returns the fraction that is available. A segment is considered fully available it has a depth of above 0.5. Below that, availability drops towards 0. A single segment can have negative availability (if it has negative depth), but this function will only return a number from 0 to 1.
[ "Given", "a", "path", "this", "function", "returns", "the", "fraction", "that", "is", "available", ".", "A", "segment", "is", "considered", "fully", "available", "it", "has", "a", "depth", "of", "above", "0", ".", "5", ".", "Below", "that", "availability", "drops", "towards", "0", ".", "A", "single", "segment", "can", "have", "negative", "availability", "(", "if", "it", "has", "negative", "depth", ")", "but", "this", "function", "will", "only", "return", "a", "number", "from", "0", "to", "1", "." ]
def get_path_availability(self, path): """ Given a path, this function returns the fraction that is available. A segment is considered fully available it has a depth of above 0.5. Below that, availability drops towards 0. A single segment can have negative availability (if it has negative depth), but this function will only return a number from 0 to 1. """ total_bases = 0 available_bases = 0.0 for seg_num in path: seg = self.segments[abs(seg_num)] if seg.depth >= 0.5: seg_availability = 1.0 else: seg_availability = 2 * seg.depth seg_len = seg.get_length() - self.overlap total_bases += seg_len available_bases += seg_len * seg_availability if total_bases == 0: return 1.0 else: return max(0.0, available_bases / total_bases)
[ "def", "get_path_availability", "(", "self", ",", "path", ")", ":", "total_bases", "=", "0", "available_bases", "=", "0.0", "for", "seg_num", "in", "path", ":", "seg", "=", "self", ".", "segments", "[", "abs", "(", "seg_num", ")", "]", "if", "seg", ".", "depth", ">=", "0.5", ":", "seg_availability", "=", "1.0", "else", ":", "seg_availability", "=", "2", "*", "seg", ".", "depth", "seg_len", "=", "seg", ".", "get_length", "(", ")", "-", "self", ".", "overlap", "total_bases", "+=", "seg_len", "available_bases", "+=", "seg_len", "*", "seg_availability", "if", "total_bases", "==", "0", ":", "return", "1.0", "else", ":", "return", "max", "(", "0.0", ",", "available_bases", "/", "total_bases", ")" ]
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/assembly_graph.py#L1885-L1906
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/base_events.py
python
BaseEventLoop.call_later
(self, delay, callback, *args, context=None)
return timer
Arrange for a callback to be called at a given time. Return a Handle: an opaque object with a cancel() method that can be used to cancel the call. The delay can be an int or float, expressed in seconds. It is always relative to the current time. Each callback will be called exactly once. If two callbacks are scheduled for exactly the same time, it undefined which will be called first. Any positional arguments after the callback will be passed to the callback when it is called.
Arrange for a callback to be called at a given time.
[ "Arrange", "for", "a", "callback", "to", "be", "called", "at", "a", "given", "time", "." ]
def call_later(self, delay, callback, *args, context=None): """Arrange for a callback to be called at a given time. Return a Handle: an opaque object with a cancel() method that can be used to cancel the call. The delay can be an int or float, expressed in seconds. It is always relative to the current time. Each callback will be called exactly once. If two callbacks are scheduled for exactly the same time, it undefined which will be called first. Any positional arguments after the callback will be passed to the callback when it is called. """ timer = self.call_at(self.time() + delay, callback, *args, context=context) if timer._source_traceback: del timer._source_traceback[-1] return timer
[ "def", "call_later", "(", "self", ",", "delay", ",", "callback", ",", "*", "args", ",", "context", "=", "None", ")", ":", "timer", "=", "self", ".", "call_at", "(", "self", ".", "time", "(", ")", "+", "delay", ",", "callback", ",", "*", "args", ",", "context", "=", "context", ")", "if", "timer", ".", "_source_traceback", ":", "del", "timer", ".", "_source_traceback", "[", "-", "1", "]", "return", "timer" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/base_events.py#L643-L663
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/program_members/uniform.py
python
Uniform.read
(self)
return self.mglo.data
Read the value of the uniform.
Read the value of the uniform.
[ "Read", "the", "value", "of", "the", "uniform", "." ]
def read(self) -> bytes: ''' Read the value of the uniform. ''' return self.mglo.data
[ "def", "read", "(", "self", ")", "->", "bytes", ":", "return", "self", ".", "mglo", ".", "data" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/program_members/uniform.py#L169-L174
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextParagraphLayoutBox.ClearListStyle
(*args, **kwargs)
return _richtext.RichTextParagraphLayoutBox_ClearListStyle(*args, **kwargs)
ClearListStyle(self, RichTextRange range, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool
ClearListStyle(self, RichTextRange range, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool
[ "ClearListStyle", "(", "self", "RichTextRange", "range", "int", "flags", "=", "RICHTEXT_SETSTYLE_WITH_UNDO", ")", "-", ">", "bool" ]
def ClearListStyle(*args, **kwargs): """ClearListStyle(self, RichTextRange range, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool""" return _richtext.RichTextParagraphLayoutBox_ClearListStyle(*args, **kwargs)
[ "def", "ClearListStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextParagraphLayoutBox_ClearListStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L1765-L1767
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib2to3/pgen2/tokenize.py
python
untokenize
(iterable)
return ut.untokenize(iterable)
Transform tokens back into Python source code. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited intput: # Output text will tokenize the back to the input t1 = [tok[:2] for tok in generate_tokens(f.readline)] newcode = untokenize(t1) readline = iter(newcode.splitlines(1)).next t2 = [tok[:2] for tokin generate_tokens(readline)] assert t1 == t2
Transform tokens back into Python source code.
[ "Transform", "tokens", "back", "into", "Python", "source", "code", "." ]
def untokenize(iterable): """Transform tokens back into Python source code. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited intput: # Output text will tokenize the back to the input t1 = [tok[:2] for tok in generate_tokens(f.readline)] newcode = untokenize(t1) readline = iter(newcode.splitlines(1)).next t2 = [tok[:2] for tokin generate_tokens(readline)] assert t1 == t2 """ ut = Untokenizer() return ut.untokenize(iterable)
[ "def", "untokenize", "(", "iterable", ")", ":", "ut", "=", "Untokenizer", "(", ")", "return", "ut", ".", "untokenize", "(", "iterable", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib2to3/pgen2/tokenize.py#L326-L345
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/pycc/cc.py
python
CC.export
(self, exported_name, sig)
return decorator
Mark a function for exporting in the extension module.
Mark a function for exporting in the extension module.
[ "Mark", "a", "function", "for", "exporting", "in", "the", "extension", "module", "." ]
def export(self, exported_name, sig): """ Mark a function for exporting in the extension module. """ fn_args, fn_retty = sigutils.normalize_signature(sig) sig = typing.signature(fn_retty, *fn_args) if exported_name in self._exported_functions: raise KeyError("duplicated export symbol %s" % (exported_name)) def decorator(func): entry = ExportEntry(exported_name, sig, func) self._exported_functions[exported_name] = entry return func return decorator
[ "def", "export", "(", "self", ",", "exported_name", ",", "sig", ")", ":", "fn_args", ",", "fn_retty", "=", "sigutils", ".", "normalize_signature", "(", "sig", ")", "sig", "=", "typing", ".", "signature", "(", "fn_retty", ",", "*", "fn_args", ")", "if", "exported_name", "in", "self", ".", "_exported_functions", ":", "raise", "KeyError", "(", "\"duplicated export symbol %s\"", "%", "(", "exported_name", ")", ")", "def", "decorator", "(", "func", ")", ":", "entry", "=", "ExportEntry", "(", "exported_name", ",", "sig", ",", "func", ")", "self", ".", "_exported_functions", "[", "exported_name", "]", "=", "entry", "return", "func", "return", "decorator" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/pycc/cc.py#L134-L148
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/minimum-knight-moves.py
python
Solution2.minKnightMoves
(self, x, y)
return dp(x, y)
:type x: int :type y: int :rtype: int
:type x: int :type y: int :rtype: int
[ ":", "type", "x", ":", "int", ":", "type", "y", ":", "int", ":", "rtype", ":", "int" ]
def minKnightMoves(self, x, y): """ :type x: int :type y: int :rtype: int """ def dp(x, y): x, y = abs(x), abs(y) if x < y: x, y = y, x if (x, y) not in self.__lookup: # greedy, smaller x, y is always better if not special cases self.__lookup[(x, y)] = min(dp(x-1, y-2), dp(x-2, y-1)) + 1 return self.__lookup[(x, y)] return dp(x, y)
[ "def", "minKnightMoves", "(", "self", ",", "x", ",", "y", ")", ":", "def", "dp", "(", "x", ",", "y", ")", ":", "x", ",", "y", "=", "abs", "(", "x", ")", ",", "abs", "(", "y", ")", "if", "x", "<", "y", ":", "x", ",", "y", "=", "y", ",", "x", "if", "(", "x", ",", "y", ")", "not", "in", "self", ".", "__lookup", ":", "# greedy, smaller x, y is always better if not special cases", "self", ".", "__lookup", "[", "(", "x", ",", "y", ")", "]", "=", "min", "(", "dp", "(", "x", "-", "1", ",", "y", "-", "2", ")", ",", "dp", "(", "x", "-", "2", ",", "y", "-", "1", ")", ")", "+", "1", "return", "self", ".", "__lookup", "[", "(", "x", ",", "y", ")", "]", "return", "dp", "(", "x", ",", "y", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/minimum-knight-moves.py#L55-L68
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/distributed/DoCollectionManager.py
python
DoCollectionManager.doFindAll
(self, str)
return matches
Returns list of distributed objects with matching str in value.
Returns list of distributed objects with matching str in value.
[ "Returns", "list", "of", "distributed", "objects", "with", "matching", "str", "in", "value", "." ]
def doFindAll(self, str): """ Returns list of distributed objects with matching str in value. """ matches = [] for value in self.doId2do.values(): if repr(value).find(str) >= 0: matches.append(value) return matches
[ "def", "doFindAll", "(", "self", ",", "str", ")", ":", "matches", "=", "[", "]", "for", "value", "in", "self", ".", "doId2do", ".", "values", "(", ")", ":", "if", "repr", "(", "value", ")", ".", "find", "(", "str", ")", ">=", "0", ":", "matches", ".", "append", "(", "value", ")", "return", "matches" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/distributed/DoCollectionManager.py#L64-L72
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/plugins/db_manager/db_plugins/postgis/plugin.py
python
PGRasterTable.uri
(self, uri=None)
return uri
Returns the datasource URI for postgresraster provider
Returns the datasource URI for postgresraster provider
[ "Returns", "the", "datasource", "URI", "for", "postgresraster", "provider" ]
def uri(self, uri=None): """Returns the datasource URI for postgresraster provider""" if not uri: uri = self.database().uri() service = (u'service=\'%s\'' % uri.service()) if uri.service() else '' dbname = (u'dbname=\'%s\'' % uri.database()) if uri.database() else '' host = (u'host=%s' % uri.host()) if uri.host() else '' user = (u'user=%s' % uri.username()) if uri.username() else '' passw = (u'password=%s' % uri.password()) if uri.password() else '' port = (u'port=%s' % uri.port()) if uri.port() else '' schema = self.schemaName() if self.schemaName() else 'public' table = '"%s"."%s"' % (schema, self.name) if not dbname: # postgresraster provider *requires* a dbname connector = self.database().connector r = connector._execute(None, "SELECT current_database()") dbname = (u'dbname=\'%s\'' % connector._fetchone(r)[0]) connector._close_cursor(r) # Find first raster field col = '' for fld in self.fields(): if fld.dataType == "raster": col = u'column=\'%s\'' % fld.name break uri = u'%s %s %s %s %s %s %s table=%s' % \ (service, dbname, host, user, passw, port, col, table) return uri
[ "def", "uri", "(", "self", ",", "uri", "=", "None", ")", ":", "if", "not", "uri", ":", "uri", "=", "self", ".", "database", "(", ")", ".", "uri", "(", ")", "service", "=", "(", "u'service=\\'%s\\''", "%", "uri", ".", "service", "(", ")", ")", "if", "uri", ".", "service", "(", ")", "else", "''", "dbname", "=", "(", "u'dbname=\\'%s\\''", "%", "uri", ".", "database", "(", ")", ")", "if", "uri", ".", "database", "(", ")", "else", "''", "host", "=", "(", "u'host=%s'", "%", "uri", ".", "host", "(", ")", ")", "if", "uri", ".", "host", "(", ")", "else", "''", "user", "=", "(", "u'user=%s'", "%", "uri", ".", "username", "(", ")", ")", "if", "uri", ".", "username", "(", ")", "else", "''", "passw", "=", "(", "u'password=%s'", "%", "uri", ".", "password", "(", ")", ")", "if", "uri", ".", "password", "(", ")", "else", "''", "port", "=", "(", "u'port=%s'", "%", "uri", ".", "port", "(", ")", ")", "if", "uri", ".", "port", "(", ")", "else", "''", "schema", "=", "self", ".", "schemaName", "(", ")", "if", "self", ".", "schemaName", "(", ")", "else", "'public'", "table", "=", "'\"%s\".\"%s\"'", "%", "(", "schema", ",", "self", ".", "name", ")", "if", "not", "dbname", ":", "# postgresraster provider *requires* a dbname", "connector", "=", "self", ".", "database", "(", ")", ".", "connector", "r", "=", "connector", ".", "_execute", "(", "None", ",", "\"SELECT current_database()\"", ")", "dbname", "=", "(", "u'dbname=\\'%s\\''", "%", "connector", ".", "_fetchone", "(", "r", ")", "[", "0", "]", ")", "connector", ".", "_close_cursor", "(", "r", ")", "# Find first raster field", "col", "=", "''", "for", "fld", "in", "self", ".", "fields", "(", ")", ":", "if", "fld", ".", "dataType", "==", "\"raster\"", ":", "col", "=", "u'column=\\'%s\\''", "%", "fld", ".", "name", "break", "uri", "=", "u'%s %s %s %s %s %s %s table=%s'", "%", "(", "service", ",", "dbname", ",", "host", ",", "user", ",", "passw", ",", "port", ",", "col", ",", "table", ")", "return", "uri" ]
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/postgis/plugin.py#L343-L375
zetavm/zetavm
61af9cd317fa5629f570b30b61ea8c7ffc375e59
espresso/e_parser.py
python
parse_atom
(input_handler)
Parsing an atomic expression
Parsing an atomic expression
[ "Parsing", "an", "atomic", "expression" ]
def parse_atom(input_handler): """Parsing an atomic expression""" input_handler.eat_ws() if input_handler.peek_ch().isdigit(): return parse_num(input_handler) if input_handler.match('"'): return parse_string_literal(input_handler, '"') if input_handler.match("'"): return parse_string_literal(input_handler, "'") if input_handler.match('['): return ArrayExpr(parse_expr_list(input_handler, "]")) if input_handler.match("{"): return parse_obj_literal(input_handler) if input_handler.match("("): expr = parse_expr(input_handler) input_handler.expect_ws(")") return expr op = match_op(input_handler, 0, True) if op is not None: expr = parse_expr_prec(input_handler, op.prec) return UnOpExpr(op, expr) if input_handler.peek_ch().isalnum(): if input_handler.match_kw("fun"): return parse_fun_expr(input_handler) return IdentExpr(parse_ident_expr(input_handler)) if input_handler.match("$"): op_name = parse_ident_expr(input_handler) input_handler.expect('(') arg_exprs = parse_expr_list(input_handler, ')') return IRExpr(op_name, arg_exprs) raise ParseError(input_handler, "invalid expression")
[ "def", "parse_atom", "(", "input_handler", ")", ":", "input_handler", ".", "eat_ws", "(", ")", "if", "input_handler", ".", "peek_ch", "(", ")", ".", "isdigit", "(", ")", ":", "return", "parse_num", "(", "input_handler", ")", "if", "input_handler", ".", "match", "(", "'\"'", ")", ":", "return", "parse_string_literal", "(", "input_handler", ",", "'\"'", ")", "if", "input_handler", ".", "match", "(", "\"'\"", ")", ":", "return", "parse_string_literal", "(", "input_handler", ",", "\"'\"", ")", "if", "input_handler", ".", "match", "(", "'['", ")", ":", "return", "ArrayExpr", "(", "parse_expr_list", "(", "input_handler", ",", "\"]\"", ")", ")", "if", "input_handler", ".", "match", "(", "\"{\"", ")", ":", "return", "parse_obj_literal", "(", "input_handler", ")", "if", "input_handler", ".", "match", "(", "\"(\"", ")", ":", "expr", "=", "parse_expr", "(", "input_handler", ")", "input_handler", ".", "expect_ws", "(", "\")\"", ")", "return", "expr", "op", "=", "match_op", "(", "input_handler", ",", "0", ",", "True", ")", "if", "op", "is", "not", "None", ":", "expr", "=", "parse_expr_prec", "(", "input_handler", ",", "op", ".", "prec", ")", "return", "UnOpExpr", "(", "op", ",", "expr", ")", "if", "input_handler", ".", "peek_ch", "(", ")", ".", "isalnum", "(", ")", ":", "if", "input_handler", ".", "match_kw", "(", "\"fun\"", ")", ":", "return", "parse_fun_expr", "(", "input_handler", ")", "return", "IdentExpr", "(", "parse_ident_expr", "(", "input_handler", ")", ")", "if", "input_handler", ".", "match", "(", "\"$\"", ")", ":", "op_name", "=", "parse_ident_expr", "(", "input_handler", ")", "input_handler", ".", "expect", "(", "'('", ")", "arg_exprs", "=", "parse_expr_list", "(", "input_handler", ",", "')'", ")", "return", "IRExpr", "(", "op_name", ",", "arg_exprs", ")", "raise", "ParseError", "(", "input_handler", ",", "\"invalid expression\"", ")" ]
https://github.com/zetavm/zetavm/blob/61af9cd317fa5629f570b30b61ea8c7ffc375e59/espresso/e_parser.py#L207-L237
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/virtualenv/files/virtualenv.py
python
install_python
(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear)
return py_executable
Install just the base environment, no distutils patches etc
Install just the base environment, no distutils patches etc
[ "Install", "just", "the", "base", "environment", "no", "distutils", "patches", "etc" ]
def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear): """Install just the base environment, no distutils patches etc""" if sys.executable.startswith(bin_dir): print('Please use the *system* python to run this script') return if clear: rmtree(lib_dir) ## FIXME: why not delete it? ## Maybe it should delete everything with #!/path/to/venv/python in it logger.notify('Not deleting %s', bin_dir) if hasattr(sys, 'real_prefix'): logger.notify('Using real prefix %r' % sys.real_prefix) prefix = sys.real_prefix else: prefix = sys.prefix mkdir(lib_dir) fix_lib64(lib_dir) stdlib_dirs = [os.path.dirname(os.__file__)] if sys.platform == 'win32': stdlib_dirs.append(join(os.path.dirname(stdlib_dirs[0]), 'DLLs')) elif sys.platform == 'darwin': stdlib_dirs.append(join(stdlib_dirs[0], 'site-packages')) if hasattr(os, 'symlink'): logger.info('Symlinking Python bootstrap modules') else: logger.info('Copying Python bootstrap modules') logger.indent += 2 try: # copy required files... for stdlib_dir in stdlib_dirs: if not os.path.isdir(stdlib_dir): continue for fn in os.listdir(stdlib_dir): bn = os.path.splitext(fn)[0] if fn != 'site-packages' and bn in REQUIRED_FILES: copyfile(join(stdlib_dir, fn), join(lib_dir, fn)) # ...and modules copy_required_modules(home_dir) finally: logger.indent -= 2 mkdir(join(lib_dir, 'site-packages')) import site site_filename = site.__file__ if site_filename.endswith('.pyc'): site_filename = site_filename[:-1] elif site_filename.endswith('$py.class'): site_filename = site_filename.replace('$py.class', '.py') site_filename_dst = change_prefix(site_filename, home_dir) site_dir = os.path.dirname(site_filename_dst) writefile(site_filename_dst, SITE_PY) writefile(join(site_dir, 'orig-prefix.txt'), prefix) site_packages_filename = join(site_dir, 'no-global-site-packages.txt') if not site_packages: writefile(site_packages_filename, '') else: if os.path.exists(site_packages_filename): logger.info('Deleting %s' % site_packages_filename) os.unlink(site_packages_filename) if is_pypy: stdinc_dir = join(prefix, 'include') else: stdinc_dir = join(prefix, 'include', py_version + abiflags) if os.path.exists(stdinc_dir): copyfile(stdinc_dir, inc_dir) else: logger.debug('No include dir %s' % stdinc_dir) # pypy never uses exec_prefix, just ignore it if sys.exec_prefix != prefix and not is_pypy: if sys.platform == 'win32': exec_dir = join(sys.exec_prefix, 'lib') elif is_jython: exec_dir = join(sys.exec_prefix, 'Lib') else: exec_dir = join(sys.exec_prefix, 'lib', py_version) for fn in os.listdir(exec_dir): copyfile(join(exec_dir, fn), join(lib_dir, fn)) if is_jython: # Jython has either jython-dev.jar and javalib/ dir, or just # jython.jar for name in 'jython-dev.jar', 'javalib', 'jython.jar': src = join(prefix, name) if os.path.exists(src): copyfile(src, join(home_dir, name)) # XXX: registry should always exist after Jython 2.5rc1 src = join(prefix, 'registry') if os.path.exists(src): copyfile(src, join(home_dir, 'registry'), symlink=False) copyfile(join(prefix, 'cachedir'), join(home_dir, 'cachedir'), symlink=False) mkdir(bin_dir) py_executable = join(bin_dir, os.path.basename(sys.executable)) if 'Python.framework' in prefix: if re.search(r'/Python(?:-32|-64)*$', py_executable): # The name of the python executable is not quite what # we want, rename it. py_executable = os.path.join( os.path.dirname(py_executable), 'python') logger.notify('New %s executable in %s', expected_exe, py_executable) if sys.executable != py_executable: ## FIXME: could I just hard link? executable = sys.executable if sys.platform == 'cygwin' and os.path.exists(executable + '.exe'): # Cygwin misreports sys.executable sometimes executable += '.exe' py_executable += '.exe' logger.info('Executable actually exists in %s' % executable) shutil.copyfile(executable, py_executable) make_exe(py_executable) if sys.platform == 'win32' or sys.platform == 'cygwin': pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe') if os.path.exists(pythonw): logger.info('Also created pythonw.exe') shutil.copyfile(pythonw, os.path.join(os.path.dirname(py_executable), 'pythonw.exe')) if is_pypy: # make a symlink python --> pypy-c python_executable = os.path.join(os.path.dirname(py_executable), 'python') logger.info('Also created executable %s' % python_executable) copyfile(py_executable, python_executable) if os.path.splitext(os.path.basename(py_executable))[0] != expected_exe: secondary_exe = os.path.join(os.path.dirname(py_executable), expected_exe) py_executable_ext = os.path.splitext(py_executable)[1] if py_executable_ext == '.exe': # python2.4 gives an extension of '.4' :P secondary_exe += py_executable_ext if os.path.exists(secondary_exe): logger.warn('Not overwriting existing %s script %s (you must use %s)' % (expected_exe, secondary_exe, py_executable)) else: logger.notify('Also creating executable in %s' % secondary_exe) shutil.copyfile(sys.executable, secondary_exe) make_exe(secondary_exe) if 'Python.framework' in prefix: logger.debug('MacOSX Python framework detected') # Make sure we use the the embedded interpreter inside # the framework, even if sys.executable points to # the stub executable in ${sys.prefix}/bin # See http://groups.google.com/group/python-virtualenv/ # browse_thread/thread/17cab2f85da75951 original_python = os.path.join( prefix, 'Resources/Python.app/Contents/MacOS/Python') shutil.copy(original_python, py_executable) # Copy the framework's dylib into the virtual # environment virtual_lib = os.path.join(home_dir, '.Python') if os.path.exists(virtual_lib): os.unlink(virtual_lib) copyfile( os.path.join(prefix, 'Python'), virtual_lib) # And then change the install_name of the copied python executable try: call_subprocess( ["install_name_tool", "-change", os.path.join(prefix, 'Python'), '@executable_path/../.Python', py_executable]) except: logger.fatal( "Could not call install_name_tool -- you must have Apple's development tools installed") raise # Some tools depend on pythonX.Y being present py_executable_version = '%s.%s' % ( sys.version_info[0], sys.version_info[1]) if not py_executable.endswith(py_executable_version): # symlinking pythonX.Y > python pth = py_executable + '%s.%s' % ( sys.version_info[0], sys.version_info[1]) if os.path.exists(pth): os.unlink(pth) os.symlink('python', pth) else: # reverse symlinking python -> pythonX.Y (with --python) pth = join(bin_dir, 'python') if os.path.exists(pth): os.unlink(pth) os.symlink(os.path.basename(py_executable), pth) if sys.platform == 'win32' and ' ' in py_executable: # There's a bug with subprocess on Windows when using a first # argument that has a space in it. Instead we have to quote # the value: py_executable = '"%s"' % py_executable cmd = [py_executable, '-c', 'import sys; print(sys.prefix)'] logger.info('Testing executable with %s %s "%s"' % tuple(cmd)) try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) proc_stdout, proc_stderr = proc.communicate() except OSError: e = sys.exc_info()[1] if e.errno == errno.EACCES: logger.fatal('ERROR: The executable %s could not be run: %s' % (py_executable, e)) sys.exit(100) else: raise e proc_stdout = proc_stdout.strip().decode(sys.getdefaultencoding()) proc_stdout = os.path.normcase(os.path.abspath(proc_stdout)) if proc_stdout != os.path.normcase(os.path.abspath(home_dir)): logger.fatal( 'ERROR: The executable %s is not functioning' % py_executable) logger.fatal( 'ERROR: It thinks sys.prefix is %r (should be %r)' % (proc_stdout, os.path.normcase(os.path.abspath(home_dir)))) logger.fatal( 'ERROR: virtualenv is not compatible with this system or executable') if sys.platform == 'win32': logger.fatal( 'Note: some Windows users have reported this error when they installed Python for "Only this user". The problem may be resolvable if you install Python "For all users". (See https://bugs.launchpad.net/virtualenv/+bug/352844)') sys.exit(100) else: logger.info('Got sys.prefix result: %r' % proc_stdout) pydistutils = os.path.expanduser('~/.pydistutils.cfg') if os.path.exists(pydistutils): logger.notify('Please make sure you remove any previous custom paths from ' 'your %s file.' % pydistutils) ## FIXME: really this should be calculated earlier return py_executable
[ "def", "install_python", "(", "home_dir", ",", "lib_dir", ",", "inc_dir", ",", "bin_dir", ",", "site_packages", ",", "clear", ")", ":", "if", "sys", ".", "executable", ".", "startswith", "(", "bin_dir", ")", ":", "print", "(", "'Please use the *system* python to run this script'", ")", "return", "if", "clear", ":", "rmtree", "(", "lib_dir", ")", "## FIXME: why not delete it?", "## Maybe it should delete everything with #!/path/to/venv/python in it", "logger", ".", "notify", "(", "'Not deleting %s'", ",", "bin_dir", ")", "if", "hasattr", "(", "sys", ",", "'real_prefix'", ")", ":", "logger", ".", "notify", "(", "'Using real prefix %r'", "%", "sys", ".", "real_prefix", ")", "prefix", "=", "sys", ".", "real_prefix", "else", ":", "prefix", "=", "sys", ".", "prefix", "mkdir", "(", "lib_dir", ")", "fix_lib64", "(", "lib_dir", ")", "stdlib_dirs", "=", "[", "os", ".", "path", ".", "dirname", "(", "os", ".", "__file__", ")", "]", "if", "sys", ".", "platform", "==", "'win32'", ":", "stdlib_dirs", ".", "append", "(", "join", "(", "os", ".", "path", ".", "dirname", "(", "stdlib_dirs", "[", "0", "]", ")", ",", "'DLLs'", ")", ")", "elif", "sys", ".", "platform", "==", "'darwin'", ":", "stdlib_dirs", ".", "append", "(", "join", "(", "stdlib_dirs", "[", "0", "]", ",", "'site-packages'", ")", ")", "if", "hasattr", "(", "os", ",", "'symlink'", ")", ":", "logger", ".", "info", "(", "'Symlinking Python bootstrap modules'", ")", "else", ":", "logger", ".", "info", "(", "'Copying Python bootstrap modules'", ")", "logger", ".", "indent", "+=", "2", "try", ":", "# copy required files...", "for", "stdlib_dir", "in", "stdlib_dirs", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "stdlib_dir", ")", ":", "continue", "for", "fn", "in", "os", ".", "listdir", "(", "stdlib_dir", ")", ":", "bn", "=", "os", ".", "path", ".", "splitext", "(", "fn", ")", "[", "0", "]", "if", "fn", "!=", "'site-packages'", "and", "bn", "in", "REQUIRED_FILES", ":", "copyfile", "(", "join", "(", "stdlib_dir", ",", "fn", ")", ",", "join", "(", "lib_dir", ",", "fn", ")", ")", "# ...and modules", "copy_required_modules", "(", "home_dir", ")", "finally", ":", "logger", ".", "indent", "-=", "2", "mkdir", "(", "join", "(", "lib_dir", ",", "'site-packages'", ")", ")", "import", "site", "site_filename", "=", "site", ".", "__file__", "if", "site_filename", ".", "endswith", "(", "'.pyc'", ")", ":", "site_filename", "=", "site_filename", "[", ":", "-", "1", "]", "elif", "site_filename", ".", "endswith", "(", "'$py.class'", ")", ":", "site_filename", "=", "site_filename", ".", "replace", "(", "'$py.class'", ",", "'.py'", ")", "site_filename_dst", "=", "change_prefix", "(", "site_filename", ",", "home_dir", ")", "site_dir", "=", "os", ".", "path", ".", "dirname", "(", "site_filename_dst", ")", "writefile", "(", "site_filename_dst", ",", "SITE_PY", ")", "writefile", "(", "join", "(", "site_dir", ",", "'orig-prefix.txt'", ")", ",", "prefix", ")", "site_packages_filename", "=", "join", "(", "site_dir", ",", "'no-global-site-packages.txt'", ")", "if", "not", "site_packages", ":", "writefile", "(", "site_packages_filename", ",", "''", ")", "else", ":", "if", "os", ".", "path", ".", "exists", "(", "site_packages_filename", ")", ":", "logger", ".", "info", "(", "'Deleting %s'", "%", "site_packages_filename", ")", "os", ".", "unlink", "(", "site_packages_filename", ")", "if", "is_pypy", ":", "stdinc_dir", "=", "join", "(", "prefix", ",", "'include'", ")", "else", ":", "stdinc_dir", "=", "join", "(", "prefix", ",", "'include'", ",", "py_version", "+", "abiflags", ")", "if", "os", ".", "path", ".", "exists", "(", "stdinc_dir", ")", ":", "copyfile", "(", "stdinc_dir", ",", "inc_dir", ")", "else", ":", "logger", ".", "debug", "(", "'No include dir %s'", "%", "stdinc_dir", ")", "# pypy never uses exec_prefix, just ignore it", "if", "sys", ".", "exec_prefix", "!=", "prefix", "and", "not", "is_pypy", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "exec_dir", "=", "join", "(", "sys", ".", "exec_prefix", ",", "'lib'", ")", "elif", "is_jython", ":", "exec_dir", "=", "join", "(", "sys", ".", "exec_prefix", ",", "'Lib'", ")", "else", ":", "exec_dir", "=", "join", "(", "sys", ".", "exec_prefix", ",", "'lib'", ",", "py_version", ")", "for", "fn", "in", "os", ".", "listdir", "(", "exec_dir", ")", ":", "copyfile", "(", "join", "(", "exec_dir", ",", "fn", ")", ",", "join", "(", "lib_dir", ",", "fn", ")", ")", "if", "is_jython", ":", "# Jython has either jython-dev.jar and javalib/ dir, or just", "# jython.jar", "for", "name", "in", "'jython-dev.jar'", ",", "'javalib'", ",", "'jython.jar'", ":", "src", "=", "join", "(", "prefix", ",", "name", ")", "if", "os", ".", "path", ".", "exists", "(", "src", ")", ":", "copyfile", "(", "src", ",", "join", "(", "home_dir", ",", "name", ")", ")", "# XXX: registry should always exist after Jython 2.5rc1", "src", "=", "join", "(", "prefix", ",", "'registry'", ")", "if", "os", ".", "path", ".", "exists", "(", "src", ")", ":", "copyfile", "(", "src", ",", "join", "(", "home_dir", ",", "'registry'", ")", ",", "symlink", "=", "False", ")", "copyfile", "(", "join", "(", "prefix", ",", "'cachedir'", ")", ",", "join", "(", "home_dir", ",", "'cachedir'", ")", ",", "symlink", "=", "False", ")", "mkdir", "(", "bin_dir", ")", "py_executable", "=", "join", "(", "bin_dir", ",", "os", ".", "path", ".", "basename", "(", "sys", ".", "executable", ")", ")", "if", "'Python.framework'", "in", "prefix", ":", "if", "re", ".", "search", "(", "r'/Python(?:-32|-64)*$'", ",", "py_executable", ")", ":", "# The name of the python executable is not quite what", "# we want, rename it.", "py_executable", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "py_executable", ")", ",", "'python'", ")", "logger", ".", "notify", "(", "'New %s executable in %s'", ",", "expected_exe", ",", "py_executable", ")", "if", "sys", ".", "executable", "!=", "py_executable", ":", "## FIXME: could I just hard link?", "executable", "=", "sys", ".", "executable", "if", "sys", ".", "platform", "==", "'cygwin'", "and", "os", ".", "path", ".", "exists", "(", "executable", "+", "'.exe'", ")", ":", "# Cygwin misreports sys.executable sometimes", "executable", "+=", "'.exe'", "py_executable", "+=", "'.exe'", "logger", ".", "info", "(", "'Executable actually exists in %s'", "%", "executable", ")", "shutil", ".", "copyfile", "(", "executable", ",", "py_executable", ")", "make_exe", "(", "py_executable", ")", "if", "sys", ".", "platform", "==", "'win32'", "or", "sys", ".", "platform", "==", "'cygwin'", ":", "pythonw", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "sys", ".", "executable", ")", ",", "'pythonw.exe'", ")", "if", "os", ".", "path", ".", "exists", "(", "pythonw", ")", ":", "logger", ".", "info", "(", "'Also created pythonw.exe'", ")", "shutil", ".", "copyfile", "(", "pythonw", ",", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "py_executable", ")", ",", "'pythonw.exe'", ")", ")", "if", "is_pypy", ":", "# make a symlink python --> pypy-c", "python_executable", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "py_executable", ")", ",", "'python'", ")", "logger", ".", "info", "(", "'Also created executable %s'", "%", "python_executable", ")", "copyfile", "(", "py_executable", ",", "python_executable", ")", "if", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "py_executable", ")", ")", "[", "0", "]", "!=", "expected_exe", ":", "secondary_exe", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "py_executable", ")", ",", "expected_exe", ")", "py_executable_ext", "=", "os", ".", "path", ".", "splitext", "(", "py_executable", ")", "[", "1", "]", "if", "py_executable_ext", "==", "'.exe'", ":", "# python2.4 gives an extension of '.4' :P", "secondary_exe", "+=", "py_executable_ext", "if", "os", ".", "path", ".", "exists", "(", "secondary_exe", ")", ":", "logger", ".", "warn", "(", "'Not overwriting existing %s script %s (you must use %s)'", "%", "(", "expected_exe", ",", "secondary_exe", ",", "py_executable", ")", ")", "else", ":", "logger", ".", "notify", "(", "'Also creating executable in %s'", "%", "secondary_exe", ")", "shutil", ".", "copyfile", "(", "sys", ".", "executable", ",", "secondary_exe", ")", "make_exe", "(", "secondary_exe", ")", "if", "'Python.framework'", "in", "prefix", ":", "logger", ".", "debug", "(", "'MacOSX Python framework detected'", ")", "# Make sure we use the the embedded interpreter inside", "# the framework, even if sys.executable points to", "# the stub executable in ${sys.prefix}/bin", "# See http://groups.google.com/group/python-virtualenv/", "# browse_thread/thread/17cab2f85da75951", "original_python", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "'Resources/Python.app/Contents/MacOS/Python'", ")", "shutil", ".", "copy", "(", "original_python", ",", "py_executable", ")", "# Copy the framework's dylib into the virtual", "# environment", "virtual_lib", "=", "os", ".", "path", ".", "join", "(", "home_dir", ",", "'.Python'", ")", "if", "os", ".", "path", ".", "exists", "(", "virtual_lib", ")", ":", "os", ".", "unlink", "(", "virtual_lib", ")", "copyfile", "(", "os", ".", "path", ".", "join", "(", "prefix", ",", "'Python'", ")", ",", "virtual_lib", ")", "# And then change the install_name of the copied python executable", "try", ":", "call_subprocess", "(", "[", "\"install_name_tool\"", ",", "\"-change\"", ",", "os", ".", "path", ".", "join", "(", "prefix", ",", "'Python'", ")", ",", "'@executable_path/../.Python'", ",", "py_executable", "]", ")", "except", ":", "logger", ".", "fatal", "(", "\"Could not call install_name_tool -- you must have Apple's development tools installed\"", ")", "raise", "# Some tools depend on pythonX.Y being present", "py_executable_version", "=", "'%s.%s'", "%", "(", "sys", ".", "version_info", "[", "0", "]", ",", "sys", ".", "version_info", "[", "1", "]", ")", "if", "not", "py_executable", ".", "endswith", "(", "py_executable_version", ")", ":", "# symlinking pythonX.Y > python", "pth", "=", "py_executable", "+", "'%s.%s'", "%", "(", "sys", ".", "version_info", "[", "0", "]", ",", "sys", ".", "version_info", "[", "1", "]", ")", "if", "os", ".", "path", ".", "exists", "(", "pth", ")", ":", "os", ".", "unlink", "(", "pth", ")", "os", ".", "symlink", "(", "'python'", ",", "pth", ")", "else", ":", "# reverse symlinking python -> pythonX.Y (with --python)", "pth", "=", "join", "(", "bin_dir", ",", "'python'", ")", "if", "os", ".", "path", ".", "exists", "(", "pth", ")", ":", "os", ".", "unlink", "(", "pth", ")", "os", ".", "symlink", "(", "os", ".", "path", ".", "basename", "(", "py_executable", ")", ",", "pth", ")", "if", "sys", ".", "platform", "==", "'win32'", "and", "' '", "in", "py_executable", ":", "# There's a bug with subprocess on Windows when using a first", "# argument that has a space in it. Instead we have to quote", "# the value:", "py_executable", "=", "'\"%s\"'", "%", "py_executable", "cmd", "=", "[", "py_executable", ",", "'-c'", ",", "'import sys; print(sys.prefix)'", "]", "logger", ".", "info", "(", "'Testing executable with %s %s \"%s\"'", "%", "tuple", "(", "cmd", ")", ")", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "proc_stdout", ",", "proc_stderr", "=", "proc", ".", "communicate", "(", ")", "except", "OSError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "errno", "==", "errno", ".", "EACCES", ":", "logger", ".", "fatal", "(", "'ERROR: The executable %s could not be run: %s'", "%", "(", "py_executable", ",", "e", ")", ")", "sys", ".", "exit", "(", "100", ")", "else", ":", "raise", "e", "proc_stdout", "=", "proc_stdout", ".", "strip", "(", ")", ".", "decode", "(", "sys", ".", "getdefaultencoding", "(", ")", ")", "proc_stdout", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "proc_stdout", ")", ")", "if", "proc_stdout", "!=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "home_dir", ")", ")", ":", "logger", ".", "fatal", "(", "'ERROR: The executable %s is not functioning'", "%", "py_executable", ")", "logger", ".", "fatal", "(", "'ERROR: It thinks sys.prefix is %r (should be %r)'", "%", "(", "proc_stdout", ",", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "home_dir", ")", ")", ")", ")", "logger", ".", "fatal", "(", "'ERROR: virtualenv is not compatible with this system or executable'", ")", "if", "sys", ".", "platform", "==", "'win32'", ":", "logger", ".", "fatal", "(", "'Note: some Windows users have reported this error when they installed Python for \"Only this user\". The problem may be resolvable if you install Python \"For all users\". (See https://bugs.launchpad.net/virtualenv/+bug/352844)'", ")", "sys", ".", "exit", "(", "100", ")", "else", ":", "logger", ".", "info", "(", "'Got sys.prefix result: %r'", "%", "proc_stdout", ")", "pydistutils", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.pydistutils.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "pydistutils", ")", ":", "logger", ".", "notify", "(", "'Please make sure you remove any previous custom paths from '", "'your %s file.'", "%", "pydistutils", ")", "## FIXME: really this should be calculated earlier", "return", "py_executable" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/virtualenv/files/virtualenv.py#L981-L1214
kevinlin311tw/Caffe-DeepBinaryCode
9eaa7662be47d49f475ecbeea2bd51be105270d2
scripts/cpp_lint.py
python
RemoveMultiLineCommentsFromRange
(lines, begin, end)
Clears a range of lines for multi-line comments.
Clears a range of lines for multi-line comments.
[ "Clears", "a", "range", "of", "lines", "for", "multi", "-", "line", "comments", "." ]
def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '// dummy'
[ "def", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "begin", ",", "end", ")", ":", "# Having // dummy comments makes the lines non-empty, so we will not get", "# unnecessary blank line warnings later in the code.", "for", "i", "in", "range", "(", "begin", ",", "end", ")", ":", "lines", "[", "i", "]", "=", "'// dummy'" ]
https://github.com/kevinlin311tw/Caffe-DeepBinaryCode/blob/9eaa7662be47d49f475ecbeea2bd51be105270d2/scripts/cpp_lint.py#L1143-L1148
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/io/matlab/mio4.py
python
MatFile4Reader.list_variables
(self)
return vars
list variables from stream
list variables from stream
[ "list", "variables", "from", "stream" ]
def list_variables(self): ''' list variables from stream ''' self.mat_stream.seek(0) # set up variable reader self.initialize_read() vars = [] while not self.end_of_stream(): hdr, next_position = self.read_var_header() name = asstr(hdr.name) shape = self._matrix_reader.shape_from_header(hdr) info = mclass_info.get(hdr.mclass, 'unknown') vars.append((name, shape, info)) self.mat_stream.seek(next_position) return vars
[ "def", "list_variables", "(", "self", ")", ":", "self", ".", "mat_stream", ".", "seek", "(", "0", ")", "# set up variable reader", "self", ".", "initialize_read", "(", ")", "vars", "=", "[", "]", "while", "not", "self", ".", "end_of_stream", "(", ")", ":", "hdr", ",", "next_position", "=", "self", ".", "read_var_header", "(", ")", "name", "=", "asstr", "(", "hdr", ".", "name", ")", "shape", "=", "self", ".", "_matrix_reader", ".", "shape_from_header", "(", "hdr", ")", "info", "=", "mclass_info", ".", "get", "(", "hdr", ".", "mclass", ",", "'unknown'", ")", "vars", ".", "append", "(", "(", "name", ",", "shape", ",", "info", ")", ")", "self", ".", "mat_stream", ".", "seek", "(", "next_position", ")", "return", "vars" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/io/matlab/mio4.py#L408-L422
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/distributions/util.py
python
pad
(x, axis, front=False, back=False, value=0, count=1, name=None)
Pads `value` to the front and/or back of a `Tensor` dim, `count` times. Args: x: `Tensor` input. axis: Scalar `int`-like `Tensor` representing the single dimension to pad. (Negative indexing is supported.) front: Python `bool`; if `True` the beginning of the `axis` dimension is padded with `value`, `count` times. If `False` no front padding is made. back: Python `bool`; if `True` the end of the `axis` dimension is padded with `value`, `count` times. If `False` no end padding is made. value: Scalar `int`-like `Tensor` representing the actual value added to the front and/or back of the `axis` dimension of `x`. count: Scalar `int`-like `Tensor` representing number of elements added to the front and/or back of the `axis` dimension of `x`. E.g., if `front = back = True` then `2 * count` elements are added. name: Python `str` name prefixed to Ops created by this function. Returns: pad: The padded version of input `x`. Raises: ValueError: if both `front` and `back` are `False`. TypeError: if `count` is not `int`-like.
Pads `value` to the front and/or back of a `Tensor` dim, `count` times.
[ "Pads", "value", "to", "the", "front", "and", "/", "or", "back", "of", "a", "Tensor", "dim", "count", "times", "." ]
def pad(x, axis, front=False, back=False, value=0, count=1, name=None): """Pads `value` to the front and/or back of a `Tensor` dim, `count` times. Args: x: `Tensor` input. axis: Scalar `int`-like `Tensor` representing the single dimension to pad. (Negative indexing is supported.) front: Python `bool`; if `True` the beginning of the `axis` dimension is padded with `value`, `count` times. If `False` no front padding is made. back: Python `bool`; if `True` the end of the `axis` dimension is padded with `value`, `count` times. If `False` no end padding is made. value: Scalar `int`-like `Tensor` representing the actual value added to the front and/or back of the `axis` dimension of `x`. count: Scalar `int`-like `Tensor` representing number of elements added to the front and/or back of the `axis` dimension of `x`. E.g., if `front = back = True` then `2 * count` elements are added. name: Python `str` name prefixed to Ops created by this function. Returns: pad: The padded version of input `x`. Raises: ValueError: if both `front` and `back` are `False`. TypeError: if `count` is not `int`-like. """ with ops.name_scope(name, "pad", [x, value, count]): x = ops.convert_to_tensor(x, name="x") value = ops.convert_to_tensor(value, dtype=x.dtype, name="value") count = ops.convert_to_tensor(count, name="count") if not count.dtype.is_integer: raise TypeError("`count.dtype` (`{}`) must be `int`-like.".format( count.dtype.name)) if not front and not back: raise ValueError("At least one of `front`, `back` must be `True`.") ndims = ( x.shape.ndims if x.shape.ndims is not None else array_ops.rank( x, name="ndims")) axis = ops.convert_to_tensor(axis, name="axis") axis_ = tensor_util.constant_value(axis) if axis_ is not None: axis = axis_ if axis < 0: axis = ndims + axis count_ = tensor_util.constant_value(count) if axis_ >= 0 or x.shape.ndims is not None: head = x.shape[:axis] middle = tensor_shape.TensorShape(None if count_ is None else ( tensor_shape.dimension_at_index(x.shape, axis) + count_ * (front + back))) tail = x.shape[axis + 1:] final_shape = head.concatenate(middle.concatenate(tail)) else: final_shape = None else: axis = array_ops.where_v2(axis < 0, ndims + axis, axis) final_shape = None x = array_ops.pad( x, paddings=array_ops.one_hot( indices=array_ops.stack( [axis if front else -1, axis if back else -1]), depth=ndims, axis=0, on_value=count, dtype=dtypes.int32), constant_values=value) if final_shape is not None: x.set_shape(final_shape) return x
[ "def", "pad", "(", "x", ",", "axis", ",", "front", "=", "False", ",", "back", "=", "False", ",", "value", "=", "0", ",", "count", "=", "1", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"pad\"", ",", "[", "x", ",", "value", ",", "count", "]", ")", ":", "x", "=", "ops", ".", "convert_to_tensor", "(", "x", ",", "name", "=", "\"x\"", ")", "value", "=", "ops", ".", "convert_to_tensor", "(", "value", ",", "dtype", "=", "x", ".", "dtype", ",", "name", "=", "\"value\"", ")", "count", "=", "ops", ".", "convert_to_tensor", "(", "count", ",", "name", "=", "\"count\"", ")", "if", "not", "count", ".", "dtype", ".", "is_integer", ":", "raise", "TypeError", "(", "\"`count.dtype` (`{}`) must be `int`-like.\"", ".", "format", "(", "count", ".", "dtype", ".", "name", ")", ")", "if", "not", "front", "and", "not", "back", ":", "raise", "ValueError", "(", "\"At least one of `front`, `back` must be `True`.\"", ")", "ndims", "=", "(", "x", ".", "shape", ".", "ndims", "if", "x", ".", "shape", ".", "ndims", "is", "not", "None", "else", "array_ops", ".", "rank", "(", "x", ",", "name", "=", "\"ndims\"", ")", ")", "axis", "=", "ops", ".", "convert_to_tensor", "(", "axis", ",", "name", "=", "\"axis\"", ")", "axis_", "=", "tensor_util", ".", "constant_value", "(", "axis", ")", "if", "axis_", "is", "not", "None", ":", "axis", "=", "axis_", "if", "axis", "<", "0", ":", "axis", "=", "ndims", "+", "axis", "count_", "=", "tensor_util", ".", "constant_value", "(", "count", ")", "if", "axis_", ">=", "0", "or", "x", ".", "shape", ".", "ndims", "is", "not", "None", ":", "head", "=", "x", ".", "shape", "[", ":", "axis", "]", "middle", "=", "tensor_shape", ".", "TensorShape", "(", "None", "if", "count_", "is", "None", "else", "(", "tensor_shape", ".", "dimension_at_index", "(", "x", ".", "shape", ",", "axis", ")", "+", "count_", "*", "(", "front", "+", "back", ")", ")", ")", "tail", "=", "x", ".", "shape", "[", "axis", "+", "1", ":", "]", "final_shape", "=", "head", ".", "concatenate", "(", "middle", ".", "concatenate", "(", "tail", ")", ")", "else", ":", "final_shape", "=", "None", "else", ":", "axis", "=", "array_ops", ".", "where_v2", "(", "axis", "<", "0", ",", "ndims", "+", "axis", ",", "axis", ")", "final_shape", "=", "None", "x", "=", "array_ops", ".", "pad", "(", "x", ",", "paddings", "=", "array_ops", ".", "one_hot", "(", "indices", "=", "array_ops", ".", "stack", "(", "[", "axis", "if", "front", "else", "-", "1", ",", "axis", "if", "back", "else", "-", "1", "]", ")", ",", "depth", "=", "ndims", ",", "axis", "=", "0", ",", "on_value", "=", "count", ",", "dtype", "=", "dtypes", ".", "int32", ")", ",", "constant_values", "=", "value", ")", "if", "final_shape", "is", "not", "None", ":", "x", ".", "set_shape", "(", "final_shape", ")", "return", "x" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/distributions/util.py#L1280-L1348
ideawu/ssdb-rocks
a3cbb322cafb2f493252829c608e2239df98c9ac
deps/cpy/antlr3/recognizers.py
python
BaseRecognizer._getRuleInvocationStack
(cls, module)
return rules
A more general version of getRuleInvocationStack where you can pass in, for example, a RecognitionException to get it's rule stack trace. This routine is shared with all recognizers, hence, static. TODO: move to a utility class or something; weird having lexer call this
A more general version of getRuleInvocationStack where you can pass in, for example, a RecognitionException to get it's rule stack trace. This routine is shared with all recognizers, hence, static.
[ "A", "more", "general", "version", "of", "getRuleInvocationStack", "where", "you", "can", "pass", "in", "for", "example", "a", "RecognitionException", "to", "get", "it", "s", "rule", "stack", "trace", ".", "This", "routine", "is", "shared", "with", "all", "recognizers", "hence", "static", "." ]
def _getRuleInvocationStack(cls, module): """ A more general version of getRuleInvocationStack where you can pass in, for example, a RecognitionException to get it's rule stack trace. This routine is shared with all recognizers, hence, static. TODO: move to a utility class or something; weird having lexer call this """ # mmmhhh,... perhaps look at the first argument # (f_locals[co_varnames[0]]?) and test if it's a (sub)class of # requested recognizer... rules = [] for frame in reversed(inspect.stack()): code = frame[0].f_code codeMod = inspect.getmodule(code) if codeMod is None: continue # skip frames not in requested module if codeMod.__name__ != module: continue # skip some unwanted names if code.co_name in ('nextToken', '<module>'): continue rules.append(code.co_name) return rules
[ "def", "_getRuleInvocationStack", "(", "cls", ",", "module", ")", ":", "# mmmhhh,... perhaps look at the first argument", "# (f_locals[co_varnames[0]]?) and test if it's a (sub)class of", "# requested recognizer...", "rules", "=", "[", "]", "for", "frame", "in", "reversed", "(", "inspect", ".", "stack", "(", ")", ")", ":", "code", "=", "frame", "[", "0", "]", ".", "f_code", "codeMod", "=", "inspect", ".", "getmodule", "(", "code", ")", "if", "codeMod", "is", "None", ":", "continue", "# skip frames not in requested module", "if", "codeMod", ".", "__name__", "!=", "module", ":", "continue", "# skip some unwanted names", "if", "code", ".", "co_name", "in", "(", "'nextToken'", ",", "'<module>'", ")", ":", "continue", "rules", ".", "append", "(", "code", ".", "co_name", ")", "return", "rules" ]
https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/recognizers.py#L886-L918
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/contrib/slim/quantization/cal_kl_threshold.py
python
expand_quantized_bins
(quantized_bins, reference_bins)
return expanded_quantized_bins
Expand hist bins.
Expand hist bins.
[ "Expand", "hist", "bins", "." ]
def expand_quantized_bins(quantized_bins, reference_bins): ''' Expand hist bins. ''' expanded_quantized_bins = [0] * len(reference_bins) num_merged_bins = int(len(reference_bins) / len(quantized_bins)) j_start = 0 j_end = num_merged_bins for idx in range(len(quantized_bins)): zero_count = reference_bins[j_start:j_end].count(0) num_merged_bins = j_end - j_start if zero_count == num_merged_bins: avg_bin_ele = 0 else: avg_bin_ele = quantized_bins[idx] / ( num_merged_bins - zero_count + 0.0) for idx1 in range(j_start, j_end): expanded_quantized_bins[idx1] = (0 if reference_bins[idx1] == 0 else avg_bin_ele) j_start += num_merged_bins j_end += num_merged_bins if (idx + 1) == len(quantized_bins) - 1: j_end = len(reference_bins) return expanded_quantized_bins
[ "def", "expand_quantized_bins", "(", "quantized_bins", ",", "reference_bins", ")", ":", "expanded_quantized_bins", "=", "[", "0", "]", "*", "len", "(", "reference_bins", ")", "num_merged_bins", "=", "int", "(", "len", "(", "reference_bins", ")", "/", "len", "(", "quantized_bins", ")", ")", "j_start", "=", "0", "j_end", "=", "num_merged_bins", "for", "idx", "in", "range", "(", "len", "(", "quantized_bins", ")", ")", ":", "zero_count", "=", "reference_bins", "[", "j_start", ":", "j_end", "]", ".", "count", "(", "0", ")", "num_merged_bins", "=", "j_end", "-", "j_start", "if", "zero_count", "==", "num_merged_bins", ":", "avg_bin_ele", "=", "0", "else", ":", "avg_bin_ele", "=", "quantized_bins", "[", "idx", "]", "/", "(", "num_merged_bins", "-", "zero_count", "+", "0.0", ")", "for", "idx1", "in", "range", "(", "j_start", ",", "j_end", ")", ":", "expanded_quantized_bins", "[", "idx1", "]", "=", "(", "0", "if", "reference_bins", "[", "idx1", "]", "==", "0", "else", "avg_bin_ele", ")", "j_start", "+=", "num_merged_bins", "j_end", "+=", "num_merged_bins", "if", "(", "idx", "+", "1", ")", "==", "len", "(", "quantized_bins", ")", "-", "1", ":", "j_end", "=", "len", "(", "reference_bins", ")", "return", "expanded_quantized_bins" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/slim/quantization/cal_kl_threshold.py#L26-L49
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/crywaflib/branch_spec.py
python
spec_force_individual_build_directory
(ctx, spec_name = None, platform = None, configuration = None)
return force_individual_build_directory[0].lower() == "true"
Return true if the current platform|configuration should use it's own temporary build directory
Return true if the current platform|configuration should use it's own temporary build directory
[ "Return", "true", "if", "the", "current", "platform|configuration", "should", "use", "it", "s", "own", "temporary", "build", "directory" ]
def spec_force_individual_build_directory(ctx, spec_name = None, platform = None, configuration = None): """ Return true if the current platform|configuration should use it's own temporary build directory """ force_individual_build_directory = _spec_entry_as_single_list(ctx, 'force_individual_build_directory', spec_name, platform, configuration) if force_individual_build_directory == []: return False # _spec_entry always returns a list, but client code expects a single boolean assert( len(force_individual_build_directory) == 1 ) return force_individual_build_directory[0].lower() == "true"
[ "def", "spec_force_individual_build_directory", "(", "ctx", ",", "spec_name", "=", "None", ",", "platform", "=", "None", ",", "configuration", "=", "None", ")", ":", "force_individual_build_directory", "=", "_spec_entry_as_single_list", "(", "ctx", ",", "'force_individual_build_directory'", ",", "spec_name", ",", "platform", ",", "configuration", ")", "if", "force_individual_build_directory", "==", "[", "]", ":", "return", "False", "# _spec_entry always returns a list, but client code expects a single boolean", "assert", "(", "len", "(", "force_individual_build_directory", ")", "==", "1", ")", "return", "force_individual_build_directory", "[", "0", "]", ".", "lower", "(", ")", "==", "\"true\"" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/branch_spec.py#L305-L313
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py
python
LoadVesuvio._set_spectra_type
(self, spectrum_no)
Set whether this spectrum no is forward/backward scattering and set the normalization range appropriately @param spectrum_no The current spectrum no
Set whether this spectrum no is forward/backward scattering and set the normalization range appropriately
[ "Set", "whether", "this", "spectrum", "no", "is", "forward", "/", "backward", "scattering", "and", "set", "the", "normalization", "range", "appropriately" ]
def _set_spectra_type(self, spectrum_no): """ Set whether this spectrum no is forward/backward scattering and set the normalization range appropriately @param spectrum_no The current spectrum no """ if self._is_back_scattering(spectrum_no): self._spectra_type=BACKWARD self._mon_norm_start, self._mon_norm_end = self._back_mon_norm self._period_sum1_start, self._period_sum1_end = self._back_period_sum1 self._period_sum2_start, self._period_sum2_end = self._back_period_sum2 self._foil_out_norm_start, self._foil_out_norm_end = self._back_foil_out_norm else: self._spectra_type=FORWARD self._mon_norm_start, self._mon_norm_end = self._forw_mon_norm self._period_sum1_start, self._period_sum1_end = self._forw_period_sum1 self._period_sum2_start, self._period_sum2_end = self._forw_period_sum2 self._foil_out_norm_start, self._foil_out_norm_end = self._forw_foil_out_norm
[ "def", "_set_spectra_type", "(", "self", ",", "spectrum_no", ")", ":", "if", "self", ".", "_is_back_scattering", "(", "spectrum_no", ")", ":", "self", ".", "_spectra_type", "=", "BACKWARD", "self", ".", "_mon_norm_start", ",", "self", ".", "_mon_norm_end", "=", "self", ".", "_back_mon_norm", "self", ".", "_period_sum1_start", ",", "self", ".", "_period_sum1_end", "=", "self", ".", "_back_period_sum1", "self", ".", "_period_sum2_start", ",", "self", ".", "_period_sum2_end", "=", "self", ".", "_back_period_sum2", "self", ".", "_foil_out_norm_start", ",", "self", ".", "_foil_out_norm_end", "=", "self", ".", "_back_foil_out_norm", "else", ":", "self", ".", "_spectra_type", "=", "FORWARD", "self", ".", "_mon_norm_start", ",", "self", ".", "_mon_norm_end", "=", "self", ".", "_forw_mon_norm", "self", ".", "_period_sum1_start", ",", "self", ".", "_period_sum1_end", "=", "self", ".", "_forw_period_sum1", "self", ".", "_period_sum2_start", ",", "self", ".", "_period_sum2_end", "=", "self", ".", "_forw_period_sum2", "self", ".", "_foil_out_norm_start", ",", "self", ".", "_foil_out_norm_end", "=", "self", ".", "_forw_foil_out_norm" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py#L669-L686
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/lambda-code/SanitizationLambda/sanitization_lambda.py
python
Sanitizer.__validate_file
(self, key, file_path)
Validates plain text files like logs.
Validates plain text files like logs.
[ "Validates", "plain", "text", "files", "like", "logs", "." ]
def __validate_file(self, key, file_path): ''' Validates plain text files like logs. ''' if self.__validate_file_size(file_path): return True else: self.rejected_files.append(FileStatus(key, False, "Invalid file size.", '')) return False
[ "def", "__validate_file", "(", "self", ",", "key", ",", "file_path", ")", ":", "if", "self", ".", "__validate_file_size", "(", "file_path", ")", ":", "return", "True", "else", ":", "self", ".", "rejected_files", ".", "append", "(", "FileStatus", "(", "key", ",", "False", ",", "\"Invalid file size.\"", ",", "''", ")", ")", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/lambda-code/SanitizationLambda/sanitization_lambda.py#L252-L259
qt/qt
0a2f2382541424726168804be2c90b91381608c6
src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/MSVSProject.py
python
Writer.AddConfig
(self, name, attrs=None, tools=None)
Adds a configuration to the project. Args: name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None.
Adds a configuration to the project.
[ "Adds", "a", "configuration", "to", "the", "project", "." ]
def AddConfig(self, name, attrs=None, tools=None): """Adds a configuration to the project. Args: name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. """ self._AddConfigToNode(self.n_configs, 'Configuration', name, attrs, tools)
[ "def", "AddConfig", "(", "self", ",", "name", ",", "attrs", "=", "None", ",", "tools", "=", "None", ")", ":", "self", ".", "_AddConfigToNode", "(", "self", ".", "n_configs", ",", "'Configuration'", ",", "name", ",", "attrs", ",", "tools", ")" ]
https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/MSVSProject.py#L173-L181
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteTarget
(self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all)
Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() extra_outputs: any extra outputs that our target should depend on part_of_all: flag indicating this target is part of 'all'
Write Makefile code to produce the final target of the gyp spec.
[ "Write", "Makefile", "code", "to", "produce", "the", "final", "target", "of", "the", "gyp", "spec", "." ]
def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() extra_outputs: any extra outputs that our target should depend on part_of_all: flag indicating this target is part of 'all' """ self.WriteLn('### Rules for final target.') if extra_outputs: self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs) self.WriteMakeRule(extra_outputs, deps, comment=('Preserve order dependency of ' 'special output on deps.'), order_only = True) target_postbuilds = {} if self.type != 'none': for configname in sorted(configs.keys()): config = configs[configname] if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(configname, generator_default_variables['PRODUCT_DIR'], lambda p: Sourceify(self.Absolutify(p))) # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on. gyp_to_build = gyp.common.InvertRelativePath(self.path) target_postbuild = self.xcode_settings.AddImplicitPostbuilds( configname, QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, self.output))), QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, self.output_binary)))) if target_postbuild: target_postbuilds[configname] = target_postbuild else: ldflags = config.get('ldflags', []) # Compute an rpath for this output if needed. if any(dep.endswith('.so') or '.so.' in dep for dep in deps): # We want to get the literal string "$ORIGIN" into the link command, # so we need lots of escaping. ldflags.append(r'-Wl,-rpath=\$$ORIGIN/lib.%s/' % self.toolset) ldflags.append(r'-Wl,-rpath-link=\$(builddir)/lib.%s/' % self.toolset) library_dirs = config.get('library_dirs', []) ldflags += [('-L%s' % library_dir) for library_dir in library_dirs] self.WriteList(ldflags, 'LDFLAGS_%s' % configname) if self.flavor == 'mac': self.WriteList(self.xcode_settings.GetLibtoolflags(configname), 'LIBTOOLFLAGS_%s' % configname) libraries = spec.get('libraries') if libraries: # Remove duplicate entries libraries = gyp.common.uniquer(libraries) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries) self.WriteList(libraries, 'LIBS') self.WriteLn('%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) self.WriteLn('%s: LIBS := $(LIBS)' % QuoteSpaces(self.output_binary)) if self.flavor == 'mac': self.WriteLn('%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) # Postbuild actions. Like actions, but implicitly depend on the target's # output. postbuilds = [] if self.flavor == 'mac': if target_postbuilds: postbuilds.append('$(TARGET_POSTBUILDS_$(BUILDTYPE))') postbuilds.extend( gyp.xcode_emulation.GetSpecPostbuildCommands(spec)) if postbuilds: # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE), # so we must output its definition first, since we declare variables # using ":=". self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv()) for configname in target_postbuilds: self.WriteLn('%s: TARGET_POSTBUILDS_%s := %s' % (QuoteSpaces(self.output), configname, gyp.common.EncodePOSIXShellList(target_postbuilds[configname]))) # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path])) for i in range(len(postbuilds)): if not postbuilds[i].startswith('$'): postbuilds[i] = EscapeShellArgument(postbuilds[i]) self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output)) self.WriteLn('%s: POSTBUILDS := %s' % ( QuoteSpaces(self.output), ' '.join(postbuilds))) # A bundle directory depends on its dependencies such as bundle resources # and bundle binary. When all dependencies have been built, the bundle # needs to be packaged. if self.is_mac_bundle: # If the framework doesn't contain a binary, then nothing depends # on the actions -- make the framework depend on them directly too. self.WriteDependencyOnExtraOutputs(self.output, extra_outputs) # Bundle dependencies. Note that the code below adds actions to this # target, so if you move these two lines, move the lines below as well. self.WriteList([QuoteSpaces(dep) for dep in bundle_deps], 'BUNDLE_DEPS') self.WriteLn('%s: $(BUNDLE_DEPS)' % QuoteSpaces(self.output)) # After the framework is built, package it. Needs to happen before # postbuilds, since postbuilds depend on this. if self.type in ('shared_library', 'loadable_module'): self.WriteLn('\t@$(call do_cmd,mac_package_framework,,,%s)' % self.xcode_settings.GetFrameworkVersion()) # Bundle postbuilds can depend on the whole bundle, so run them after # the bundle is packaged, not already after the bundle binary is done. if postbuilds: self.WriteLn('\t@$(call do_postbuilds)') postbuilds = [] # Don't write postbuilds for target's output. # Needed by test/mac/gyptest-rebuild.py. self.WriteLn('\t@true # No-op, used by tests') # Since this target depends on binary and resources which are in # nested subfolders, the framework directory will be older than # its dependencies usually. To prevent this rule from executing # on every build (expensive, especially with postbuilds), expliclity # update the time on the framework directory. self.WriteLn('\t@touch -c %s' % QuoteSpaces(self.output)) if postbuilds: assert not self.is_mac_bundle, ('Postbuilds for bundles should be done ' 'on the bundle, not the binary (target \'%s\')' % self.target) assert 'product_dir' not in spec, ('Postbuilds do not work with ' 'custom product_dir') if self.type == 'executable': self.WriteLn('%s: LD_INPUTS := %s' % ( QuoteSpaces(self.output_binary), ' '.join(QuoteSpaces(dep) for dep in link_deps))) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'link_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'link', part_of_all, postbuilds=postbuilds) elif self.type == 'static_library': for link_dep in link_deps: assert ' ' not in link_dep, ( "Spaces in alink input filenames not supported (%s)" % link_dep) if (self.flavor not in ('mac', 'openbsd', 'netbsd', 'win') and not self.is_standalone_static_library): self.WriteDoCmd([self.output_binary], link_deps, 'alink_thin', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all, postbuilds=postbuilds) elif self.type == 'shared_library': self.WriteLn('%s: LD_INPUTS := %s' % ( QuoteSpaces(self.output_binary), ' '.join(QuoteSpaces(dep) for dep in link_deps))) self.WriteDoCmd([self.output_binary], link_deps, 'solink', part_of_all, postbuilds=postbuilds) elif self.type == 'loadable_module': for link_dep in link_deps: assert ' ' not in link_dep, ( "Spaces in module input filenames not supported (%s)" % link_dep) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'solink_module_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd( [self.output_binary], link_deps, 'solink_module', part_of_all, postbuilds=postbuilds) elif self.type == 'none': # Write a stamp line. self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all, postbuilds=postbuilds) else: print("WARNING: no output for", self.type, self.target) # Add an alias for each target (if there are any outputs). # Installable target aliases are created below. if ((self.output and self.output != self.target) and (self.type not in self._INSTALLABLE_TARGETS)): self.WriteMakeRule([self.target], [self.output], comment='Add target alias', phony = True) if part_of_all: self.WriteMakeRule(['all'], [self.target], comment = 'Add target alias to "all" target.', phony = True) # Add special-case rules for our installable targets. # 1) They need to install to the build dir or "product" dir. # 2) They get shortcuts for building (e.g. "make chrome"). # 3) They are part of "make all". if (self.type in self._INSTALLABLE_TARGETS or self.is_standalone_static_library): if self.type == 'shared_library': file_desc = 'shared library' elif self.type == 'static_library': file_desc = 'static library' else: file_desc = 'executable' install_path = self._InstallableTargetInstallPath() installable_deps = [self.output] if (self.flavor == 'mac' and not 'product_dir' in spec and self.toolset == 'target'): # On mac, products are created in install_path immediately. assert install_path == self.output, '%s != %s' % ( install_path, self.output) # Point the target alias to the final binary output. self.WriteMakeRule([self.target], [install_path], comment='Add target alias', phony = True) if install_path != self.output: assert not self.is_mac_bundle # See comment a few lines above. self.WriteDoCmd([install_path], [self.output], 'copy', comment = 'Copy this to the %s output path.' % file_desc, part_of_all=part_of_all) installable_deps.append(install_path) if self.output != self.alias and self.alias != self.target: self.WriteMakeRule([self.alias], installable_deps, comment = 'Short alias for building this %s.' % file_desc, phony = True) if part_of_all: self.WriteMakeRule(['all'], [install_path], comment = 'Add %s to "all" target.' % file_desc, phony = True)
[ "def", "WriteTarget", "(", "self", ",", "spec", ",", "configs", ",", "deps", ",", "link_deps", ",", "bundle_deps", ",", "extra_outputs", ",", "part_of_all", ")", ":", "self", ".", "WriteLn", "(", "'### Rules for final target.'", ")", "if", "extra_outputs", ":", "self", ".", "WriteDependencyOnExtraOutputs", "(", "self", ".", "output_binary", ",", "extra_outputs", ")", "self", ".", "WriteMakeRule", "(", "extra_outputs", ",", "deps", ",", "comment", "=", "(", "'Preserve order dependency of '", "'special output on deps.'", ")", ",", "order_only", "=", "True", ")", "target_postbuilds", "=", "{", "}", "if", "self", ".", "type", "!=", "'none'", ":", "for", "configname", "in", "sorted", "(", "configs", ".", "keys", "(", ")", ")", ":", "config", "=", "configs", "[", "configname", "]", "if", "self", ".", "flavor", "==", "'mac'", ":", "ldflags", "=", "self", ".", "xcode_settings", ".", "GetLdflags", "(", "configname", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ",", "lambda", "p", ":", "Sourceify", "(", "self", ".", "Absolutify", "(", "p", ")", ")", ")", "# TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on.", "gyp_to_build", "=", "gyp", ".", "common", ".", "InvertRelativePath", "(", "self", ".", "path", ")", "target_postbuild", "=", "self", ".", "xcode_settings", ".", "AddImplicitPostbuilds", "(", "configname", ",", "QuoteSpaces", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "gyp_to_build", ",", "self", ".", "output", ")", ")", ")", ",", "QuoteSpaces", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "gyp_to_build", ",", "self", ".", "output_binary", ")", ")", ")", ")", "if", "target_postbuild", ":", "target_postbuilds", "[", "configname", "]", "=", "target_postbuild", "else", ":", "ldflags", "=", "config", ".", "get", "(", "'ldflags'", ",", "[", "]", ")", "# Compute an rpath for this output if needed.", "if", "any", "(", "dep", ".", "endswith", "(", "'.so'", ")", "or", "'.so.'", "in", "dep", "for", "dep", "in", "deps", ")", ":", "# We want to get the literal string \"$ORIGIN\" into the link command,", "# so we need lots of escaping.", "ldflags", ".", "append", "(", "r'-Wl,-rpath=\\$$ORIGIN/lib.%s/'", "%", "self", ".", "toolset", ")", "ldflags", ".", "append", "(", "r'-Wl,-rpath-link=\\$(builddir)/lib.%s/'", "%", "self", ".", "toolset", ")", "library_dirs", "=", "config", ".", "get", "(", "'library_dirs'", ",", "[", "]", ")", "ldflags", "+=", "[", "(", "'-L%s'", "%", "library_dir", ")", "for", "library_dir", "in", "library_dirs", "]", "self", ".", "WriteList", "(", "ldflags", ",", "'LDFLAGS_%s'", "%", "configname", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteList", "(", "self", ".", "xcode_settings", ".", "GetLibtoolflags", "(", "configname", ")", ",", "'LIBTOOLFLAGS_%s'", "%", "configname", ")", "libraries", "=", "spec", ".", "get", "(", "'libraries'", ")", "if", "libraries", ":", "# Remove duplicate entries", "libraries", "=", "gyp", ".", "common", ".", "uniquer", "(", "libraries", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "libraries", "=", "self", ".", "xcode_settings", ".", "AdjustLibraries", "(", "libraries", ")", "self", ".", "WriteList", "(", "libraries", ",", "'LIBS'", ")", "self", ".", "WriteLn", "(", "'%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))'", "%", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ")", "self", ".", "WriteLn", "(", "'%s: LIBS := $(LIBS)'", "%", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteLn", "(", "'%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))'", "%", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ")", "# Postbuild actions. Like actions, but implicitly depend on the target's", "# output.", "postbuilds", "=", "[", "]", "if", "self", ".", "flavor", "==", "'mac'", ":", "if", "target_postbuilds", ":", "postbuilds", ".", "append", "(", "'$(TARGET_POSTBUILDS_$(BUILDTYPE))'", ")", "postbuilds", ".", "extend", "(", "gyp", ".", "xcode_emulation", ".", "GetSpecPostbuildCommands", "(", "spec", ")", ")", "if", "postbuilds", ":", "# Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE),", "# so we must output its definition first, since we declare variables", "# using \":=\".", "self", ".", "WriteSortedXcodeEnv", "(", "self", ".", "output", ",", "self", ".", "GetSortedXcodePostbuildEnv", "(", ")", ")", "for", "configname", "in", "target_postbuilds", ":", "self", ".", "WriteLn", "(", "'%s: TARGET_POSTBUILDS_%s := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output", ")", ",", "configname", ",", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "target_postbuilds", "[", "configname", "]", ")", ")", ")", "# Postbuilds expect to be run in the gyp file's directory, so insert an", "# implicit postbuild to cd to there.", "postbuilds", ".", "insert", "(", "0", ",", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "[", "'cd'", ",", "self", ".", "path", "]", ")", ")", "for", "i", "in", "range", "(", "len", "(", "postbuilds", ")", ")", ":", "if", "not", "postbuilds", "[", "i", "]", ".", "startswith", "(", "'$'", ")", ":", "postbuilds", "[", "i", "]", "=", "EscapeShellArgument", "(", "postbuilds", "[", "i", "]", ")", "self", ".", "WriteLn", "(", "'%s: builddir := $(abs_builddir)'", "%", "QuoteSpaces", "(", "self", ".", "output", ")", ")", "self", ".", "WriteLn", "(", "'%s: POSTBUILDS := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output", ")", ",", "' '", ".", "join", "(", "postbuilds", ")", ")", ")", "# A bundle directory depends on its dependencies such as bundle resources", "# and bundle binary. When all dependencies have been built, the bundle", "# needs to be packaged.", "if", "self", ".", "is_mac_bundle", ":", "# If the framework doesn't contain a binary, then nothing depends", "# on the actions -- make the framework depend on them directly too.", "self", ".", "WriteDependencyOnExtraOutputs", "(", "self", ".", "output", ",", "extra_outputs", ")", "# Bundle dependencies. Note that the code below adds actions to this", "# target, so if you move these two lines, move the lines below as well.", "self", ".", "WriteList", "(", "[", "QuoteSpaces", "(", "dep", ")", "for", "dep", "in", "bundle_deps", "]", ",", "'BUNDLE_DEPS'", ")", "self", ".", "WriteLn", "(", "'%s: $(BUNDLE_DEPS)'", "%", "QuoteSpaces", "(", "self", ".", "output", ")", ")", "# After the framework is built, package it. Needs to happen before", "# postbuilds, since postbuilds depend on this.", "if", "self", ".", "type", "in", "(", "'shared_library'", ",", "'loadable_module'", ")", ":", "self", ".", "WriteLn", "(", "'\\t@$(call do_cmd,mac_package_framework,,,%s)'", "%", "self", ".", "xcode_settings", ".", "GetFrameworkVersion", "(", ")", ")", "# Bundle postbuilds can depend on the whole bundle, so run them after", "# the bundle is packaged, not already after the bundle binary is done.", "if", "postbuilds", ":", "self", ".", "WriteLn", "(", "'\\t@$(call do_postbuilds)'", ")", "postbuilds", "=", "[", "]", "# Don't write postbuilds for target's output.", "# Needed by test/mac/gyptest-rebuild.py.", "self", ".", "WriteLn", "(", "'\\t@true # No-op, used by tests'", ")", "# Since this target depends on binary and resources which are in", "# nested subfolders, the framework directory will be older than", "# its dependencies usually. To prevent this rule from executing", "# on every build (expensive, especially with postbuilds), expliclity", "# update the time on the framework directory.", "self", ".", "WriteLn", "(", "'\\t@touch -c %s'", "%", "QuoteSpaces", "(", "self", ".", "output", ")", ")", "if", "postbuilds", ":", "assert", "not", "self", ".", "is_mac_bundle", ",", "(", "'Postbuilds for bundles should be done '", "'on the bundle, not the binary (target \\'%s\\')'", "%", "self", ".", "target", ")", "assert", "'product_dir'", "not", "in", "spec", ",", "(", "'Postbuilds do not work with '", "'custom product_dir'", ")", "if", "self", ".", "type", "==", "'executable'", ":", "self", ".", "WriteLn", "(", "'%s: LD_INPUTS := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ",", "' '", ".", "join", "(", "QuoteSpaces", "(", "dep", ")", "for", "dep", "in", "link_deps", ")", ")", ")", "if", "self", ".", "toolset", "==", "'host'", "and", "self", ".", "flavor", "==", "'android'", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'link_host'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'link'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'static_library'", ":", "for", "link_dep", "in", "link_deps", ":", "assert", "' '", "not", "in", "link_dep", ",", "(", "\"Spaces in alink input filenames not supported (%s)\"", "%", "link_dep", ")", "if", "(", "self", ".", "flavor", "not", "in", "(", "'mac'", ",", "'openbsd'", ",", "'netbsd'", ",", "'win'", ")", "and", "not", "self", ".", "is_standalone_static_library", ")", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'alink_thin'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'alink'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'shared_library'", ":", "self", ".", "WriteLn", "(", "'%s: LD_INPUTS := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ",", "' '", ".", "join", "(", "QuoteSpaces", "(", "dep", ")", "for", "dep", "in", "link_deps", ")", ")", ")", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'solink'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'loadable_module'", ":", "for", "link_dep", "in", "link_deps", ":", "assert", "' '", "not", "in", "link_dep", ",", "(", "\"Spaces in module input filenames not supported (%s)\"", "%", "link_dep", ")", "if", "self", ".", "toolset", "==", "'host'", "and", "self", ".", "flavor", "==", "'android'", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'solink_module_host'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'solink_module'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'none'", ":", "# Write a stamp line.", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "deps", ",", "'touch'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "print", "(", "\"WARNING: no output for\"", ",", "self", ".", "type", ",", "self", ".", "target", ")", "# Add an alias for each target (if there are any outputs).", "# Installable target aliases are created below.", "if", "(", "(", "self", ".", "output", "and", "self", ".", "output", "!=", "self", ".", "target", ")", "and", "(", "self", ".", "type", "not", "in", "self", ".", "_INSTALLABLE_TARGETS", ")", ")", ":", "self", ".", "WriteMakeRule", "(", "[", "self", ".", "target", "]", ",", "[", "self", ".", "output", "]", ",", "comment", "=", "'Add target alias'", ",", "phony", "=", "True", ")", "if", "part_of_all", ":", "self", ".", "WriteMakeRule", "(", "[", "'all'", "]", ",", "[", "self", ".", "target", "]", ",", "comment", "=", "'Add target alias to \"all\" target.'", ",", "phony", "=", "True", ")", "# Add special-case rules for our installable targets.", "# 1) They need to install to the build dir or \"product\" dir.", "# 2) They get shortcuts for building (e.g. \"make chrome\").", "# 3) They are part of \"make all\".", "if", "(", "self", ".", "type", "in", "self", ".", "_INSTALLABLE_TARGETS", "or", "self", ".", "is_standalone_static_library", ")", ":", "if", "self", ".", "type", "==", "'shared_library'", ":", "file_desc", "=", "'shared library'", "elif", "self", ".", "type", "==", "'static_library'", ":", "file_desc", "=", "'static library'", "else", ":", "file_desc", "=", "'executable'", "install_path", "=", "self", ".", "_InstallableTargetInstallPath", "(", ")", "installable_deps", "=", "[", "self", ".", "output", "]", "if", "(", "self", ".", "flavor", "==", "'mac'", "and", "not", "'product_dir'", "in", "spec", "and", "self", ".", "toolset", "==", "'target'", ")", ":", "# On mac, products are created in install_path immediately.", "assert", "install_path", "==", "self", ".", "output", ",", "'%s != %s'", "%", "(", "install_path", ",", "self", ".", "output", ")", "# Point the target alias to the final binary output.", "self", ".", "WriteMakeRule", "(", "[", "self", ".", "target", "]", ",", "[", "install_path", "]", ",", "comment", "=", "'Add target alias'", ",", "phony", "=", "True", ")", "if", "install_path", "!=", "self", ".", "output", ":", "assert", "not", "self", ".", "is_mac_bundle", "# See comment a few lines above.", "self", ".", "WriteDoCmd", "(", "[", "install_path", "]", ",", "[", "self", ".", "output", "]", ",", "'copy'", ",", "comment", "=", "'Copy this to the %s output path.'", "%", "file_desc", ",", "part_of_all", "=", "part_of_all", ")", "installable_deps", ".", "append", "(", "install_path", ")", "if", "self", ".", "output", "!=", "self", ".", "alias", "and", "self", ".", "alias", "!=", "self", ".", "target", ":", "self", ".", "WriteMakeRule", "(", "[", "self", ".", "alias", "]", ",", "installable_deps", ",", "comment", "=", "'Short alias for building this %s.'", "%", "file_desc", ",", "phony", "=", "True", ")", "if", "part_of_all", ":", "self", ".", "WriteMakeRule", "(", "[", "'all'", "]", ",", "[", "install_path", "]", ",", "comment", "=", "'Add %s to \"all\" target.'", "%", "file_desc", ",", "phony", "=", "True", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py#L1458-L1691
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/multiprocessing/util.py
python
close_fds
(*fds)
Close each file descriptor given as an argument
Close each file descriptor given as an argument
[ "Close", "each", "file", "descriptor", "given", "as", "an", "argument" ]
def close_fds(*fds): """Close each file descriptor given as an argument""" for fd in fds: os.close(fd)
[ "def", "close_fds", "(", "*", "fds", ")", ":", "for", "fd", "in", "fds", ":", "os", ".", "close", "(", "fd", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/util.py#L476-L479
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
xmlTextReader.ReadOuterXml
(self)
return ret
Reads the contents of the current node, including child nodes and markup.
Reads the contents of the current node, including child nodes and markup.
[ "Reads", "the", "contents", "of", "the", "current", "node", "including", "child", "nodes", "and", "markup", "." ]
def ReadOuterXml(self): """Reads the contents of the current node, including child nodes and markup. """ ret = libxml2mod.xmlTextReaderReadOuterXml(self._o) return ret
[ "def", "ReadOuterXml", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlTextReaderReadOuterXml", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L6844-L6848
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/chardet/cli/chardetect.py
python
description_of
(lines, name='stdin')
Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str
Return a string describing the probable encoding of a file or list of strings.
[ "Return", "a", "string", "describing", "the", "probable", "encoding", "of", "a", "file", "or", "list", "of", "strings", "." ]
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = UniversalDetector() for line in lines: line = bytearray(line) u.feed(line) # shortcut out of the loop to save reading further - particularly useful if we read a BOM. if u.done: break u.close() result = u.result if PY2: name = name.decode(sys.getfilesystemencoding(), 'ignore') if result['encoding']: return '{0}: {1} with confidence {2}'.format(name, result['encoding'], result['confidence']) else: return '{0}: no result'.format(name)
[ "def", "description_of", "(", "lines", ",", "name", "=", "'stdin'", ")", ":", "u", "=", "UniversalDetector", "(", ")", "for", "line", "in", "lines", ":", "line", "=", "bytearray", "(", "line", ")", "u", ".", "feed", "(", "line", ")", "# shortcut out of the loop to save reading further - particularly useful if we read a BOM.", "if", "u", ".", "done", ":", "break", "u", ".", "close", "(", ")", "result", "=", "u", ".", "result", "if", "PY2", ":", "name", "=", "name", ".", "decode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ",", "'ignore'", ")", "if", "result", "[", "'encoding'", "]", ":", "return", "'{0}: {1} with confidence {2}'", ".", "format", "(", "name", ",", "result", "[", "'encoding'", "]", ",", "result", "[", "'confidence'", "]", ")", "else", ":", "return", "'{0}: no result'", ".", "format", "(", "name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/chardet/cli/chardetect.py#L26-L51
dmlc/treelite
df56babb6a4a2d7c29d719c28ce53acfa7dbab3c
runtime/python/treelite_runtime/libpath.py
python
find_lib_path
()
return lib_path
Find the path to Treelite runtime library files. Returns ------- lib_path: :py:class:`list <python:list>` of :py:class:`str <python:str>` List of all found library path to Treelite
Find the path to Treelite runtime library files.
[ "Find", "the", "path", "to", "Treelite", "runtime", "library", "files", "." ]
def find_lib_path(): """Find the path to Treelite runtime library files. Returns ------- lib_path: :py:class:`list <python:list>` of :py:class:`str <python:str>` List of all found library path to Treelite """ if sys.platform == 'win32': lib_name = f'treelite_runtime.dll' elif sys.platform.startswith('linux'): lib_name = f'libtreelite_runtime.so' elif sys.platform == 'darwin': lib_name = f'libtreelite_runtime.dylib' else: raise RuntimeError('Unsupported operating system') curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) # List possible locations for the library file dll_path = [ # normal, after installation `lib` is copied into Python package tree. os.path.join(curr_path, 'lib'), # editable installation, no copying is performed. os.path.join(curr_path, os.path.pardir, os.path.pardir, os.path.pardir, 'build') ] # Windows hack: additional candidate locations if sys.platform == 'win32': if platform.architecture()[0] == '64bit': dll_path.append(os.path.join(curr_path, '../../windows/x64/Release/')) # hack for pip installation when copy all parent source directory here dll_path.append(os.path.join(curr_path, './windows/x64/Release/')) else: dll_path.append(os.path.join(curr_path, '../../windows/Release/')) # hack for pip installation when copy all parent source directory here dll_path.append(os.path.join(curr_path, './windows/Release/')) # Now examine all candidate locations for the library file dll_path = [os.path.join(p, lib_name) for p in dll_path] lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)] if not lib_path: candidate_list = '\n'.join(dll_path) raise TreeliteRuntimeLibraryNotFound( f'Cannot find library {lib_name} in the candidate path: ' + f'List of candidates:\n{os.path.normpath(candidate_list)}\n') return lib_path
[ "def", "find_lib_path", "(", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "lib_name", "=", "f'treelite_runtime.dll'", "elif", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "lib_name", "=", "f'libtreelite_runtime.so'", "elif", "sys", ".", "platform", "==", "'darwin'", ":", "lib_name", "=", "f'libtreelite_runtime.dylib'", "else", ":", "raise", "RuntimeError", "(", "'Unsupported operating system'", ")", "curr_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "__file__", ")", ")", ")", "# List possible locations for the library file", "dll_path", "=", "[", "# normal, after installation `lib` is copied into Python package tree.", "os", ".", "path", ".", "join", "(", "curr_path", ",", "'lib'", ")", ",", "# editable installation, no copying is performed.", "os", ".", "path", ".", "join", "(", "curr_path", ",", "os", ".", "path", ".", "pardir", ",", "os", ".", "path", ".", "pardir", ",", "os", ".", "path", ".", "pardir", ",", "'build'", ")", "]", "# Windows hack: additional candidate locations", "if", "sys", ".", "platform", "==", "'win32'", ":", "if", "platform", ".", "architecture", "(", ")", "[", "0", "]", "==", "'64bit'", ":", "dll_path", ".", "append", "(", "os", ".", "path", ".", "join", "(", "curr_path", ",", "'../../windows/x64/Release/'", ")", ")", "# hack for pip installation when copy all parent source directory here", "dll_path", ".", "append", "(", "os", ".", "path", ".", "join", "(", "curr_path", ",", "'./windows/x64/Release/'", ")", ")", "else", ":", "dll_path", ".", "append", "(", "os", ".", "path", ".", "join", "(", "curr_path", ",", "'../../windows/Release/'", ")", ")", "# hack for pip installation when copy all parent source directory here", "dll_path", ".", "append", "(", "os", ".", "path", ".", "join", "(", "curr_path", ",", "'./windows/Release/'", ")", ")", "# Now examine all candidate locations for the library file", "dll_path", "=", "[", "os", ".", "path", ".", "join", "(", "p", ",", "lib_name", ")", "for", "p", "in", "dll_path", "]", "lib_path", "=", "[", "p", "for", "p", "in", "dll_path", "if", "os", ".", "path", ".", "exists", "(", "p", ")", "and", "os", ".", "path", ".", "isfile", "(", "p", ")", "]", "if", "not", "lib_path", ":", "candidate_list", "=", "'\\n'", ".", "join", "(", "dll_path", ")", "raise", "TreeliteRuntimeLibraryNotFound", "(", "f'Cannot find library {lib_name} in the candidate path: '", "+", "f'List of candidates:\\n{os.path.normpath(candidate_list)}\\n'", ")", "return", "lib_path" ]
https://github.com/dmlc/treelite/blob/df56babb6a4a2d7c29d719c28ce53acfa7dbab3c/runtime/python/treelite_runtime/libpath.py#L13-L57
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/descriptor_pool.py
python
DescriptorPool.FindFileByName
(self, file_name)
return self._ConvertFileProtoToFileDescriptor(file_proto)
Gets a FileDescriptor by file name. Args: file_name (str): The path to the file to get a descriptor for. Returns: FileDescriptor: The descriptor for the named file. Raises: KeyError: if the file cannot be found in the pool.
Gets a FileDescriptor by file name.
[ "Gets", "a", "FileDescriptor", "by", "file", "name", "." ]
def FindFileByName(self, file_name): """Gets a FileDescriptor by file name. Args: file_name (str): The path to the file to get a descriptor for. Returns: FileDescriptor: The descriptor for the named file. Raises: KeyError: if the file cannot be found in the pool. """ try: return self._file_descriptors[file_name] except KeyError: pass try: file_proto = self._internal_db.FindFileByName(file_name) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileByName(file_name) else: raise error if not file_proto: raise KeyError('Cannot find a file named %s' % file_name) return self._ConvertFileProtoToFileDescriptor(file_proto)
[ "def", "FindFileByName", "(", "self", ",", "file_name", ")", ":", "try", ":", "return", "self", ".", "_file_descriptors", "[", "file_name", "]", "except", "KeyError", ":", "pass", "try", ":", "file_proto", "=", "self", ".", "_internal_db", ".", "FindFileByName", "(", "file_name", ")", "except", "KeyError", "as", "error", ":", "if", "self", ".", "_descriptor_db", ":", "file_proto", "=", "self", ".", "_descriptor_db", ".", "FindFileByName", "(", "file_name", ")", "else", ":", "raise", "error", "if", "not", "file_proto", ":", "raise", "KeyError", "(", "'Cannot find a file named %s'", "%", "file_name", ")", "return", "self", ".", "_ConvertFileProtoToFileDescriptor", "(", "file_proto", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/descriptor_pool.py#L391-L418
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/timeseries/python/timeseries/state_space_models/level_trend.py
python
AdderStateSpaceModel.transition_power_noise_accumulator
(self, num_steps)
return _pack_and_reshape( num_steps * a + sum_of_first_n * (b + c) + sum_of_first_n_squares * d, num_steps * b + sum_of_first_n * d, num_steps * c + sum_of_first_n * d, num_steps * d)
Computes power sums in closed form.
Computes power sums in closed form.
[ "Computes", "power", "sums", "in", "closed", "form", "." ]
def transition_power_noise_accumulator(self, num_steps): """Computes power sums in closed form.""" def _pack_and_reshape(*values): return array_ops.reshape( array_ops.stack(axis=1, values=values), array_ops.concat(values=[array_ops.shape(num_steps), [2, 2]], axis=0)) num_steps = math_ops.cast(num_steps, self.dtype) noise_transitions = num_steps - 1 noise_transform = ops.convert_to_tensor(self.get_noise_transform(), self.dtype) noise_covariance_transformed = math_ops.matmul( math_ops.matmul(noise_transform, self.state_transition_noise_covariance), noise_transform, adjoint_b=True) # Un-packing the transformed noise as: # [[a b] # [c d]] a, b, c, d = array_ops.unstack( array_ops.reshape(noise_covariance_transformed, [-1, 4]), axis=1) sum_of_first_n = noise_transitions * (noise_transitions + 1) / 2 sum_of_first_n_squares = sum_of_first_n * (2 * noise_transitions + 1) / 3 return _pack_and_reshape( num_steps * a + sum_of_first_n * (b + c) + sum_of_first_n_squares * d, num_steps * b + sum_of_first_n * d, num_steps * c + sum_of_first_n * d, num_steps * d)
[ "def", "transition_power_noise_accumulator", "(", "self", ",", "num_steps", ")", ":", "def", "_pack_and_reshape", "(", "*", "values", ")", ":", "return", "array_ops", ".", "reshape", "(", "array_ops", ".", "stack", "(", "axis", "=", "1", ",", "values", "=", "values", ")", ",", "array_ops", ".", "concat", "(", "values", "=", "[", "array_ops", ".", "shape", "(", "num_steps", ")", ",", "[", "2", ",", "2", "]", "]", ",", "axis", "=", "0", ")", ")", "num_steps", "=", "math_ops", ".", "cast", "(", "num_steps", ",", "self", ".", "dtype", ")", "noise_transitions", "=", "num_steps", "-", "1", "noise_transform", "=", "ops", ".", "convert_to_tensor", "(", "self", ".", "get_noise_transform", "(", ")", ",", "self", ".", "dtype", ")", "noise_covariance_transformed", "=", "math_ops", ".", "matmul", "(", "math_ops", ".", "matmul", "(", "noise_transform", ",", "self", ".", "state_transition_noise_covariance", ")", ",", "noise_transform", ",", "adjoint_b", "=", "True", ")", "# Un-packing the transformed noise as:", "# [[a b]", "# [c d]]", "a", ",", "b", ",", "c", ",", "d", "=", "array_ops", ".", "unstack", "(", "array_ops", ".", "reshape", "(", "noise_covariance_transformed", ",", "[", "-", "1", ",", "4", "]", ")", ",", "axis", "=", "1", ")", "sum_of_first_n", "=", "noise_transitions", "*", "(", "noise_transitions", "+", "1", ")", "/", "2", "sum_of_first_n_squares", "=", "sum_of_first_n", "*", "(", "2", "*", "noise_transitions", "+", "1", ")", "/", "3", "return", "_pack_and_reshape", "(", "num_steps", "*", "a", "+", "sum_of_first_n", "*", "(", "b", "+", "c", ")", "+", "sum_of_first_n_squares", "*", "d", ",", "num_steps", "*", "b", "+", "sum_of_first_n", "*", "d", ",", "num_steps", "*", "c", "+", "sum_of_first_n", "*", "d", ",", "num_steps", "*", "d", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/state_space_models/level_trend.py#L93-L120
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/nn_ops.py
python
KLDivLoss.__init__
(self, reduction='mean')
Initialize KLDivLoss.
Initialize KLDivLoss.
[ "Initialize", "KLDivLoss", "." ]
def __init__(self, reduction='mean'): """Initialize KLDivLoss.""" self.reduction = validator.check_string(reduction, ['none', 'mean', 'sum'], 'reduction', self.name)
[ "def", "__init__", "(", "self", ",", "reduction", "=", "'mean'", ")", ":", "self", ".", "reduction", "=", "validator", ".", "check_string", "(", "reduction", ",", "[", "'none'", ",", "'mean'", ",", "'sum'", "]", ",", "'reduction'", ",", "self", ".", "name", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/nn_ops.py#L5138-L5140
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/lib2to3/pytree.py
python
WildcardPattern._bare_name_matches
(self, nodes)
return count, r
Special optimized matcher for bare_name.
Special optimized matcher for bare_name.
[ "Special", "optimized", "matcher", "for", "bare_name", "." ]
def _bare_name_matches(self, nodes): """Special optimized matcher for bare_name.""" count = 0 r = {} done = False max = len(nodes) while not done and count < max: done = True for leaf in self.content: if leaf[0].match(nodes[count], r): count += 1 done = False break r[self.name] = nodes[:count] return count, r
[ "def", "_bare_name_matches", "(", "self", ",", "nodes", ")", ":", "count", "=", "0", "r", "=", "{", "}", "done", "=", "False", "max", "=", "len", "(", "nodes", ")", "while", "not", "done", "and", "count", "<", "max", ":", "done", "=", "True", "for", "leaf", "in", "self", ".", "content", ":", "if", "leaf", "[", "0", "]", ".", "match", "(", "nodes", "[", "count", "]", ",", "r", ")", ":", "count", "+=", "1", "done", "=", "False", "break", "r", "[", "self", ".", "name", "]", "=", "nodes", "[", ":", "count", "]", "return", "count", ",", "r" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/lib2to3/pytree.py#L762-L776
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/CommandBody.py
python
CommandBody.accept
(self, visitor)
The operation in Visitor design pattern that takes a visitor as an argument and calls the visitor's method that corresponds to this element. @raise Exception: if the given visitor is not a subclass of AbstractVisitor
The operation in Visitor design pattern that takes a visitor as an argument and calls the visitor's method that corresponds to this element.
[ "The", "operation", "in", "Visitor", "design", "pattern", "that", "takes", "a", "visitor", "as", "an", "argument", "and", "calls", "the", "visitor", "s", "method", "that", "corresponds", "to", "this", "element", "." ]
def accept(self, visitor): """ The operation in Visitor design pattern that takes a visitor as an argument and calls the visitor's method that corresponds to this element. @raise Exception: if the given visitor is not a subclass of AbstractVisitor """ # visitor should be extended from the AbstractVisitor class if issubclass(visitor.__class__, AbstractVisitor.AbstractVisitor): visitor.commandBodyVisit(self.__obj) else: DEBUG.error( "startCommandVisit.accept() - the given visitor is not a subclass of AbstractVisitor!" ) raise Exception( "startCommandVisit.accept() - the given visitor is not a subclass of AbstractVisitor!" )
[ "def", "accept", "(", "self", ",", "visitor", ")", ":", "# visitor should be extended from the AbstractVisitor class", "if", "issubclass", "(", "visitor", ".", "__class__", ",", "AbstractVisitor", ".", "AbstractVisitor", ")", ":", "visitor", ".", "commandBodyVisit", "(", "self", ".", "__obj", ")", "else", ":", "DEBUG", ".", "error", "(", "\"startCommandVisit.accept() - the given visitor is not a subclass of AbstractVisitor!\"", ")", "raise", "Exception", "(", "\"startCommandVisit.accept() - the given visitor is not a subclass of AbstractVisitor!\"", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/CommandBody.py#L69-L84
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings._GetStandaloneBinaryPath
(self)
return target_prefix + target + target_ext
Returns the name of the non-bundle binary represented by this target. E.g. hello_world. Only valid for non-bundles.
Returns the name of the non-bundle binary represented by this target. E.g. hello_world. Only valid for non-bundles.
[ "Returns", "the", "name", "of", "the", "non", "-", "bundle", "binary", "represented", "by", "this", "target", ".", "E", ".", "g", ".", "hello_world", ".", "Only", "valid", "for", "non", "-", "bundles", "." ]
def _GetStandaloneBinaryPath(self): """Returns the name of the non-bundle binary represented by this target. E.g. hello_world. Only valid for non-bundles.""" assert not self._IsBundle() assert self.spec['type'] in ( 'executable', 'shared_library', 'static_library', 'loadable_module'), ( 'Unexpected type %s' % self.spec['type']) target = self.spec['target_name'] if self.spec['type'] == 'static_library': if target[:3] == 'lib': target = target[3:] elif self.spec['type'] in ('loadable_module', 'shared_library'): if target[:3] == 'lib': target = target[3:] target_prefix = self._GetStandaloneExecutablePrefix() target = self.spec.get('product_name', target) target_ext = self._GetStandaloneExecutableSuffix() return target_prefix + target + target_ext
[ "def", "_GetStandaloneBinaryPath", "(", "self", ")", ":", "assert", "not", "self", ".", "_IsBundle", "(", ")", "assert", "self", ".", "spec", "[", "'type'", "]", "in", "(", "'executable'", ",", "'shared_library'", ",", "'static_library'", ",", "'loadable_module'", ")", ",", "(", "'Unexpected type %s'", "%", "self", ".", "spec", "[", "'type'", "]", ")", "target", "=", "self", ".", "spec", "[", "'target_name'", "]", "if", "self", ".", "spec", "[", "'type'", "]", "==", "'static_library'", ":", "if", "target", "[", ":", "3", "]", "==", "'lib'", ":", "target", "=", "target", "[", "3", ":", "]", "elif", "self", ".", "spec", "[", "'type'", "]", "in", "(", "'loadable_module'", ",", "'shared_library'", ")", ":", "if", "target", "[", ":", "3", "]", "==", "'lib'", ":", "target", "=", "target", "[", "3", ":", "]", "target_prefix", "=", "self", ".", "_GetStandaloneExecutablePrefix", "(", ")", "target", "=", "self", ".", "spec", ".", "get", "(", "'product_name'", ",", "target", ")", "target_ext", "=", "self", ".", "_GetStandaloneExecutableSuffix", "(", ")", "return", "target_prefix", "+", "target", "+", "target_ext" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L384-L402
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/distributions/bijector_impl.py
python
Bijector._lookup
(self, x=None, y=None, kwargs=None)
return mapping
Helper which retrieves mapping info from forward/inverse dicts.
Helper which retrieves mapping info from forward/inverse dicts.
[ "Helper", "which", "retrieves", "mapping", "info", "from", "forward", "/", "inverse", "dicts", "." ]
def _lookup(self, x=None, y=None, kwargs=None): """Helper which retrieves mapping info from forward/inverse dicts.""" mapping = _Mapping(x=x, y=y, kwargs=kwargs) # Since _cache requires both x,y to be set, we only need to do one cache # lookup since the mapping is always in both or neither. if mapping.x is not None: return self._from_x.get(mapping.x_key, mapping) if mapping.y is not None: return self._from_y.get(mapping.y_key, mapping) return mapping
[ "def", "_lookup", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ",", "kwargs", "=", "None", ")", ":", "mapping", "=", "_Mapping", "(", "x", "=", "x", ",", "y", "=", "y", ",", "kwargs", "=", "kwargs", ")", "# Since _cache requires both x,y to be set, we only need to do one cache", "# lookup since the mapping is always in both or neither.", "if", "mapping", ".", "x", "is", "not", "None", ":", "return", "self", ".", "_from_x", ".", "get", "(", "mapping", ".", "x_key", ",", "mapping", ")", "if", "mapping", ".", "y", "is", "not", "None", ":", "return", "self", ".", "_from_y", ".", "get", "(", "mapping", ".", "y_key", ",", "mapping", ")", "return", "mapping" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/distributions/bijector_impl.py#L1019-L1028
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/ma/mrecords.py
python
fromtextfile
(fname, delimitor=None, commentchar='#', missingchar='', varnames=None, vartypes=None)
return fromarrays(_datalist, dtype=mdescr)
Creates a mrecarray from data stored in the file `filename`. Parameters ---------- fname : {file name/handle} Handle of an opened file. delimitor : {None, string}, optional Alphanumeric character used to separate columns in the file. If None, any (group of) white spacestring(s) will be used. commentchar : {'#', string}, optional Alphanumeric character used to mark the start of a comment. missingchar : {'', string}, optional String indicating missing data, and used to create the masks. varnames : {None, sequence}, optional Sequence of the variable names. If None, a list will be created from the first non empty line of the file. vartypes : {None, sequence}, optional Sequence of the variables dtypes. If None, it will be estimated from the first non-commented line. Ultra simple: the varnames are in the header, one line
Creates a mrecarray from data stored in the file `filename`.
[ "Creates", "a", "mrecarray", "from", "data", "stored", "in", "the", "file", "filename", "." ]
def fromtextfile(fname, delimitor=None, commentchar='#', missingchar='', varnames=None, vartypes=None): """ Creates a mrecarray from data stored in the file `filename`. Parameters ---------- fname : {file name/handle} Handle of an opened file. delimitor : {None, string}, optional Alphanumeric character used to separate columns in the file. If None, any (group of) white spacestring(s) will be used. commentchar : {'#', string}, optional Alphanumeric character used to mark the start of a comment. missingchar : {'', string}, optional String indicating missing data, and used to create the masks. varnames : {None, sequence}, optional Sequence of the variable names. If None, a list will be created from the first non empty line of the file. vartypes : {None, sequence}, optional Sequence of the variables dtypes. If None, it will be estimated from the first non-commented line. Ultra simple: the varnames are in the header, one line""" # Try to open the file. ftext = openfile(fname) # Get the first non-empty line as the varnames while True: line = ftext.readline() firstline = line[:line.find(commentchar)].strip() _varnames = firstline.split(delimitor) if len(_varnames) > 1: break if varnames is None: varnames = _varnames # Get the data. _variables = masked_array([line.strip().split(delimitor) for line in ftext if line[0] != commentchar and len(line) > 1]) (_, nfields) = _variables.shape ftext.close() # Try to guess the dtype. if vartypes is None: vartypes = _guessvartypes(_variables[0]) else: vartypes = [np.dtype(v) for v in vartypes] if len(vartypes) != nfields: msg = "Attempting to %i dtypes for %i fields!" msg += " Reverting to default." warnings.warn(msg % (len(vartypes), nfields), stacklevel=2) vartypes = _guessvartypes(_variables[0]) # Construct the descriptor. mdescr = [(n, f) for (n, f) in zip(varnames, vartypes)] mfillv = [ma.default_fill_value(f) for f in vartypes] # Get the data and the mask. # We just need a list of masked_arrays. It's easier to create it like that: _mask = (_variables.T == missingchar) _datalist = [masked_array(a, mask=m, dtype=t, fill_value=f) for (a, m, t, f) in zip(_variables.T, _mask, vartypes, mfillv)] return fromarrays(_datalist, dtype=mdescr)
[ "def", "fromtextfile", "(", "fname", ",", "delimitor", "=", "None", ",", "commentchar", "=", "'#'", ",", "missingchar", "=", "''", ",", "varnames", "=", "None", ",", "vartypes", "=", "None", ")", ":", "# Try to open the file.", "ftext", "=", "openfile", "(", "fname", ")", "# Get the first non-empty line as the varnames", "while", "True", ":", "line", "=", "ftext", ".", "readline", "(", ")", "firstline", "=", "line", "[", ":", "line", ".", "find", "(", "commentchar", ")", "]", ".", "strip", "(", ")", "_varnames", "=", "firstline", ".", "split", "(", "delimitor", ")", "if", "len", "(", "_varnames", ")", ">", "1", ":", "break", "if", "varnames", "is", "None", ":", "varnames", "=", "_varnames", "# Get the data.", "_variables", "=", "masked_array", "(", "[", "line", ".", "strip", "(", ")", ".", "split", "(", "delimitor", ")", "for", "line", "in", "ftext", "if", "line", "[", "0", "]", "!=", "commentchar", "and", "len", "(", "line", ")", ">", "1", "]", ")", "(", "_", ",", "nfields", ")", "=", "_variables", ".", "shape", "ftext", ".", "close", "(", ")", "# Try to guess the dtype.", "if", "vartypes", "is", "None", ":", "vartypes", "=", "_guessvartypes", "(", "_variables", "[", "0", "]", ")", "else", ":", "vartypes", "=", "[", "np", ".", "dtype", "(", "v", ")", "for", "v", "in", "vartypes", "]", "if", "len", "(", "vartypes", ")", "!=", "nfields", ":", "msg", "=", "\"Attempting to %i dtypes for %i fields!\"", "msg", "+=", "\" Reverting to default.\"", "warnings", ".", "warn", "(", "msg", "%", "(", "len", "(", "vartypes", ")", ",", "nfields", ")", ",", "stacklevel", "=", "2", ")", "vartypes", "=", "_guessvartypes", "(", "_variables", "[", "0", "]", ")", "# Construct the descriptor.", "mdescr", "=", "[", "(", "n", ",", "f", ")", "for", "(", "n", ",", "f", ")", "in", "zip", "(", "varnames", ",", "vartypes", ")", "]", "mfillv", "=", "[", "ma", ".", "default_fill_value", "(", "f", ")", "for", "f", "in", "vartypes", "]", "# Get the data and the mask.", "# We just need a list of masked_arrays. It's easier to create it like that:", "_mask", "=", "(", "_variables", ".", "T", "==", "missingchar", ")", "_datalist", "=", "[", "masked_array", "(", "a", ",", "mask", "=", "m", ",", "dtype", "=", "t", ",", "fill_value", "=", "f", ")", "for", "(", "a", ",", "m", ",", "t", ",", "f", ")", "in", "zip", "(", "_variables", ".", "T", ",", "_mask", ",", "vartypes", ",", "mfillv", ")", "]", "return", "fromarrays", "(", "_datalist", ",", "dtype", "=", "mdescr", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/mrecords.py#L672-L737
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/pipeline/sync/skip/skippable.py
python
Skippable.poppable
(self)
Iterates over namespaced skip names to be popped.
Iterates over namespaced skip names to be popped.
[ "Iterates", "over", "namespaced", "skip", "names", "to", "be", "popped", "." ]
def poppable(self) -> Iterable[Tuple[Namespace, str]]: """Iterates over namespaced skip names to be popped.""" for name in self.poppable_names: yield self.namespaced(name)
[ "def", "poppable", "(", "self", ")", "->", "Iterable", "[", "Tuple", "[", "Namespace", ",", "str", "]", "]", ":", "for", "name", "in", "self", ".", "poppable_names", ":", "yield", "self", ".", "namespaced", "(", "name", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/pipeline/sync/skip/skippable.py#L83-L86
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/sslproto.py
python
SSLProtocol.resume_writing
(self)
Called when the low-level transport's buffer drains below the low-water mark.
Called when the low-level transport's buffer drains below the low-water mark.
[ "Called", "when", "the", "low", "-", "level", "transport", "s", "buffer", "drains", "below", "the", "low", "-", "water", "mark", "." ]
def resume_writing(self): """Called when the low-level transport's buffer drains below the low-water mark. """ self._app_protocol.resume_writing()
[ "def", "resume_writing", "(", "self", ")", ":", "self", ".", "_app_protocol", ".", "resume_writing", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/sslproto.py#L514-L518
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/selectionDataModel.py
python
Blocker.blocked
(self)
return self._count > 0
Returns True if in the 'blocked' state, and False otherwise.
Returns True if in the 'blocked' state, and False otherwise.
[ "Returns", "True", "if", "in", "the", "blocked", "state", "and", "False", "otherwise", "." ]
def blocked(self): """Returns True if in the 'blocked' state, and False otherwise.""" return self._count > 0
[ "def", "blocked", "(", "self", ")", ":", "return", "self", ".", "_count", ">", "0" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/selectionDataModel.py#L67-L70
nest/nest-simulator
f2623eb78518cdbd55e77e0ed486bf1111bcb62f
pynest/nest/lib/hl_api_connections.py
python
Connect
(pre, post, conn_spec=None, syn_spec=None, return_synapsecollection=False)
Connect `pre` nodes to `post` nodes. Nodes in `pre` and `post` are connected using the specified connectivity (`all-to-all` by default) and synapse type (:cpp:class:`static_synapse <nest::static_synapse>` by default). Details depend on the connectivity rule. Parameters ---------- pre : NodeCollection (or array-like object) Presynaptic nodes, as object representing the IDs of the nodes post : NodeCollection (or array-like object) Postsynaptic nodes, as object representing the IDs of the nodes conn_spec : str or dict, optional Specifies connectivity rule, see below syn_spec : str or dict, optional Specifies synapse model, see below return_synapsecollection: bool Specifies whether or not we should return a :py:class:`.SynapseCollection` of pre and post connections Raises ------ kernel.NESTError Notes ----- It is possible to connect NumPy arrays of node IDs one-to-one by passing the arrays as `pre` and `post`, specifying `'one_to_one'` for `conn_spec`. In that case, the arrays may contain non-unique IDs. You may also specify weight, delay, and receptor type for each connection as NumPy arrays in the `syn_spec` dictionary. This feature is currently not available when MPI is used; trying to connect arrays with more than one MPI process will raise an error. If pre and post have spatial positions, a `mask` can be specified as a dictionary. The mask define which nodes are considered as potential targets for each source node. Connections with spatial nodes can also use `nest.spatial_distributions` as parameters, for instance for the probability `p`. **Connectivity specification (conn_spec)** Available rules and associated parameters:: - 'all_to_all' (default) - 'one_to_one' - 'fixed_indegree', 'indegree' - 'fixed_outdegree', 'outdegree' - 'fixed_total_number', 'N' - 'pairwise_bernoulli', 'p' - 'symmetric_pairwise_bernoulli', 'p' See :ref:`conn_rules` for more details, including example usage. **Synapse specification (syn_spec)** The synapse model and its properties can be given either as a string identifying a specific synapse model (default: :cpp:class:`static_synapse <nest::static_synapse>`) or as a dictionary specifying the synapse model and its parameters. Available keys in the synapse specification dictionary are:: - 'synapse_model' - 'weight' - 'delay' - 'receptor_type' - any parameters specific to the selected synapse model. See :ref:`synapse_spec` for details, including example usage. All parameters are optional and if not specified, the default values of the synapse model will be used. The key 'synapse_model' identifies the synapse model, this can be one of NEST's built-in synapse models or a user-defined model created via :py:func:`.CopyModel`. If `synapse_model` is not specified the default model :cpp:class:`static_synapse <nest::static_synapse>` will be used. Distributed parameters can be defined through NEST's different parametertypes. NEST has various random parameters, spatial parameters and distributions (only accesseable for nodes with spatial positions), logical expressions and mathematical expressions, which can be used to define node and connection parameters. To see all available parameters, see documentation defined in distributions, logic, math, random and spatial modules. See Also --------- :ref:`connection_management`
Connect `pre` nodes to `post` nodes.
[ "Connect", "pre", "nodes", "to", "post", "nodes", "." ]
def Connect(pre, post, conn_spec=None, syn_spec=None, return_synapsecollection=False): """ Connect `pre` nodes to `post` nodes. Nodes in `pre` and `post` are connected using the specified connectivity (`all-to-all` by default) and synapse type (:cpp:class:`static_synapse <nest::static_synapse>` by default). Details depend on the connectivity rule. Parameters ---------- pre : NodeCollection (or array-like object) Presynaptic nodes, as object representing the IDs of the nodes post : NodeCollection (or array-like object) Postsynaptic nodes, as object representing the IDs of the nodes conn_spec : str or dict, optional Specifies connectivity rule, see below syn_spec : str or dict, optional Specifies synapse model, see below return_synapsecollection: bool Specifies whether or not we should return a :py:class:`.SynapseCollection` of pre and post connections Raises ------ kernel.NESTError Notes ----- It is possible to connect NumPy arrays of node IDs one-to-one by passing the arrays as `pre` and `post`, specifying `'one_to_one'` for `conn_spec`. In that case, the arrays may contain non-unique IDs. You may also specify weight, delay, and receptor type for each connection as NumPy arrays in the `syn_spec` dictionary. This feature is currently not available when MPI is used; trying to connect arrays with more than one MPI process will raise an error. If pre and post have spatial positions, a `mask` can be specified as a dictionary. The mask define which nodes are considered as potential targets for each source node. Connections with spatial nodes can also use `nest.spatial_distributions` as parameters, for instance for the probability `p`. **Connectivity specification (conn_spec)** Available rules and associated parameters:: - 'all_to_all' (default) - 'one_to_one' - 'fixed_indegree', 'indegree' - 'fixed_outdegree', 'outdegree' - 'fixed_total_number', 'N' - 'pairwise_bernoulli', 'p' - 'symmetric_pairwise_bernoulli', 'p' See :ref:`conn_rules` for more details, including example usage. **Synapse specification (syn_spec)** The synapse model and its properties can be given either as a string identifying a specific synapse model (default: :cpp:class:`static_synapse <nest::static_synapse>`) or as a dictionary specifying the synapse model and its parameters. Available keys in the synapse specification dictionary are:: - 'synapse_model' - 'weight' - 'delay' - 'receptor_type' - any parameters specific to the selected synapse model. See :ref:`synapse_spec` for details, including example usage. All parameters are optional and if not specified, the default values of the synapse model will be used. The key 'synapse_model' identifies the synapse model, this can be one of NEST's built-in synapse models or a user-defined model created via :py:func:`.CopyModel`. If `synapse_model` is not specified the default model :cpp:class:`static_synapse <nest::static_synapse>` will be used. Distributed parameters can be defined through NEST's different parametertypes. NEST has various random parameters, spatial parameters and distributions (only accesseable for nodes with spatial positions), logical expressions and mathematical expressions, which can be used to define node and connection parameters. To see all available parameters, see documentation defined in distributions, logic, math, random and spatial modules. See Also --------- :ref:`connection_management` """ use_connect_arrays, pre, post = _process_input_nodes(pre, post, conn_spec) # Converting conn_spec to dict, without putting it on the SLI stack. processed_conn_spec = _process_conn_spec(conn_spec) # If syn_spec is given, its contents are checked, and if needed converted # to the right formats. processed_syn_spec = _process_syn_spec( syn_spec, processed_conn_spec, len(pre), len(post), use_connect_arrays) # If pre and post are arrays of node IDs, and conn_spec is unspecified, # the node IDs are connected one-to-one. if use_connect_arrays: if return_synapsecollection: raise ValueError("SynapseCollection cannot be returned when connecting two arrays of node IDs") if processed_syn_spec is None: raise ValueError("When connecting two arrays of node IDs, the synapse specification dictionary must " "be specified and contain at least the synapse model.") # In case of misspelling if "weights" in processed_syn_spec: raise ValueError("To specify weights, use 'weight' in syn_spec.") if "delays" in processed_syn_spec: raise ValueError("To specify delays, use 'delay' in syn_spec.") weights = numpy.array(processed_syn_spec['weight']) if 'weight' in processed_syn_spec else None delays = numpy.array(processed_syn_spec['delay']) if 'delay' in processed_syn_spec else None try: synapse_model = processed_syn_spec['synapse_model'] except KeyError: raise ValueError("When connecting two arrays of node IDs, the synapse specification dictionary must " "contain a synapse model.") # Split remaining syn_spec entries to key and value arrays reduced_processed_syn_spec = {k: processed_syn_spec[k] for k in set(processed_syn_spec.keys()).difference( set(('weight', 'delay', 'synapse_model')))} if len(reduced_processed_syn_spec) > 0: syn_param_keys = numpy.array(list(reduced_processed_syn_spec.keys()), dtype=numpy.string_) syn_param_values = numpy.zeros([len(reduced_processed_syn_spec), len(pre)]) for i, value in enumerate(reduced_processed_syn_spec.values()): syn_param_values[i] = value else: syn_param_keys = None syn_param_values = None connect_arrays(pre, post, weights, delays, synapse_model, syn_param_keys, syn_param_values) return sps(pre) sps(post) if not isinstance(pre, NodeCollection): raise TypeError("Not implemented, presynaptic nodes must be a NodeCollection") if not isinstance(post, NodeCollection): raise TypeError("Not implemented, postsynaptic nodes must be a NodeCollection") # In some cases we must connect with ConnectLayers instead. if _connect_layers_needed(processed_conn_spec, processed_syn_spec): # Check that pre and post are layers if pre.spatial is None: raise TypeError("Presynaptic NodeCollection must have spatial information") if post.spatial is None: raise TypeError("Presynaptic NodeCollection must have spatial information") # Create the projection dictionary spatial_projections = _process_spatial_projections( processed_conn_spec, processed_syn_spec) # Connect using ConnectLayers _connect_spatial(pre, post, spatial_projections) else: sps(processed_conn_spec) if processed_syn_spec is not None: sps(processed_syn_spec) sr('Connect') if return_synapsecollection: return GetConnections(pre, post)
[ "def", "Connect", "(", "pre", ",", "post", ",", "conn_spec", "=", "None", ",", "syn_spec", "=", "None", ",", "return_synapsecollection", "=", "False", ")", ":", "use_connect_arrays", ",", "pre", ",", "post", "=", "_process_input_nodes", "(", "pre", ",", "post", ",", "conn_spec", ")", "# Converting conn_spec to dict, without putting it on the SLI stack.", "processed_conn_spec", "=", "_process_conn_spec", "(", "conn_spec", ")", "# If syn_spec is given, its contents are checked, and if needed converted", "# to the right formats.", "processed_syn_spec", "=", "_process_syn_spec", "(", "syn_spec", ",", "processed_conn_spec", ",", "len", "(", "pre", ")", ",", "len", "(", "post", ")", ",", "use_connect_arrays", ")", "# If pre and post are arrays of node IDs, and conn_spec is unspecified,", "# the node IDs are connected one-to-one.", "if", "use_connect_arrays", ":", "if", "return_synapsecollection", ":", "raise", "ValueError", "(", "\"SynapseCollection cannot be returned when connecting two arrays of node IDs\"", ")", "if", "processed_syn_spec", "is", "None", ":", "raise", "ValueError", "(", "\"When connecting two arrays of node IDs, the synapse specification dictionary must \"", "\"be specified and contain at least the synapse model.\"", ")", "# In case of misspelling", "if", "\"weights\"", "in", "processed_syn_spec", ":", "raise", "ValueError", "(", "\"To specify weights, use 'weight' in syn_spec.\"", ")", "if", "\"delays\"", "in", "processed_syn_spec", ":", "raise", "ValueError", "(", "\"To specify delays, use 'delay' in syn_spec.\"", ")", "weights", "=", "numpy", ".", "array", "(", "processed_syn_spec", "[", "'weight'", "]", ")", "if", "'weight'", "in", "processed_syn_spec", "else", "None", "delays", "=", "numpy", ".", "array", "(", "processed_syn_spec", "[", "'delay'", "]", ")", "if", "'delay'", "in", "processed_syn_spec", "else", "None", "try", ":", "synapse_model", "=", "processed_syn_spec", "[", "'synapse_model'", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"When connecting two arrays of node IDs, the synapse specification dictionary must \"", "\"contain a synapse model.\"", ")", "# Split remaining syn_spec entries to key and value arrays", "reduced_processed_syn_spec", "=", "{", "k", ":", "processed_syn_spec", "[", "k", "]", "for", "k", "in", "set", "(", "processed_syn_spec", ".", "keys", "(", ")", ")", ".", "difference", "(", "set", "(", "(", "'weight'", ",", "'delay'", ",", "'synapse_model'", ")", ")", ")", "}", "if", "len", "(", "reduced_processed_syn_spec", ")", ">", "0", ":", "syn_param_keys", "=", "numpy", ".", "array", "(", "list", "(", "reduced_processed_syn_spec", ".", "keys", "(", ")", ")", ",", "dtype", "=", "numpy", ".", "string_", ")", "syn_param_values", "=", "numpy", ".", "zeros", "(", "[", "len", "(", "reduced_processed_syn_spec", ")", ",", "len", "(", "pre", ")", "]", ")", "for", "i", ",", "value", "in", "enumerate", "(", "reduced_processed_syn_spec", ".", "values", "(", ")", ")", ":", "syn_param_values", "[", "i", "]", "=", "value", "else", ":", "syn_param_keys", "=", "None", "syn_param_values", "=", "None", "connect_arrays", "(", "pre", ",", "post", ",", "weights", ",", "delays", ",", "synapse_model", ",", "syn_param_keys", ",", "syn_param_values", ")", "return", "sps", "(", "pre", ")", "sps", "(", "post", ")", "if", "not", "isinstance", "(", "pre", ",", "NodeCollection", ")", ":", "raise", "TypeError", "(", "\"Not implemented, presynaptic nodes must be a NodeCollection\"", ")", "if", "not", "isinstance", "(", "post", ",", "NodeCollection", ")", ":", "raise", "TypeError", "(", "\"Not implemented, postsynaptic nodes must be a NodeCollection\"", ")", "# In some cases we must connect with ConnectLayers instead.", "if", "_connect_layers_needed", "(", "processed_conn_spec", ",", "processed_syn_spec", ")", ":", "# Check that pre and post are layers", "if", "pre", ".", "spatial", "is", "None", ":", "raise", "TypeError", "(", "\"Presynaptic NodeCollection must have spatial information\"", ")", "if", "post", ".", "spatial", "is", "None", ":", "raise", "TypeError", "(", "\"Presynaptic NodeCollection must have spatial information\"", ")", "# Create the projection dictionary", "spatial_projections", "=", "_process_spatial_projections", "(", "processed_conn_spec", ",", "processed_syn_spec", ")", "# Connect using ConnectLayers", "_connect_spatial", "(", "pre", ",", "post", ",", "spatial_projections", ")", "else", ":", "sps", "(", "processed_conn_spec", ")", "if", "processed_syn_spec", "is", "not", "None", ":", "sps", "(", "processed_syn_spec", ")", "sr", "(", "'Connect'", ")", "if", "return_synapsecollection", ":", "return", "GetConnections", "(", "pre", ",", "post", ")" ]
https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/nest/lib/hl_api_connections.py#L116-L287
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/sql.py
python
SQLTable._query_iterator
( self, result, chunksize, columns, coerce_float=True, parse_dates=None )
Return generator through chunked result set.
Return generator through chunked result set.
[ "Return", "generator", "through", "chunked", "result", "set", "." ]
def _query_iterator( self, result, chunksize, columns, coerce_float=True, parse_dates=None ): """Return generator through chunked result set.""" while True: data = result.fetchmany(chunksize) if not data: break else: self.frame = DataFrame.from_records( data, columns=columns, coerce_float=coerce_float ) self._harmonize_columns(parse_dates=parse_dates) if self.index is not None: self.frame.set_index(self.index, inplace=True) yield self.frame
[ "def", "_query_iterator", "(", "self", ",", "result", ",", "chunksize", ",", "columns", ",", "coerce_float", "=", "True", ",", "parse_dates", "=", "None", ")", ":", "while", "True", ":", "data", "=", "result", ".", "fetchmany", "(", "chunksize", ")", "if", "not", "data", ":", "break", "else", ":", "self", ".", "frame", "=", "DataFrame", ".", "from_records", "(", "data", ",", "columns", "=", "columns", ",", "coerce_float", "=", "coerce_float", ")", "self", ".", "_harmonize_columns", "(", "parse_dates", "=", "parse_dates", ")", "if", "self", ".", "index", "is", "not", "None", ":", "self", ".", "frame", ".", "set_index", "(", "self", ".", "index", ",", "inplace", "=", "True", ")", "yield", "self", ".", "frame" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/sql.py#L757-L776
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
build/compare-mozconfig/compare-mozconfigs-wrapper.py
python
main
()
A wrapper script that calls compare-mozconfig.py based on the platform that the machine is building for
A wrapper script that calls compare-mozconfig.py based on the platform that the machine is building for
[ "A", "wrapper", "script", "that", "calls", "compare", "-", "mozconfig", ".", "py", "based", "on", "the", "platform", "that", "the", "machine", "is", "building", "for" ]
def main(): """ A wrapper script that calls compare-mozconfig.py based on the platform that the machine is building for""" platform = determine_platform() if platform is not None: python_exe = substs['PYTHON'] topsrcdir = substs['top_srcdir'] # construct paths and args for compare-mozconfig browser_dir = path.join(topsrcdir, 'browser') script_path = path.join(topsrcdir, 'build/compare-mozconfig/compare-mozconfigs.py') whitelist_path = path.join(browser_dir, 'config/mozconfigs/whitelist') beta_mozconfig_path = path.join(browser_dir, 'config/mozconfigs', platform, 'beta') release_mozconfig_path = path.join(browser_dir, 'config/mozconfigs', platform, 'release') nightly_mozconfig_path = path.join(browser_dir, 'config/mozconfigs', platform, 'nightly') log.info("Comparing beta against nightly mozconfigs") ret_code = subprocess.call([python_exe, script_path, '--whitelist', whitelist_path, '--no-download', platform + ',' + beta_mozconfig_path + ',' + nightly_mozconfig_path]) if ret_code > 0: return ret_code log.info("Comparing release against nightly mozconfigs") ret_code = subprocess.call([python_exe, script_path, '--whitelist', whitelist_path, '--no-download', platform + ',' + release_mozconfig_path + ',' + nightly_mozconfig_path]) return ret_code
[ "def", "main", "(", ")", ":", "platform", "=", "determine_platform", "(", ")", "if", "platform", "is", "not", "None", ":", "python_exe", "=", "substs", "[", "'PYTHON'", "]", "topsrcdir", "=", "substs", "[", "'top_srcdir'", "]", "# construct paths and args for compare-mozconfig", "browser_dir", "=", "path", ".", "join", "(", "topsrcdir", ",", "'browser'", ")", "script_path", "=", "path", ".", "join", "(", "topsrcdir", ",", "'build/compare-mozconfig/compare-mozconfigs.py'", ")", "whitelist_path", "=", "path", ".", "join", "(", "browser_dir", ",", "'config/mozconfigs/whitelist'", ")", "beta_mozconfig_path", "=", "path", ".", "join", "(", "browser_dir", ",", "'config/mozconfigs'", ",", "platform", ",", "'beta'", ")", "release_mozconfig_path", "=", "path", ".", "join", "(", "browser_dir", ",", "'config/mozconfigs'", ",", "platform", ",", "'release'", ")", "nightly_mozconfig_path", "=", "path", ".", "join", "(", "browser_dir", ",", "'config/mozconfigs'", ",", "platform", ",", "'nightly'", ")", "log", ".", "info", "(", "\"Comparing beta against nightly mozconfigs\"", ")", "ret_code", "=", "subprocess", ".", "call", "(", "[", "python_exe", ",", "script_path", ",", "'--whitelist'", ",", "whitelist_path", ",", "'--no-download'", ",", "platform", "+", "','", "+", "beta_mozconfig_path", "+", "','", "+", "nightly_mozconfig_path", "]", ")", "if", "ret_code", ">", "0", ":", "return", "ret_code", "log", ".", "info", "(", "\"Comparing release against nightly mozconfigs\"", ")", "ret_code", "=", "subprocess", ".", "call", "(", "[", "python_exe", ",", "script_path", ",", "'--whitelist'", ",", "whitelist_path", ",", "'--no-download'", ",", "platform", "+", "','", "+", "release_mozconfig_path", "+", "','", "+", "nightly_mozconfig_path", "]", ")", "return", "ret_code" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/build/compare-mozconfig/compare-mozconfigs-wrapper.py#L28-L60
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/configHandler.py
python
IdleConfParser.Get
(self, section, option, type=None, default=None, raw=False)
Get an option value for given section/option or return default. If type is specified, return as type.
Get an option value for given section/option or return default. If type is specified, return as type.
[ "Get", "an", "option", "value", "for", "given", "section", "/", "option", "or", "return", "default", ".", "If", "type", "is", "specified", "return", "as", "type", "." ]
def Get(self, section, option, type=None, default=None, raw=False): """ Get an option value for given section/option or return default. If type is specified, return as type. """ if not self.has_option(section, option): return default if type=='bool': return self.getboolean(section, option) elif type=='int': return self.getint(section, option) else: return self.get(section, option, raw=raw)
[ "def", "Get", "(", "self", ",", "section", ",", "option", ",", "type", "=", "None", ",", "default", "=", "None", ",", "raw", "=", "False", ")", ":", "if", "not", "self", ".", "has_option", "(", "section", ",", "option", ")", ":", "return", "default", "if", "type", "==", "'bool'", ":", "return", "self", ".", "getboolean", "(", "section", ",", "option", ")", "elif", "type", "==", "'int'", ":", "return", "self", ".", "getint", "(", "section", ",", "option", ")", "else", ":", "return", "self", ".", "get", "(", "section", ",", "option", ",", "raw", "=", "raw", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/configHandler.py#L42-L54
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/data_selectors/cyclic_data_selector_view.py
python
CyclicDataSelectorView.set_data_combo_box_label
(self, text: str)
Sets the label text next to the data selector combobox.
Sets the label text next to the data selector combobox.
[ "Sets", "the", "label", "text", "next", "to", "the", "data", "selector", "combobox", "." ]
def set_data_combo_box_label(self, text: str) -> None: """Sets the label text next to the data selector combobox.""" self.data_combo_box_label.setText(text)
[ "def", "set_data_combo_box_label", "(", "self", ",", "text", ":", "str", ")", "->", "None", ":", "self", ".", "data_combo_box_label", ".", "setText", "(", "text", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/data_selectors/cyclic_data_selector_view.py#L137-L139
bayandin/chromedriver
d40a2092b50f2fca817221eeb5ea093e0e642c10
log_replay/client_replay.py
python
Replayer.__init__
(self, logfile, server, chrome_binary, base_url=None)
Initialize the Replayer instance. Args: logfile: log file handle object to replay from. options: command-line options; see below. Needs at least options.chromedriver for the ChromeDriver binary. base_url: string, base of the url to replace in the logged urls (useful for when ports change). If any value is passed here, it overrides any base url passed in options.
Initialize the Replayer instance.
[ "Initialize", "the", "Replayer", "instance", "." ]
def __init__(self, logfile, server, chrome_binary, base_url=None): """Initialize the Replayer instance. Args: logfile: log file handle object to replay from. options: command-line options; see below. Needs at least options.chromedriver for the ChromeDriver binary. base_url: string, base of the url to replace in the logged urls (useful for when ports change). If any value is passed here, it overrides any base url passed in options. """ # TODO(cwinstanley) Add Android support and perhaps support for other # chromedriver command line options. self.executor = command_executor.CommandExecutor(server.GetUrl()) self.command_sequence = CommandSequence(logfile, base_url=base_url, chrome_binary=chrome_binary)
[ "def", "__init__", "(", "self", ",", "logfile", ",", "server", ",", "chrome_binary", ",", "base_url", "=", "None", ")", ":", "# TODO(cwinstanley) Add Android support and perhaps support for other", "# chromedriver command line options.", "self", ".", "executor", "=", "command_executor", ".", "CommandExecutor", "(", "server", ".", "GetUrl", "(", ")", ")", "self", ".", "command_sequence", "=", "CommandSequence", "(", "logfile", ",", "base_url", "=", "base_url", ",", "chrome_binary", "=", "chrome_binary", ")" ]
https://github.com/bayandin/chromedriver/blob/d40a2092b50f2fca817221eeb5ea093e0e642c10/log_replay/client_replay.py#L847-L864
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
samples/wxPIA_book/Chapter-14/grid_editor.py
python
UpCaseCellEditor.SetSize
(self, rect)
Called to position/size the edit control within the cell rectangle. If you don't fill the cell (the rect) then be sure to override PaintBackground and do something meaningful there.
Called to position/size the edit control within the cell rectangle. If you don't fill the cell (the rect) then be sure to override PaintBackground and do something meaningful there.
[ "Called", "to", "position", "/", "size", "the", "edit", "control", "within", "the", "cell", "rectangle", ".", "If", "you", "don", "t", "fill", "the", "cell", "(", "the", "rect", ")", "then", "be", "sure", "to", "override", "PaintBackground", "and", "do", "something", "meaningful", "there", "." ]
def SetSize(self, rect): """ Called to position/size the edit control within the cell rectangle. If you don't fill the cell (the rect) then be sure to override PaintBackground and do something meaningful there. """ self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2, wx.SIZE_ALLOW_MINUS_ONE)
[ "def", "SetSize", "(", "self", ",", "rect", ")", ":", "self", ".", "_tc", ".", "SetDimensions", "(", "rect", ".", "x", ",", "rect", ".", "y", ",", "rect", ".", "width", "+", "2", ",", "rect", ".", "height", "+", "2", ",", "wx", ".", "SIZE_ALLOW_MINUS_ONE", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/wxPIA_book/Chapter-14/grid_editor.py#L23-L30
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/android/loading/cloud/common/google_instance_helper.py
python
GoogleInstanceHelper.DeleteInstanceGroup
(self, tag)
return False
Deletes the instance group identified by tag. If instances are still running in this group, they are deleted as well.
Deletes the instance group identified by tag. If instances are still running in this group, they are deleted as well.
[ "Deletes", "the", "instance", "group", "identified", "by", "tag", ".", "If", "instances", "are", "still", "running", "in", "this", "group", "they", "are", "deleted", "as", "well", "." ]
def DeleteInstanceGroup(self, tag): """Deletes the instance group identified by tag. If instances are still running in this group, they are deleted as well. """ group_name = self._GetInstanceGroupName(tag) request = self._compute_api.instanceGroupManagers().delete( project=self._project, zone=self._zone, instanceGroupManager=group_name) (success, result) = self._ExecuteApiRequest(request) if success: return True if google_error_helper.GetErrorReason(result) == \ google_error_helper.REASON_NOT_FOUND: # The group does not exist, nothing to do. self._logger.warning('Instance group not found: ' + group_name) return True return False
[ "def", "DeleteInstanceGroup", "(", "self", ",", "tag", ")", ":", "group_name", "=", "self", ".", "_GetInstanceGroupName", "(", "tag", ")", "request", "=", "self", ".", "_compute_api", ".", "instanceGroupManagers", "(", ")", ".", "delete", "(", "project", "=", "self", ".", "_project", ",", "zone", "=", "self", ".", "_zone", ",", "instanceGroupManager", "=", "group_name", ")", "(", "success", ",", "result", ")", "=", "self", ".", "_ExecuteApiRequest", "(", "request", ")", "if", "success", ":", "return", "True", "if", "google_error_helper", ".", "GetErrorReason", "(", "result", ")", "==", "google_error_helper", ".", "REASON_NOT_FOUND", ":", "# The group does not exist, nothing to do.", "self", ".", "_logger", ".", "warning", "(", "'Instance group not found: '", "+", "group_name", ")", "return", "True", "return", "False" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/cloud/common/google_instance_helper.py#L162-L178
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/tempfile.py
python
mkdtemp
(suffix="", prefix=template, dir=None)
User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory. Arguments are as for mkstemp, except that the 'text' argument is not accepted. The directory is readable, writable, and searchable only by the creating user. Caller is responsible for deleting the directory when done with it.
User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory.
[ "User", "-", "callable", "function", "to", "create", "and", "return", "a", "unique", "temporary", "directory", ".", "The", "return", "value", "is", "the", "pathname", "of", "the", "directory", "." ]
def mkdtemp(suffix="", prefix=template, dir=None): """User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory. Arguments are as for mkstemp, except that the 'text' argument is not accepted. The directory is readable, writable, and searchable only by the creating user. Caller is responsible for deleting the directory when done with it. """ if dir is None: dir = gettempdir() names = _get_candidate_names() for seq in xrange(TMP_MAX): name = names.next() file = _os.path.join(dir, prefix + name + suffix) try: _os.mkdir(file, 0700) return file except OSError, e: if e.errno == _errno.EEXIST: continue # try again raise raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
[ "def", "mkdtemp", "(", "suffix", "=", "\"\"", ",", "prefix", "=", "template", ",", "dir", "=", "None", ")", ":", "if", "dir", "is", "None", ":", "dir", "=", "gettempdir", "(", ")", "names", "=", "_get_candidate_names", "(", ")", "for", "seq", "in", "xrange", "(", "TMP_MAX", ")", ":", "name", "=", "names", ".", "next", "(", ")", "file", "=", "_os", ".", "path", ".", "join", "(", "dir", ",", "prefix", "+", "name", "+", "suffix", ")", "try", ":", "_os", ".", "mkdir", "(", "file", ",", "0700", ")", "return", "file", "except", "OSError", ",", "e", ":", "if", "e", ".", "errno", "==", "_errno", ".", "EEXIST", ":", "continue", "# try again", "raise", "raise", "IOError", ",", "(", "_errno", ".", "EEXIST", ",", "\"No usable temporary directory name found\"", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/tempfile.py#L307-L336
ivansafrin/Polycode
37a40fefe194ec7f6e9d1257f3bb3517b0a168bc
Bindings/Scripts/create_lua_library/zipfile.py
python
_ZipDecrypter.__call__
(self, c)
return c
Decrypt a single character.
Decrypt a single character.
[ "Decrypt", "a", "single", "character", "." ]
def __call__(self, c): """Decrypt a single character.""" c = ord(c) k = self.key2 | 2 c = c ^ (((k * (k^1)) >> 8) & 255) c = chr(c) self._UpdateKeys(c) return c
[ "def", "__call__", "(", "self", ",", "c", ")", ":", "c", "=", "ord", "(", "c", ")", "k", "=", "self", ".", "key2", "|", "2", "c", "=", "c", "^", "(", "(", "(", "k", "*", "(", "k", "^", "1", ")", ")", ">>", "8", ")", "&", "255", ")", "c", "=", "chr", "(", "c", ")", "self", ".", "_UpdateKeys", "(", "c", ")", "return", "c" ]
https://github.com/ivansafrin/Polycode/blob/37a40fefe194ec7f6e9d1257f3bb3517b0a168bc/Bindings/Scripts/create_lua_library/zipfile.py#L455-L462
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/html5lib-python/html5lib/treebuilders/etree_lxml.py
python
TreeBuilder.insertRoot
(self, token)
Create the document root
Create the document root
[ "Create", "the", "document", "root" ]
def insertRoot(self, token): """Create the document root""" # Because of the way libxml2 works, it doesn't seem to be possible to # alter information like the doctype after the tree has been parsed. # Therefore we need to use the built-in parser to create our iniial # tree, after which we can add elements like normal docStr = "" if self.doctype: assert self.doctype.name docStr += "<!DOCTYPE %s" % self.doctype.name if (self.doctype.publicId is not None or self.doctype.systemId is not None): docStr += (' PUBLIC "%s" ' % (self.infosetFilter.coercePubid(self.doctype.publicId or ""))) if self.doctype.systemId: sysid = self.doctype.systemId if sysid.find("'") >= 0 and sysid.find('"') >= 0: warnings.warn("DOCTYPE system cannot contain single and double quotes", DataLossWarning) sysid = sysid.replace("'", 'U00027') if sysid.find("'") >= 0: docStr += '"%s"' % sysid else: docStr += "'%s'" % sysid else: docStr += "''" docStr += ">" if self.doctype.name != token["name"]: warnings.warn("lxml cannot represent doctype with a different name to the root element", DataLossWarning) docStr += "<THIS_SHOULD_NEVER_APPEAR_PUBLICLY/>" root = etree.fromstring(docStr) # Append the initial comments: for comment_token in self.initial_comments: root.addprevious(etree.Comment(comment_token["data"])) # Create the root document and add the ElementTree to it self.document = self.documentClass() self.document._elementTree = root.getroottree() # Give the root element the right name name = token["name"] namespace = token.get("namespace", self.defaultNamespace) if namespace is None: etree_tag = name else: etree_tag = "{%s}%s" % (namespace, name) root.tag = etree_tag # Add the root element to the internal child/open data structures root_element = self.elementClass(name, namespace) root_element._element = root self.document._childNodes.append(root_element) self.openElements.append(root_element) # Reset to the default insert comment function self.insertComment = self.insertCommentMain
[ "def", "insertRoot", "(", "self", ",", "token", ")", ":", "# Because of the way libxml2 works, it doesn't seem to be possible to", "# alter information like the doctype after the tree has been parsed.", "# Therefore we need to use the built-in parser to create our iniial", "# tree, after which we can add elements like normal", "docStr", "=", "\"\"", "if", "self", ".", "doctype", ":", "assert", "self", ".", "doctype", ".", "name", "docStr", "+=", "\"<!DOCTYPE %s\"", "%", "self", ".", "doctype", ".", "name", "if", "(", "self", ".", "doctype", ".", "publicId", "is", "not", "None", "or", "self", ".", "doctype", ".", "systemId", "is", "not", "None", ")", ":", "docStr", "+=", "(", "' PUBLIC \"%s\" '", "%", "(", "self", ".", "infosetFilter", ".", "coercePubid", "(", "self", ".", "doctype", ".", "publicId", "or", "\"\"", ")", ")", ")", "if", "self", ".", "doctype", ".", "systemId", ":", "sysid", "=", "self", ".", "doctype", ".", "systemId", "if", "sysid", ".", "find", "(", "\"'\"", ")", ">=", "0", "and", "sysid", ".", "find", "(", "'\"'", ")", ">=", "0", ":", "warnings", ".", "warn", "(", "\"DOCTYPE system cannot contain single and double quotes\"", ",", "DataLossWarning", ")", "sysid", "=", "sysid", ".", "replace", "(", "\"'\"", ",", "'U00027'", ")", "if", "sysid", ".", "find", "(", "\"'\"", ")", ">=", "0", ":", "docStr", "+=", "'\"%s\"'", "%", "sysid", "else", ":", "docStr", "+=", "\"'%s'\"", "%", "sysid", "else", ":", "docStr", "+=", "\"''\"", "docStr", "+=", "\">\"", "if", "self", ".", "doctype", ".", "name", "!=", "token", "[", "\"name\"", "]", ":", "warnings", ".", "warn", "(", "\"lxml cannot represent doctype with a different name to the root element\"", ",", "DataLossWarning", ")", "docStr", "+=", "\"<THIS_SHOULD_NEVER_APPEAR_PUBLICLY/>\"", "root", "=", "etree", ".", "fromstring", "(", "docStr", ")", "# Append the initial comments:", "for", "comment_token", "in", "self", ".", "initial_comments", ":", "root", ".", "addprevious", "(", "etree", ".", "Comment", "(", "comment_token", "[", "\"data\"", "]", ")", ")", "# Create the root document and add the ElementTree to it", "self", ".", "document", "=", "self", ".", "documentClass", "(", ")", "self", ".", "document", ".", "_elementTree", "=", "root", ".", "getroottree", "(", ")", "# Give the root element the right name", "name", "=", "token", "[", "\"name\"", "]", "namespace", "=", "token", ".", "get", "(", "\"namespace\"", ",", "self", ".", "defaultNamespace", ")", "if", "namespace", "is", "None", ":", "etree_tag", "=", "name", "else", ":", "etree_tag", "=", "\"{%s}%s\"", "%", "(", "namespace", ",", "name", ")", "root", ".", "tag", "=", "etree_tag", "# Add the root element to the internal child/open data structures", "root_element", "=", "self", ".", "elementClass", "(", "name", ",", "namespace", ")", "root_element", ".", "_element", "=", "root", "self", ".", "document", ".", "_childNodes", ".", "append", "(", "root_element", ")", "self", ".", "openElements", ".", "append", "(", "root_element", ")", "# Reset to the default insert comment function", "self", ".", "insertComment", "=", "self", ".", "insertCommentMain" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/html5lib-python/html5lib/treebuilders/etree_lxml.py#L314-L369
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/signaltools.py
python
correlate
(in1, in2, mode='full', method='auto')
r""" Cross-correlate two N-dimensional arrays. Cross-correlate `in1` and `in2`, with the output size determined by the `mode` argument. Parameters ---------- in1 : array_like First input. in2 : array_like Second input. Should have the same number of dimensions as `in1`. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear cross-correlation of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. In 'valid' mode, either `in1` or `in2` must be at least as large as the other in every dimension. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. method : str {'auto', 'direct', 'fft'}, optional A string indicating which method to use to calculate the correlation. ``direct`` The correlation is determined directly from sums, the definition of correlation. ``fft`` The Fast Fourier Transform is used to perform the correlation more quickly (only available for numerical arrays.) ``auto`` Automatically chooses direct or Fourier method based on an estimate of which is faster (default). See `convolve` Notes for more detail. .. versionadded:: 0.19.0 Returns ------- correlate : array An N-dimensional array containing a subset of the discrete linear cross-correlation of `in1` with `in2`. See Also -------- choose_conv_method : contains more documentation on `method`. Notes ----- The correlation z of two d-dimensional arrays x and y is defined as:: z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...]) This way, if x and y are 1-D arrays and ``z = correlate(x, y, 'full')`` then .. math:: z[k] = (x * y)(k - N + 1) = \sum_{l=0}^{||x||-1}x_l y_{l-k+N-1}^{*} for :math:`k = 0, 1, ..., ||x|| + ||y|| - 2` where :math:`||x||` is the length of ``x``, :math:`N = \max(||x||,||y||)`, and :math:`y_m` is 0 when m is outside the range of y. ``method='fft'`` only works for numerical arrays as it relies on `fftconvolve`. In certain cases (i.e., arrays of objects or when rounding integers can lose precision), ``method='direct'`` is always used. Examples -------- Implement a matched filter using cross-correlation, to recover a signal that has passed through a noisy channel. >>> from scipy import signal >>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128) >>> sig_noise = sig + np.random.randn(len(sig)) >>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128 >>> import matplotlib.pyplot as plt >>> clock = np.arange(64, len(sig), 128) >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True) >>> ax_orig.plot(sig) >>> ax_orig.plot(clock, sig[clock], 'ro') >>> ax_orig.set_title('Original signal') >>> ax_noise.plot(sig_noise) >>> ax_noise.set_title('Signal with noise') >>> ax_corr.plot(corr) >>> ax_corr.plot(clock, corr[clock], 'ro') >>> ax_corr.axhline(0.5, ls=':') >>> ax_corr.set_title('Cross-correlated with rectangular pulse') >>> ax_orig.margins(0, 0.1) >>> fig.tight_layout() >>> fig.show()
r""" Cross-correlate two N-dimensional arrays.
[ "r", "Cross", "-", "correlate", "two", "N", "-", "dimensional", "arrays", "." ]
def correlate(in1, in2, mode='full', method='auto'): r""" Cross-correlate two N-dimensional arrays. Cross-correlate `in1` and `in2`, with the output size determined by the `mode` argument. Parameters ---------- in1 : array_like First input. in2 : array_like Second input. Should have the same number of dimensions as `in1`. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear cross-correlation of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. In 'valid' mode, either `in1` or `in2` must be at least as large as the other in every dimension. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. method : str {'auto', 'direct', 'fft'}, optional A string indicating which method to use to calculate the correlation. ``direct`` The correlation is determined directly from sums, the definition of correlation. ``fft`` The Fast Fourier Transform is used to perform the correlation more quickly (only available for numerical arrays.) ``auto`` Automatically chooses direct or Fourier method based on an estimate of which is faster (default). See `convolve` Notes for more detail. .. versionadded:: 0.19.0 Returns ------- correlate : array An N-dimensional array containing a subset of the discrete linear cross-correlation of `in1` with `in2`. See Also -------- choose_conv_method : contains more documentation on `method`. Notes ----- The correlation z of two d-dimensional arrays x and y is defined as:: z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...]) This way, if x and y are 1-D arrays and ``z = correlate(x, y, 'full')`` then .. math:: z[k] = (x * y)(k - N + 1) = \sum_{l=0}^{||x||-1}x_l y_{l-k+N-1}^{*} for :math:`k = 0, 1, ..., ||x|| + ||y|| - 2` where :math:`||x||` is the length of ``x``, :math:`N = \max(||x||,||y||)`, and :math:`y_m` is 0 when m is outside the range of y. ``method='fft'`` only works for numerical arrays as it relies on `fftconvolve`. In certain cases (i.e., arrays of objects or when rounding integers can lose precision), ``method='direct'`` is always used. Examples -------- Implement a matched filter using cross-correlation, to recover a signal that has passed through a noisy channel. >>> from scipy import signal >>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128) >>> sig_noise = sig + np.random.randn(len(sig)) >>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128 >>> import matplotlib.pyplot as plt >>> clock = np.arange(64, len(sig), 128) >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True) >>> ax_orig.plot(sig) >>> ax_orig.plot(clock, sig[clock], 'ro') >>> ax_orig.set_title('Original signal') >>> ax_noise.plot(sig_noise) >>> ax_noise.set_title('Signal with noise') >>> ax_corr.plot(corr) >>> ax_corr.plot(clock, corr[clock], 'ro') >>> ax_corr.axhline(0.5, ls=':') >>> ax_corr.set_title('Cross-correlated with rectangular pulse') >>> ax_orig.margins(0, 0.1) >>> fig.tight_layout() >>> fig.show() """ in1 = asarray(in1) in2 = asarray(in2) if in1.ndim == in2.ndim == 0: return in1 * in2.conj() elif in1.ndim != in2.ndim: raise ValueError("in1 and in2 should have the same dimensionality") # Don't use _valfrommode, since correlate should not accept numeric modes try: val = _modedict[mode] except KeyError: raise ValueError("Acceptable mode flags are 'valid'," " 'same', or 'full'.") # this either calls fftconvolve or this function with method=='direct' if method in ('fft', 'auto'): return convolve(in1, _reverse_and_conj(in2), mode, method) elif method == 'direct': # fastpath to faster numpy.correlate for 1d inputs when possible if _np_conv_ok(in1, in2, mode): return np.correlate(in1, in2, mode) # _correlateND is far slower when in2.size > in1.size, so swap them # and then undo the effect afterward if mode == 'full'. Also, it fails # with 'valid' mode if in2 is larger than in1, so swap those, too. # Don't swap inputs for 'same' mode, since shape of in1 matters. swapped_inputs = ((mode == 'full') and (in2.size > in1.size) or _inputs_swap_needed(mode, in1.shape, in2.shape)) if swapped_inputs: in1, in2 = in2, in1 if mode == 'valid': ps = [i - j + 1 for i, j in zip(in1.shape, in2.shape)] out = np.empty(ps, in1.dtype) z = sigtools._correlateND(in1, in2, out, val) else: ps = [i + j - 1 for i, j in zip(in1.shape, in2.shape)] # zero pad input in1zpadded = np.zeros(ps, in1.dtype) sc = tuple(slice(0, i) for i in in1.shape) in1zpadded[sc] = in1.copy() if mode == 'full': out = np.empty(ps, in1.dtype) elif mode == 'same': out = np.empty(in1.shape, in1.dtype) z = sigtools._correlateND(in1zpadded, in2, out, val) if swapped_inputs: # Reverse and conjugate to undo the effect of swapping inputs z = _reverse_and_conj(z) return z else: raise ValueError("Acceptable method flags are 'auto'," " 'direct', or 'fft'.")
[ "def", "correlate", "(", "in1", ",", "in2", ",", "mode", "=", "'full'", ",", "method", "=", "'auto'", ")", ":", "in1", "=", "asarray", "(", "in1", ")", "in2", "=", "asarray", "(", "in2", ")", "if", "in1", ".", "ndim", "==", "in2", ".", "ndim", "==", "0", ":", "return", "in1", "*", "in2", ".", "conj", "(", ")", "elif", "in1", ".", "ndim", "!=", "in2", ".", "ndim", ":", "raise", "ValueError", "(", "\"in1 and in2 should have the same dimensionality\"", ")", "# Don't use _valfrommode, since correlate should not accept numeric modes", "try", ":", "val", "=", "_modedict", "[", "mode", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Acceptable mode flags are 'valid',\"", "\" 'same', or 'full'.\"", ")", "# this either calls fftconvolve or this function with method=='direct'", "if", "method", "in", "(", "'fft'", ",", "'auto'", ")", ":", "return", "convolve", "(", "in1", ",", "_reverse_and_conj", "(", "in2", ")", ",", "mode", ",", "method", ")", "elif", "method", "==", "'direct'", ":", "# fastpath to faster numpy.correlate for 1d inputs when possible", "if", "_np_conv_ok", "(", "in1", ",", "in2", ",", "mode", ")", ":", "return", "np", ".", "correlate", "(", "in1", ",", "in2", ",", "mode", ")", "# _correlateND is far slower when in2.size > in1.size, so swap them", "# and then undo the effect afterward if mode == 'full'. Also, it fails", "# with 'valid' mode if in2 is larger than in1, so swap those, too.", "# Don't swap inputs for 'same' mode, since shape of in1 matters.", "swapped_inputs", "=", "(", "(", "mode", "==", "'full'", ")", "and", "(", "in2", ".", "size", ">", "in1", ".", "size", ")", "or", "_inputs_swap_needed", "(", "mode", ",", "in1", ".", "shape", ",", "in2", ".", "shape", ")", ")", "if", "swapped_inputs", ":", "in1", ",", "in2", "=", "in2", ",", "in1", "if", "mode", "==", "'valid'", ":", "ps", "=", "[", "i", "-", "j", "+", "1", "for", "i", ",", "j", "in", "zip", "(", "in1", ".", "shape", ",", "in2", ".", "shape", ")", "]", "out", "=", "np", ".", "empty", "(", "ps", ",", "in1", ".", "dtype", ")", "z", "=", "sigtools", ".", "_correlateND", "(", "in1", ",", "in2", ",", "out", ",", "val", ")", "else", ":", "ps", "=", "[", "i", "+", "j", "-", "1", "for", "i", ",", "j", "in", "zip", "(", "in1", ".", "shape", ",", "in2", ".", "shape", ")", "]", "# zero pad input", "in1zpadded", "=", "np", ".", "zeros", "(", "ps", ",", "in1", ".", "dtype", ")", "sc", "=", "tuple", "(", "slice", "(", "0", ",", "i", ")", "for", "i", "in", "in1", ".", "shape", ")", "in1zpadded", "[", "sc", "]", "=", "in1", ".", "copy", "(", ")", "if", "mode", "==", "'full'", ":", "out", "=", "np", ".", "empty", "(", "ps", ",", "in1", ".", "dtype", ")", "elif", "mode", "==", "'same'", ":", "out", "=", "np", ".", "empty", "(", "in1", ".", "shape", ",", "in1", ".", "dtype", ")", "z", "=", "sigtools", ".", "_correlateND", "(", "in1zpadded", ",", "in2", ",", "out", ",", "val", ")", "if", "swapped_inputs", ":", "# Reverse and conjugate to undo the effect of swapping inputs", "z", "=", "_reverse_and_conj", "(", "z", ")", "return", "z", "else", ":", "raise", "ValueError", "(", "\"Acceptable method flags are 'auto',\"", "\" 'direct', or 'fft'.\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/signaltools.py#L105-L269
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/markdown/extensions/smart_strong.py
python
SmartEmphasisExtension.extendMarkdown
(self, md, md_globals)
Modify inline patterns.
Modify inline patterns.
[ "Modify", "inline", "patterns", "." ]
def extendMarkdown(self, md, md_globals): """ Modify inline patterns. """ md.inlinePatterns['strong'] = SimpleTagPattern(STRONG_RE, 'strong') md.inlinePatterns.add('strong2', SimpleTagPattern(SMART_STRONG_RE, 'strong'), '>emphasis2')
[ "def", "extendMarkdown", "(", "self", ",", "md", ",", "md_globals", ")", ":", "md", ".", "inlinePatterns", "[", "'strong'", "]", "=", "SimpleTagPattern", "(", "STRONG_RE", ",", "'strong'", ")", "md", ".", "inlinePatterns", ".", "add", "(", "'strong2'", ",", "SimpleTagPattern", "(", "SMART_STRONG_RE", ",", "'strong'", ")", ",", "'>emphasis2'", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/markdown/extensions/smart_strong.py#L68-L71
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/win/split_link/install_split_link.py
python
EscapeForCommandLineAndCString
(path)
return path.replace('\\', '\\\\').replace('"', '\\"')
Quoted sufficiently to be passed on the compile command line as a define to be turned into a string in the target C program.
Quoted sufficiently to be passed on the compile command line as a define to be turned into a string in the target C program.
[ "Quoted", "sufficiently", "to", "be", "passed", "on", "the", "compile", "command", "line", "as", "a", "define", "to", "be", "turned", "into", "a", "string", "in", "the", "target", "C", "program", "." ]
def EscapeForCommandLineAndCString(path): """Quoted sufficiently to be passed on the compile command line as a define to be turned into a string in the target C program.""" path = '"' + path + '"' return path.replace('\\', '\\\\').replace('"', '\\"')
[ "def", "EscapeForCommandLineAndCString", "(", "path", ")", ":", "path", "=", "'\"'", "+", "path", "+", "'\"'", "return", "path", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/win/split_link/install_split_link.py#L35-L39
Ewenwan/MVision
97b394dfa48cb21c82cd003b1a952745e413a17f
CNN/MobileNet/MobileNet_v1_ssd_caffe/ssd_detect.py
python
parse_args
()
return parser.parse_args()
parse args
parse args
[ "parse", "args" ]
def parse_args(): '''parse args''' parser = argparse.ArgumentParser() parser.add_argument('--gpu_id', type=int, default=1, help='gpu id') parser.add_argument('--labelmap_file', default='labelmap_voc.prototxt') parser.add_argument('--model_def', default='ssd_33_deploy.prototxt') parser.add_argument('--image_resize', default=300, type=int) parser.add_argument('--model_weights', default='models/ssd_33_iter_50000.caffemodel') #parser.add_argument('--image_file', default='fish-bike.jpg') #parser.add_argument('--image_file', default='dog.jpg') parser.add_argument('--image_file', default='person.jpg') return parser.parse_args()
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'--gpu_id'", ",", "type", "=", "int", ",", "default", "=", "1", ",", "help", "=", "'gpu id'", ")", "parser", ".", "add_argument", "(", "'--labelmap_file'", ",", "default", "=", "'labelmap_voc.prototxt'", ")", "parser", ".", "add_argument", "(", "'--model_def'", ",", "default", "=", "'ssd_33_deploy.prototxt'", ")", "parser", ".", "add_argument", "(", "'--image_resize'", ",", "default", "=", "300", ",", "type", "=", "int", ")", "parser", ".", "add_argument", "(", "'--model_weights'", ",", "default", "=", "'models/ssd_33_iter_50000.caffemodel'", ")", "#parser.add_argument('--image_file', default='fish-bike.jpg')", "#parser.add_argument('--image_file', default='dog.jpg')", "parser", ".", "add_argument", "(", "'--image_file'", ",", "default", "=", "'person.jpg'", ")", "return", "parser", ".", "parse_args", "(", ")" ]
https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/CNN/MobileNet/MobileNet_v1_ssd_caffe/ssd_detect.py#L152-L166
martinmoene/expected-lite
6284387cb117ea78d973fb5b1cbff1651a8d5d9a
script/create-vcpkg.py
python
createPortfile
( args )
Create vcpkg portfile
Create vcpkg portfile
[ "Create", "vcpkg", "portfile" ]
def createPortfile( args ): """Create vcpkg portfile""" output = tpl_vcpkg_portfile.format( optpfx=cfg_cmake_optpfx, usr=args.user, prj=args.project, ref=to_ref(args.version), sha=args.sha, lic=cfg_license ) if args.verbose: print( "Creating portfile '{f}':".format( f=portfile_path( args ) ) ) if args.verbose > 1: print( output ) os.makedirs( os.path.dirname( portfile_path( args ) ), exist_ok=True ) with open( portfile_path( args ), 'w') as f: print( output, file=f )
[ "def", "createPortfile", "(", "args", ")", ":", "output", "=", "tpl_vcpkg_portfile", ".", "format", "(", "optpfx", "=", "cfg_cmake_optpfx", ",", "usr", "=", "args", ".", "user", ",", "prj", "=", "args", ".", "project", ",", "ref", "=", "to_ref", "(", "args", ".", "version", ")", ",", "sha", "=", "args", ".", "sha", ",", "lic", "=", "cfg_license", ")", "if", "args", ".", "verbose", ":", "print", "(", "\"Creating portfile '{f}':\"", ".", "format", "(", "f", "=", "portfile_path", "(", "args", ")", ")", ")", "if", "args", ".", "verbose", ">", "1", ":", "print", "(", "output", ")", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "portfile_path", "(", "args", ")", ")", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "portfile_path", "(", "args", ")", ",", "'w'", ")", "as", "f", ":", "print", "(", "output", ",", "file", "=", "f", ")" ]
https://github.com/martinmoene/expected-lite/blob/6284387cb117ea78d973fb5b1cbff1651a8d5d9a/script/create-vcpkg.py#L134-L144
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/xcodeproj_file.py
python
XCConfigurationList.HasBuildSetting
(self, key)
return 1
Determines the state of a build setting in all XCBuildConfiguration child objects. If all child objects have key in their build settings, and the value is the same in all child objects, returns 1. If no child objects have the key in their build settings, returns 0. If some, but not all, child objects have the key in their build settings, or if any children have different values for the key, returns -1.
Determines the state of a build setting in all XCBuildConfiguration child objects.
[ "Determines", "the", "state", "of", "a", "build", "setting", "in", "all", "XCBuildConfiguration", "child", "objects", "." ]
def HasBuildSetting(self, key): """Determines the state of a build setting in all XCBuildConfiguration child objects. If all child objects have key in their build settings, and the value is the same in all child objects, returns 1. If no child objects have the key in their build settings, returns 0. If some, but not all, child objects have the key in their build settings, or if any children have different values for the key, returns -1. """ has = None value = None for configuration in self._properties['buildConfigurations']: configuration_has = configuration.HasBuildSetting(key) if has is None: has = configuration_has elif has != configuration_has: return -1 if configuration_has: configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value elif value != configuration_value: return -1 if not has: return 0 return 1
[ "def", "HasBuildSetting", "(", "self", ",", "key", ")", ":", "has", "=", "None", "value", "=", "None", "for", "configuration", "in", "self", ".", "_properties", "[", "'buildConfigurations'", "]", ":", "configuration_has", "=", "configuration", ".", "HasBuildSetting", "(", "key", ")", "if", "has", "is", "None", ":", "has", "=", "configuration_has", "elif", "has", "!=", "configuration_has", ":", "return", "-", "1", "if", "configuration_has", ":", "configuration_value", "=", "configuration", ".", "GetBuildSetting", "(", "key", ")", "if", "value", "is", "None", ":", "value", "=", "configuration_value", "elif", "value", "!=", "configuration_value", ":", "return", "-", "1", "if", "not", "has", ":", "return", "0", "return", "1" ]
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/xcodeproj_file.py#L1567-L1599
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/indentation.py
python
IndentationRules._AllFunctionPropertyAssignTokens
(self, start_token, end_token)
return True
Checks if tokens are (likely) a valid function property assignment. Args: start_token: Start of the token range. end_token: End of the token range. Returns: True if all tokens between start_token and end_token are legal tokens within a function declaration and assignment into a property.
Checks if tokens are (likely) a valid function property assignment.
[ "Checks", "if", "tokens", "are", "(", "likely", ")", "a", "valid", "function", "property", "assignment", "." ]
def _AllFunctionPropertyAssignTokens(self, start_token, end_token): """Checks if tokens are (likely) a valid function property assignment. Args: start_token: Start of the token range. end_token: End of the token range. Returns: True if all tokens between start_token and end_token are legal tokens within a function declaration and assignment into a property. """ for token in tokenutil.GetTokenRange(start_token, end_token): fn_decl_tokens = (Type.FUNCTION_DECLARATION, Type.PARAMETERS, Type.START_PARAMETERS, Type.END_PARAMETERS, Type.END_PAREN) if (token.type not in fn_decl_tokens and token.IsCode() and not tokenutil.IsIdentifierOrDot(token) and not token.IsAssignment() and not (token.type == Type.OPERATOR and token.string == ',')): return False return True
[ "def", "_AllFunctionPropertyAssignTokens", "(", "self", ",", "start_token", ",", "end_token", ")", ":", "for", "token", "in", "tokenutil", ".", "GetTokenRange", "(", "start_token", ",", "end_token", ")", ":", "fn_decl_tokens", "=", "(", "Type", ".", "FUNCTION_DECLARATION", ",", "Type", ".", "PARAMETERS", ",", "Type", ".", "START_PARAMETERS", ",", "Type", ".", "END_PARAMETERS", ",", "Type", ".", "END_PAREN", ")", "if", "(", "token", ".", "type", "not", "in", "fn_decl_tokens", "and", "token", ".", "IsCode", "(", ")", "and", "not", "tokenutil", ".", "IsIdentifierOrDot", "(", "token", ")", "and", "not", "token", ".", "IsAssignment", "(", ")", "and", "not", "(", "token", ".", "type", "==", "Type", ".", "OPERATOR", "and", "token", ".", "string", "==", "','", ")", ")", ":", "return", "False", "return", "True" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/indentation.py#L459-L482
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
ctpx/ctp3/ctptd.py
python
CtpTd.onErrRtnFutureToBankByFuture
(self, ReqTransferField, RspInfoField)
期货发起期货资金转银行错误回报
期货发起期货资金转银行错误回报
[ "期货发起期货资金转银行错误回报" ]
def onErrRtnFutureToBankByFuture(self, ReqTransferField, RspInfoField): """期货发起期货资金转银行错误回报""" pass
[ "def", "onErrRtnFutureToBankByFuture", "(", "self", ",", "ReqTransferField", ",", "RspInfoField", ")", ":", "pass" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/ctpx/ctp3/ctptd.py#L499-L501
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/array_ops.py
python
DynamicShape.__init__
(self)
init Shape
init Shape
[ "init", "Shape" ]
def __init__(self): """init Shape""" self.init_prim_io_names(inputs=['tensor'], outputs=['output']) self.add_prim_attr('is_dynamic_shape', True)
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "init_prim_io_names", "(", "inputs", "=", "[", "'tensor'", "]", ",", "outputs", "=", "[", "'output'", "]", ")", "self", ".", "add_prim_attr", "(", "'is_dynamic_shape'", ",", "True", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/array_ops.py#L671-L674
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/eager/function.py
python
_GraphModeFunction._build_call_outputs
(self, func_outputs, result)
return tuple(outputs) if type(func_outputs) is tuple else outputs
Maps the fdef output list to actual output structure. Args: func_outputs: The outputs originally defined by the graph function. It could potentially be a nested structure. result: Output lists defined by FunctionDef. Returns: The actual call output.
Maps the fdef output list to actual output structure.
[ "Maps", "the", "fdef", "output", "list", "to", "actual", "output", "structure", "." ]
def _build_call_outputs(self, func_outputs, result): """Maps the fdef output list to actual output structure. Args: func_outputs: The outputs originally defined by the graph function. It could potentially be a nested structure. result: Output lists defined by FunctionDef. Returns: The actual call output. """ if self._func_outputs is None: return None if isinstance(self._func_outputs, ops.Tensor): return result[0] outputs = [] for o in func_outputs: vo = o if isinstance(vo, ops.Tensor): outputs.append(result[self._returns_to_fedf_outputs[id(vo)]]) elif type(vo) in (tuple, list): outputs.append(self._build_call_outputs(o, result)) else: outputs.append(o) return tuple(outputs) if type(func_outputs) is tuple else outputs
[ "def", "_build_call_outputs", "(", "self", ",", "func_outputs", ",", "result", ")", ":", "if", "self", ".", "_func_outputs", "is", "None", ":", "return", "None", "if", "isinstance", "(", "self", ".", "_func_outputs", ",", "ops", ".", "Tensor", ")", ":", "return", "result", "[", "0", "]", "outputs", "=", "[", "]", "for", "o", "in", "func_outputs", ":", "vo", "=", "o", "if", "isinstance", "(", "vo", ",", "ops", ".", "Tensor", ")", ":", "outputs", ".", "append", "(", "result", "[", "self", ".", "_returns_to_fedf_outputs", "[", "id", "(", "vo", ")", "]", "]", ")", "elif", "type", "(", "vo", ")", "in", "(", "tuple", ",", "list", ")", ":", "outputs", ".", "append", "(", "self", ".", "_build_call_outputs", "(", "o", ",", "result", ")", ")", "else", ":", "outputs", ".", "append", "(", "o", ")", "return", "tuple", "(", "outputs", ")", "if", "type", "(", "func_outputs", ")", "is", "tuple", "else", "outputs" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/eager/function.py#L376-L401
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGridInterface.BeginAddChildren
(*args, **kwargs)
return _propgrid.PropertyGridInterface_BeginAddChildren(*args, **kwargs)
BeginAddChildren(self, PGPropArg id)
BeginAddChildren(self, PGPropArg id)
[ "BeginAddChildren", "(", "self", "PGPropArg", "id", ")" ]
def BeginAddChildren(*args, **kwargs): """BeginAddChildren(self, PGPropArg id)""" return _propgrid.PropertyGridInterface_BeginAddChildren(*args, **kwargs)
[ "def", "BeginAddChildren", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_BeginAddChildren", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L1102-L1104
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibar.py
python
AuiToolBar.SetToolOrientation
(self, orientation)
Sets the tool orientation for the toolbar items. :param integer `orientation`: the :class:`AuiToolBarItem` orientation.
Sets the tool orientation for the toolbar items.
[ "Sets", "the", "tool", "orientation", "for", "the", "toolbar", "items", "." ]
def SetToolOrientation(self, orientation): """ Sets the tool orientation for the toolbar items. :param integer `orientation`: the :class:`AuiToolBarItem` orientation. """ self._tool_orientation = orientation if self._art: self._art.SetOrientation(orientation)
[ "def", "SetToolOrientation", "(", "self", ",", "orientation", ")", ":", "self", ".", "_tool_orientation", "=", "orientation", "if", "self", ".", "_art", ":", "self", ".", "_art", ".", "SetOrientation", "(", "orientation", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibar.py#L2386-L2395
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/Tkinter.py
python
LabelFrame.__init__
(self, master=None, cnf={}, **kw)
Construct a labelframe widget with the parent MASTER. STANDARD OPTIONS borderwidth, cursor, font, foreground, highlightbackground, highlightcolor, highlightthickness, padx, pady, relief, takefocus, text WIDGET-SPECIFIC OPTIONS background, class, colormap, container, height, labelanchor, labelwidget, visual, width
Construct a labelframe widget with the parent MASTER.
[ "Construct", "a", "labelframe", "widget", "with", "the", "parent", "MASTER", "." ]
def __init__(self, master=None, cnf={}, **kw): """Construct a labelframe widget with the parent MASTER. STANDARD OPTIONS borderwidth, cursor, font, foreground, highlightbackground, highlightcolor, highlightthickness, padx, pady, relief, takefocus, text WIDGET-SPECIFIC OPTIONS background, class, colormap, container, height, labelanchor, labelwidget, visual, width """ Widget.__init__(self, master, 'labelframe', cnf, kw)
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "Widget", ".", "__init__", "(", "self", ",", "master", ",", "'labelframe'", ",", "cnf", ",", "kw", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L3609-L3625
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
ipc/ipdl/ipdl/parser.py
python
p_OptionalMessageCompress
(p)
OptionalMessageCompress : COMPRESS |
OptionalMessageCompress : COMPRESS |
[ "OptionalMessageCompress", ":", "COMPRESS", "|" ]
def p_OptionalMessageCompress(p): """OptionalMessageCompress : COMPRESS | """ if 1 == len(p): p[0] = '' else: p[0] = 'compress'
[ "def", "p_OptionalMessageCompress", "(", "p", ")", ":", "if", "1", "==", "len", "(", "p", ")", ":", "p", "[", "0", "]", "=", "''", "else", ":", "p", "[", "0", "]", "=", "'compress'" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/ipc/ipdl/ipdl/parser.py#L542-L548
timi-liuliang/echo
40a5a24d430eee4118314459ab7e03afcb3b8719
thirdparty/protobuf/python/google/protobuf/text_format.py
python
ParseBool
(text)
Parse a boolean value. Args: text: Text to parse. Returns: Boolean values parsed Raises: ValueError: If text is not a valid boolean.
Parse a boolean value.
[ "Parse", "a", "boolean", "value", "." ]
def ParseBool(text): """Parse a boolean value. Args: text: Text to parse. Returns: Boolean values parsed Raises: ValueError: If text is not a valid boolean. """ if text in ('true', 't', '1'): return True elif text in ('false', 'f', '0'): return False else: raise ValueError('Expected "true" or "false".')
[ "def", "ParseBool", "(", "text", ")", ":", "if", "text", "in", "(", "'true'", ",", "'t'", ",", "'1'", ")", ":", "return", "True", "elif", "text", "in", "(", "'false'", ",", "'f'", ",", "'0'", ")", ":", "return", "False", "else", ":", "raise", "ValueError", "(", "'Expected \"true\" or \"false\".'", ")" ]
https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/text_format.py#L820-L837
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/build_swift/build_swift/shell.py
python
copy
(source, dest, echo=False)
Emulates the `cp` command to copy a file or directory.
Emulates the `cp` command to copy a file or directory.
[ "Emulates", "the", "cp", "command", "to", "copy", "a", "file", "or", "directory", "." ]
def copy(source, dest, echo=False): """Emulates the `cp` command to copy a file or directory. """ source = _convert_pathlib_path(source) dest = _convert_pathlib_path(dest) if os.path.isfile(source): if echo: _echo_command(['cp', source, dest], sys.stdout) return shutil.copyfile(source, dest) if os.path.isdir(source): if echo: _echo_command(['cp', '-R', source, dest], sys.stdout) return shutil.copytree(source, dest)
[ "def", "copy", "(", "source", ",", "dest", ",", "echo", "=", "False", ")", ":", "source", "=", "_convert_pathlib_path", "(", "source", ")", "dest", "=", "_convert_pathlib_path", "(", "dest", ")", "if", "os", ".", "path", ".", "isfile", "(", "source", ")", ":", "if", "echo", ":", "_echo_command", "(", "[", "'cp'", ",", "source", ",", "dest", "]", ",", "sys", ".", "stdout", ")", "return", "shutil", ".", "copyfile", "(", "source", ",", "dest", ")", "if", "os", ".", "path", ".", "isdir", "(", "source", ")", ":", "if", "echo", ":", "_echo_command", "(", "[", "'cp'", ",", "'-R'", ",", "source", ",", "dest", "]", ",", "sys", ".", "stdout", ")", "return", "shutil", ".", "copytree", "(", "source", ",", "dest", ")" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/build_swift/build_swift/shell.py#L355-L370
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Window.SetOwnBackgroundColour
(*args, **kwargs)
return _core_.Window_SetOwnBackgroundColour(*args, **kwargs)
SetOwnBackgroundColour(self, Colour colour)
SetOwnBackgroundColour(self, Colour colour)
[ "SetOwnBackgroundColour", "(", "self", "Colour", "colour", ")" ]
def SetOwnBackgroundColour(*args, **kwargs): """SetOwnBackgroundColour(self, Colour colour)""" return _core_.Window_SetOwnBackgroundColour(*args, **kwargs)
[ "def", "SetOwnBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_SetOwnBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L10865-L10867
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
PreCheckBox
(*args, **kwargs)
return val
PreCheckBox() -> CheckBox Precreate a CheckBox for 2-phase creation.
PreCheckBox() -> CheckBox
[ "PreCheckBox", "()", "-", ">", "CheckBox" ]
def PreCheckBox(*args, **kwargs): """ PreCheckBox() -> CheckBox Precreate a CheckBox for 2-phase creation. """ val = _controls_.new_PreCheckBox(*args, **kwargs) return val
[ "def", "PreCheckBox", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_controls_", ".", "new_PreCheckBox", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L457-L464
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/_polybase.py
python
ABCPolyBase.has_sametype
(self, other)
return isinstance(other, self.__class__)
Check if types match. .. versionadded:: 1.7.0 Parameters ---------- other : object Class instance. Returns ------- bool : boolean True if other is same class as self
Check if types match.
[ "Check", "if", "types", "match", "." ]
def has_sametype(self, other): """Check if types match. .. versionadded:: 1.7.0 Parameters ---------- other : object Class instance. Returns ------- bool : boolean True if other is same class as self """ return isinstance(other, self.__class__)
[ "def", "has_sametype", "(", "self", ",", "other", ")", ":", "return", "isinstance", "(", "other", ",", "self", ".", "__class__", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/_polybase.py#L211-L227
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/cluster/hierarchy.py
python
ClusterNode.get_left
(self)
return self.left
Return a reference to the left child tree object. Returns ------- left : ClusterNode The left child of the target node. If the node is a leaf, None is returned.
Return a reference to the left child tree object.
[ "Return", "a", "reference", "to", "the", "left", "child", "tree", "object", "." ]
def get_left(self): """ Return a reference to the left child tree object. Returns ------- left : ClusterNode The left child of the target node. If the node is a leaf, None is returned. """ return self.left
[ "def", "get_left", "(", "self", ")", ":", "return", "self", ".", "left" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/cluster/hierarchy.py#L1228-L1239
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/nonlin.py
python
LowRankMatrix.collapse
(self)
Collapse the low-rank matrix to a full-rank one.
Collapse the low-rank matrix to a full-rank one.
[ "Collapse", "the", "low", "-", "rank", "matrix", "to", "a", "full", "-", "rank", "one", "." ]
def collapse(self): """Collapse the low-rank matrix to a full-rank one.""" self.collapsed = np.array(self) self.cs = None self.ds = None self.alpha = None
[ "def", "collapse", "(", "self", ")", ":", "self", ".", "collapsed", "=", "np", ".", "array", "(", "self", ")", "self", ".", "cs", "=", "None", "self", ".", "ds", "=", "None", "self", ".", "alpha", "=", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/nonlin.py#L792-L797
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
Locale.GetName
(*args, **kwargs)
return _gdi_.Locale_GetName(*args, **kwargs)
GetName(self) -> String
GetName(self) -> String
[ "GetName", "(", "self", ")", "-", ">", "String" ]
def GetName(*args, **kwargs): """GetName(self) -> String""" return _gdi_.Locale_GetName(*args, **kwargs)
[ "def", "GetName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Locale_GetName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L3084-L3086
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/tree.py
python
listicons
(icondir=ICONDIR)
Utility to display the available icons.
Utility to display the available icons.
[ "Utility", "to", "display", "the", "available", "icons", "." ]
def listicons(icondir=ICONDIR): """Utility to display the available icons.""" root = Tk() import glob list = glob.glob(os.path.join(icondir, "*.gif")) list.sort() images = [] row = column = 0 for file in list: name = os.path.splitext(os.path.basename(file))[0] image = PhotoImage(file=file, master=root) images.append(image) label = Label(root, image=image, bd=1, relief="raised") label.grid(row=row, column=column) label = Label(root, text=name) label.grid(row=row+1, column=column) column = column + 1 if column >= 10: row = row+2 column = 0 root.images = images
[ "def", "listicons", "(", "icondir", "=", "ICONDIR", ")", ":", "root", "=", "Tk", "(", ")", "import", "glob", "list", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "icondir", ",", "\"*.gif\"", ")", ")", "list", ".", "sort", "(", ")", "images", "=", "[", "]", "row", "=", "column", "=", "0", "for", "file", "in", "list", ":", "name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "file", ")", ")", "[", "0", "]", "image", "=", "PhotoImage", "(", "file", "=", "file", ",", "master", "=", "root", ")", "images", ".", "append", "(", "image", ")", "label", "=", "Label", "(", "root", ",", "image", "=", "image", ",", "bd", "=", "1", ",", "relief", "=", "\"raised\"", ")", "label", ".", "grid", "(", "row", "=", "row", ",", "column", "=", "column", ")", "label", "=", "Label", "(", "root", ",", "text", "=", "name", ")", "label", ".", "grid", "(", "row", "=", "row", "+", "1", ",", "column", "=", "column", ")", "column", "=", "column", "+", "1", "if", "column", ">=", "10", ":", "row", "=", "row", "+", "2", "column", "=", "0", "root", ".", "images", "=", "images" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/tree.py#L37-L57
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/window/rolling.py
python
_Window._create_blocks
(self)
return blocks, obj
Split data into blocks & return conformed data.
Split data into blocks & return conformed data.
[ "Split", "data", "into", "blocks", "&", "return", "conformed", "data", "." ]
def _create_blocks(self): """ Split data into blocks & return conformed data. """ obj = self._selected_obj # filter out the on from the object if self.on is not None and not isinstance(self.on, Index): if obj.ndim == 2: obj = obj.reindex(columns=obj.columns.difference([self.on]), copy=False) blocks = obj._to_dict_of_blocks(copy=False).values() return blocks, obj
[ "def", "_create_blocks", "(", "self", ")", ":", "obj", "=", "self", ".", "_selected_obj", "# filter out the on from the object", "if", "self", ".", "on", "is", "not", "None", "and", "not", "isinstance", "(", "self", ".", "on", ",", "Index", ")", ":", "if", "obj", ".", "ndim", "==", "2", ":", "obj", "=", "obj", ".", "reindex", "(", "columns", "=", "obj", ".", "columns", ".", "difference", "(", "[", "self", ".", "on", "]", ")", ",", "copy", "=", "False", ")", "blocks", "=", "obj", ".", "_to_dict_of_blocks", "(", "copy", "=", "False", ")", ".", "values", "(", ")", "return", "blocks", ",", "obj" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/window/rolling.py#L148-L161
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/wms/ogc/implementation/impl_v130.py
python
GetCapabilitiesRequest.SetLayers
(self)
Set the layers for the capabilities xml.
Set the layers for the capabilities xml.
[ "Set", "the", "layers", "for", "the", "capabilities", "xml", "." ]
def SetLayers(self): """Set the layers for the capabilities xml.""" # This outer, inaccessible layer is to give information just once; # the sub-layers inherit it. outer_layer = capabilities_wms.Layer( # 7.2.4.7.4 The layer is area-filling => opaque opaque=True, # 7.2.4.7.5 -- we can subset. noSubsets=False, # whether we support GetFeatureInfo queryable=False, # -- can't request it, this is just a container. Name=None, Title=_TITLE) server_layers_by_name = self.layer_obj.GetLayers( utils.GetValue(self.parameters, "server-url"), utils.GetValue(self.parameters, "TargetPath")) if not server_layers_by_name: # Raise ServiceException here. raise ServiceException(None, "Database type is not supported.") for layer_name, server_layer in server_layers_by_name.iteritems(): proj = server_layer.projection wms_layer = capabilities_wms.Layer( # 7.2.4.7.4 - Even for vector maps we always get data from # the server, even if it's just a transparent tile. By # jeffdonner's reading, this means that even the vector # layers are 'opaque'. opaque=True, # 7.2.4.7.5 - we can subset. noSubsets=False, queryable=False, Name=layer_name, Title=server_layer.label, # ex geo bounding box is required. EX_GeographicBoundingBox= capabilities_wms.EX_GeographicBoundingBox( westBoundLongitude=-proj.MAX_LONGITUDE, eastBoundLongitude=proj.MAX_LONGITUDE, southBoundLatitude=-proj.MAX_LATITUDE, northBoundLatitude=proj.MAX_LATITUDE)) for epsg_name in proj.EPSG_NAMES: wms_layer.add_CRS(epsg_name) map_limits = proj.AdvertizedLogOuterBounds() bounding_boxes = [] for epsg_name in proj.EPSG_NAMES: (min_x, min_y, max_x, max_y) = self._GetMapLimitsForEpsg( map_limits, epsg_name) bounding_box_object = capabilities_wms.BoundingBox( CRS=epsg_name, minx=min_x, miny=min_y, maxx=max_x, maxy=max_y) bounding_boxes.append(bounding_box_object) wms_layer.set_BoundingBox(bounding_boxes) outer_layer.add_Layer(wms_layer) self.capabilities_xml.get_Capability().set_Layer(outer_layer)
[ "def", "SetLayers", "(", "self", ")", ":", "# This outer, inaccessible layer is to give information just once;", "# the sub-layers inherit it.", "outer_layer", "=", "capabilities_wms", ".", "Layer", "(", "# 7.2.4.7.4 The layer is area-filling => opaque", "opaque", "=", "True", ",", "# 7.2.4.7.5 -- we can subset.", "noSubsets", "=", "False", ",", "# whether we support GetFeatureInfo", "queryable", "=", "False", ",", "# -- can't request it, this is just a container.", "Name", "=", "None", ",", "Title", "=", "_TITLE", ")", "server_layers_by_name", "=", "self", ".", "layer_obj", ".", "GetLayers", "(", "utils", ".", "GetValue", "(", "self", ".", "parameters", ",", "\"server-url\"", ")", ",", "utils", ".", "GetValue", "(", "self", ".", "parameters", ",", "\"TargetPath\"", ")", ")", "if", "not", "server_layers_by_name", ":", "# Raise ServiceException here.", "raise", "ServiceException", "(", "None", ",", "\"Database type is not supported.\"", ")", "for", "layer_name", ",", "server_layer", "in", "server_layers_by_name", ".", "iteritems", "(", ")", ":", "proj", "=", "server_layer", ".", "projection", "wms_layer", "=", "capabilities_wms", ".", "Layer", "(", "# 7.2.4.7.4 - Even for vector maps we always get data from", "# the server, even if it's just a transparent tile. By", "# jeffdonner's reading, this means that even the vector", "# layers are 'opaque'.", "opaque", "=", "True", ",", "# 7.2.4.7.5 - we can subset.", "noSubsets", "=", "False", ",", "queryable", "=", "False", ",", "Name", "=", "layer_name", ",", "Title", "=", "server_layer", ".", "label", ",", "# ex geo bounding box is required.", "EX_GeographicBoundingBox", "=", "capabilities_wms", ".", "EX_GeographicBoundingBox", "(", "westBoundLongitude", "=", "-", "proj", ".", "MAX_LONGITUDE", ",", "eastBoundLongitude", "=", "proj", ".", "MAX_LONGITUDE", ",", "southBoundLatitude", "=", "-", "proj", ".", "MAX_LATITUDE", ",", "northBoundLatitude", "=", "proj", ".", "MAX_LATITUDE", ")", ")", "for", "epsg_name", "in", "proj", ".", "EPSG_NAMES", ":", "wms_layer", ".", "add_CRS", "(", "epsg_name", ")", "map_limits", "=", "proj", ".", "AdvertizedLogOuterBounds", "(", ")", "bounding_boxes", "=", "[", "]", "for", "epsg_name", "in", "proj", ".", "EPSG_NAMES", ":", "(", "min_x", ",", "min_y", ",", "max_x", ",", "max_y", ")", "=", "self", ".", "_GetMapLimitsForEpsg", "(", "map_limits", ",", "epsg_name", ")", "bounding_box_object", "=", "capabilities_wms", ".", "BoundingBox", "(", "CRS", "=", "epsg_name", ",", "minx", "=", "min_x", ",", "miny", "=", "min_y", ",", "maxx", "=", "max_x", ",", "maxy", "=", "max_y", ")", "bounding_boxes", ".", "append", "(", "bounding_box_object", ")", "wms_layer", ".", "set_BoundingBox", "(", "bounding_boxes", ")", "outer_layer", ".", "add_Layer", "(", "wms_layer", ")", "self", ".", "capabilities_xml", ".", "get_Capability", "(", ")", ".", "set_Layer", "(", "outer_layer", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/wms/ogc/implementation/impl_v130.py#L190-L257
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/third_party/jinja2/lexer.py
python
Lexer.tokenize
(self, source, name=None, filename=None, state=None)
return TokenStream(self.wrap(stream, name, filename), name, filename)
Calls tokeniter + tokenize and wraps it in a token stream.
Calls tokeniter + tokenize and wraps it in a token stream.
[ "Calls", "tokeniter", "+", "tokenize", "and", "wraps", "it", "in", "a", "token", "stream", "." ]
def tokenize(self, source, name=None, filename=None, state=None): """Calls tokeniter + tokenize and wraps it in a token stream. """ stream = self.tokeniter(source, name, filename, state) return TokenStream(self.wrap(stream, name, filename), name, filename)
[ "def", "tokenize", "(", "self", ",", "source", ",", "name", "=", "None", ",", "filename", "=", "None", ",", "state", "=", "None", ")", ":", "stream", "=", "self", ".", "tokeniter", "(", "source", ",", "name", ",", "filename", ",", "state", ")", "return", "TokenStream", "(", "self", ".", "wrap", "(", "stream", ",", "name", ",", "filename", ")", ",", "name", ",", "filename", ")" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/lexer.py#L542-L546
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/wubi/backends/common/metalink.py
python
Metalink.get_dict
(self)
return dict
Return all the data as a dictionary. Used by __eq__.
Return all the data as a dictionary. Used by __eq__.
[ "Return", "all", "the", "data", "as", "a", "dictionary", ".", "Used", "by", "__eq__", "." ]
def get_dict(self): """Return all the data as a dictionary. Used by __eq__.""" dict = copy.copy(self.__dict__) files = [] for f in self.files: files.append(f.get_dict()) dict['files'] = files return dict
[ "def", "get_dict", "(", "self", ")", ":", "dict", "=", "copy", ".", "copy", "(", "self", ".", "__dict__", ")", "files", "=", "[", "]", "for", "f", "in", "self", ".", "files", ":", "files", ".", "append", "(", "f", ".", "get_dict", "(", ")", ")", "dict", "[", "'files'", "]", "=", "files", "return", "dict" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/wubi/backends/common/metalink.py#L35-L42
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/scons/khEnvironment.py
python
khEnvironment.bash_escape
(value)
return "'{0}'".format(value.replace("'", "'\\''"))
Escapes a given value as a BASH string.
Escapes a given value as a BASH string.
[ "Escapes", "a", "given", "value", "as", "a", "BASH", "string", "." ]
def bash_escape(value): """Escapes a given value as a BASH string.""" return "'{0}'".format(value.replace("'", "'\\''"))
[ "def", "bash_escape", "(", "value", ")", ":", "return", "\"'{0}'\"", ".", "format", "(", "value", ".", "replace", "(", "\"'\"", ",", "\"'\\\\''\"", ")", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/scons/khEnvironment.py#L310-L313
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/dask_cudf/dask_cudf/core.py
python
DataFrame.to_parquet
(self, path, *args, **kwargs)
return to_parquet(self, path, *args, **kwargs)
Calls dask.dataframe.io.to_parquet with CudfEngine backend
Calls dask.dataframe.io.to_parquet with CudfEngine backend
[ "Calls", "dask", ".", "dataframe", ".", "io", ".", "to_parquet", "with", "CudfEngine", "backend" ]
def to_parquet(self, path, *args, **kwargs): """Calls dask.dataframe.io.to_parquet with CudfEngine backend""" from dask_cudf.io import to_parquet return to_parquet(self, path, *args, **kwargs)
[ "def", "to_parquet", "(", "self", ",", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "dask_cudf", ".", "io", "import", "to_parquet", "return", "to_parquet", "(", "self", ",", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/dask_cudf/dask_cudf/core.py#L264-L268
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/function.py
python
get_extra_args
()
Returns the corresponding function arguments for the captured inputs. Returns: If the default graph is being used to define a function, the returned list of place holders are those used inside the function body corresponding those returned by get_extra_inputs(). Otherwise, returns an empty list.
Returns the corresponding function arguments for the captured inputs.
[ "Returns", "the", "corresponding", "function", "arguments", "for", "the", "captured", "inputs", "." ]
def get_extra_args(): """Returns the corresponding function arguments for the captured inputs. Returns: If the default graph is being used to define a function, the returned list of place holders are those used inside the function body corresponding those returned by get_extra_inputs(). Otherwise, returns an empty list. """ g = ops.get_default_graph() if isinstance(g, _FuncGraph): return g.extra_args else: return []
[ "def", "get_extra_args", "(", ")", ":", "g", "=", "ops", ".", "get_default_graph", "(", ")", "if", "isinstance", "(", "g", ",", "_FuncGraph", ")", ":", "return", "g", ".", "extra_args", "else", ":", "return", "[", "]" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/function.py#L1047-L1060
llvm-mirror/lldb
d01083a850f577b85501a0902b52fd0930de72c7
third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py
python
SpawnBase.read_nonblocking
(self, size=1, timeout=None)
return s
This reads data from the file descriptor. This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it. The timeout parameter is ignored.
This reads data from the file descriptor.
[ "This", "reads", "data", "from", "the", "file", "descriptor", "." ]
def read_nonblocking(self, size=1, timeout=None): """This reads data from the file descriptor. This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it. The timeout parameter is ignored. """ try: s = os.read(self.child_fd, size) except OSError as err: if err.args[0] == errno.EIO: # Linux-style EOF self.flag_eof = True raise EOF('End Of File (EOF). Exception style platform.') raise if s == b'': # BSD-style EOF self.flag_eof = True raise EOF('End Of File (EOF). Empty string style platform.') s = self._decoder.decode(s, final=False) self._log(s, 'read') return s
[ "def", "read_nonblocking", "(", "self", ",", "size", "=", "1", ",", "timeout", "=", "None", ")", ":", "try", ":", "s", "=", "os", ".", "read", "(", "self", ".", "child_fd", ",", "size", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "args", "[", "0", "]", "==", "errno", ".", "EIO", ":", "# Linux-style EOF", "self", ".", "flag_eof", "=", "True", "raise", "EOF", "(", "'End Of File (EOF). Exception style platform.'", ")", "raise", "if", "s", "==", "b''", ":", "# BSD-style EOF", "self", ".", "flag_eof", "=", "True", "raise", "EOF", "(", "'End Of File (EOF). Empty string style platform.'", ")", "s", "=", "self", ".", "_decoder", ".", "decode", "(", "s", ",", "final", "=", "False", ")", "self", ".", "_log", "(", "s", ",", "'read'", ")", "return", "s" ]
https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py#L157-L180
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/frame.py
python
DataFrame._ixs
(self, i: int, axis: int = 0)
Parameters ---------- i : int axis : int Notes ----- If slice passed, the resulting data will be a view.
Parameters ---------- i : int axis : int
[ "Parameters", "----------", "i", ":", "int", "axis", ":", "int" ]
def _ixs(self, i: int, axis: int = 0): """ Parameters ---------- i : int axis : int Notes ----- If slice passed, the resulting data will be a view. """ # irow if axis == 0: new_values = self._data.fast_xs(i) # if we are a copy, mark as such copy = isinstance(new_values, np.ndarray) and new_values.base is None result = self._constructor_sliced( new_values, index=self.columns, name=self.index[i], dtype=new_values.dtype, ) result._set_is_copy(self, copy=copy) return result # icol else: label = self.columns[i] # if the values returned are not the same length # as the index (iow a not found value), iget returns # a 0-len ndarray. This is effectively catching # a numpy error (as numpy should really raise) values = self._data.iget(i) if len(self.index) and not len(values): values = np.array([np.nan] * len(self.index), dtype=object) result = self._box_col_values(values, label) # this is a cached value, mark it so result._set_as_cached(label, self) return result
[ "def", "_ixs", "(", "self", ",", "i", ":", "int", ",", "axis", ":", "int", "=", "0", ")", ":", "# irow", "if", "axis", "==", "0", ":", "new_values", "=", "self", ".", "_data", ".", "fast_xs", "(", "i", ")", "# if we are a copy, mark as such", "copy", "=", "isinstance", "(", "new_values", ",", "np", ".", "ndarray", ")", "and", "new_values", ".", "base", "is", "None", "result", "=", "self", ".", "_constructor_sliced", "(", "new_values", ",", "index", "=", "self", ".", "columns", ",", "name", "=", "self", ".", "index", "[", "i", "]", ",", "dtype", "=", "new_values", ".", "dtype", ",", ")", "result", ".", "_set_is_copy", "(", "self", ",", "copy", "=", "copy", ")", "return", "result", "# icol", "else", ":", "label", "=", "self", ".", "columns", "[", "i", "]", "# if the values returned are not the same length", "# as the index (iow a not found value), iget returns", "# a 0-len ndarray. This is effectively catching", "# a numpy error (as numpy should really raise)", "values", "=", "self", ".", "_data", ".", "iget", "(", "i", ")", "if", "len", "(", "self", ".", "index", ")", "and", "not", "len", "(", "values", ")", ":", "values", "=", "np", ".", "array", "(", "[", "np", ".", "nan", "]", "*", "len", "(", "self", ".", "index", ")", ",", "dtype", "=", "object", ")", "result", "=", "self", ".", "_box_col_values", "(", "values", ",", "label", ")", "# this is a cached value, mark it so", "result", ".", "_set_as_cached", "(", "label", ",", "self", ")", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/frame.py#L2722-L2765
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
Examples/ReinforcementLearning/DeepQNeuralNetwork.py
python
DeepQAgent.observe
(self, old_state, action, reward, done)
This allows the agent to observe the output of doing the action it selected through act() on the old_state Attributes: old_state (Tensor[input_shape]): Previous environment state action (int): Action done by the agent reward (float): Reward for doing this action in the old_state environment done (bool): Indicate if the action has terminated the environment
This allows the agent to observe the output of doing the action it selected through act() on the old_state
[ "This", "allows", "the", "agent", "to", "observe", "the", "output", "of", "doing", "the", "action", "it", "selected", "through", "act", "()", "on", "the", "old_state" ]
def observe(self, old_state, action, reward, done): """ This allows the agent to observe the output of doing the action it selected through act() on the old_state Attributes: old_state (Tensor[input_shape]): Previous environment state action (int): Action done by the agent reward (float): Reward for doing this action in the old_state environment done (bool): Indicate if the action has terminated the environment """ self._episode_rewards.append(reward) # If done, reset short term memory (ie. History) if done: # Plot the metrics through Tensorboard and reset buffers if self._metrics_writer is not None: self._plot_metrics() self._episode_rewards, self._episode_q_means, self._episode_q_stddev = [], [], [] # Reset the short term memory self._history.reset() # Append to long term memory self._memory.append(old_state, action, reward, done)
[ "def", "observe", "(", "self", ",", "old_state", ",", "action", ",", "reward", ",", "done", ")", ":", "self", ".", "_episode_rewards", ".", "append", "(", "reward", ")", "# If done, reset short term memory (ie. History)", "if", "done", ":", "# Plot the metrics through Tensorboard and reset buffers", "if", "self", ".", "_metrics_writer", "is", "not", "None", ":", "self", ".", "_plot_metrics", "(", ")", "self", ".", "_episode_rewards", ",", "self", ".", "_episode_q_means", ",", "self", ".", "_episode_q_stddev", "=", "[", "]", ",", "[", "]", ",", "[", "]", "# Reset the short term memory", "self", ".", "_history", ".", "reset", "(", ")", "# Append to long term memory", "self", ".", "_memory", ".", "append", "(", "old_state", ",", "action", ",", "reward", ",", "done", ")" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/Examples/ReinforcementLearning/DeepQNeuralNetwork.py#L363-L385
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetComputedDefines
(self, config)
return defines
Returns the set of defines that are injected to the defines list based on other VS settings.
Returns the set of defines that are injected to the defines list based on other VS settings.
[ "Returns", "the", "set", "of", "defines", "that", "are", "injected", "to", "the", "defines", "list", "based", "on", "other", "VS", "settings", "." ]
def GetComputedDefines(self, config): """Returns the set of defines that are injected to the defines list based on other VS settings.""" config = self._TargetConfig(config) defines = [] if self._ConfigAttrib(['CharacterSet'], config) == '1': defines.extend(('_UNICODE', 'UNICODE')) if self._ConfigAttrib(['CharacterSet'], config) == '2': defines.append('_MBCS') defines.extend(self._Setting( ('VCCLCompilerTool', 'PreprocessorDefinitions'), config, default=[])) return defines
[ "def", "GetComputedDefines", "(", "self", ",", "config", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "defines", "=", "[", "]", "if", "self", ".", "_ConfigAttrib", "(", "[", "'CharacterSet'", "]", ",", "config", ")", "==", "'1'", ":", "defines", ".", "extend", "(", "(", "'_UNICODE'", ",", "'UNICODE'", ")", ")", "if", "self", ".", "_ConfigAttrib", "(", "[", "'CharacterSet'", "]", ",", "config", ")", "==", "'2'", ":", "defines", ".", "append", "(", "'_MBCS'", ")", "defines", ".", "extend", "(", "self", ".", "_Setting", "(", "(", "'VCCLCompilerTool'", ",", "'PreprocessorDefinitions'", ")", ",", "config", ",", "default", "=", "[", "]", ")", ")", "return", "defines" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L358-L369
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
ListItem.SetWidth
(*args, **kwargs)
return _controls_.ListItem_SetWidth(*args, **kwargs)
SetWidth(self, int width)
SetWidth(self, int width)
[ "SetWidth", "(", "self", "int", "width", ")" ]
def SetWidth(*args, **kwargs): """SetWidth(self, int width)""" return _controls_.ListItem_SetWidth(*args, **kwargs)
[ "def", "SetWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListItem_SetWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4200-L4202
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/third_party/Python/module/pexpect-4.6/pexpect/expect.py
python
searcher_string.__init__
(self, strings)
This creates an instance of searcher_string. This argument 'strings' may be a list; a sequence of strings; or the EOF or TIMEOUT types.
This creates an instance of searcher_string. This argument 'strings' may be a list; a sequence of strings; or the EOF or TIMEOUT types.
[ "This", "creates", "an", "instance", "of", "searcher_string", ".", "This", "argument", "strings", "may", "be", "a", "list", ";", "a", "sequence", "of", "strings", ";", "or", "the", "EOF", "or", "TIMEOUT", "types", "." ]
def __init__(self, strings): '''This creates an instance of searcher_string. This argument 'strings' may be a list; a sequence of strings; or the EOF or TIMEOUT types. ''' self.eof_index = -1 self.timeout_index = -1 self._strings = [] for n, s in enumerate(strings): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._strings.append((n, s))
[ "def", "__init__", "(", "self", ",", "strings", ")", ":", "self", ".", "eof_index", "=", "-", "1", "self", ".", "timeout_index", "=", "-", "1", "self", ".", "_strings", "=", "[", "]", "for", "n", ",", "s", "in", "enumerate", "(", "strings", ")", ":", "if", "s", "is", "EOF", ":", "self", ".", "eof_index", "=", "n", "continue", "if", "s", "is", "TIMEOUT", ":", "self", ".", "timeout_index", "=", "n", "continue", "self", ".", "_strings", ".", "append", "(", "(", "n", ",", "s", ")", ")" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/expect.py#L144-L158
opencv/opencv
76aff8478883858f0e46746044348ebb16dc3c67
modules/java/generator/gen_java.py
python
JavaWrapperGenerator.isSmartClass
(self, ci)
return ci.smart
Check if class stores Ptr<T>* instead of T* in nativeObj field
Check if class stores Ptr<T>* instead of T* in nativeObj field
[ "Check", "if", "class", "stores", "Ptr<T", ">", "*", "instead", "of", "T", "*", "in", "nativeObj", "field" ]
def isSmartClass(self, ci): ''' Check if class stores Ptr<T>* instead of T* in nativeObj field ''' if ci.smart != None: return ci.smart ci.smart = True # smart class is not properly handled in case of base/derived classes return ci.smart
[ "def", "isSmartClass", "(", "self", ",", "ci", ")", ":", "if", "ci", ".", "smart", "!=", "None", ":", "return", "ci", ".", "smart", "ci", ".", "smart", "=", "True", "# smart class is not properly handled in case of base/derived classes", "return", "ci", ".", "smart" ]
https://github.com/opencv/opencv/blob/76aff8478883858f0e46746044348ebb16dc3c67/modules/java/generator/gen_java.py#L1217-L1225
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/utils.py
python
should_bypass_proxies
(url)
return False
Returns whether we should bypass proxies or not.
Returns whether we should bypass proxies or not.
[ "Returns", "whether", "we", "should", "bypass", "proxies", "or", "not", "." ]
def should_bypass_proxies(url): """ Returns whether we should bypass proxies or not. """ get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy = get_proxy('no_proxy') netloc = urlparse(url).netloc if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the netloc, both with and without the port. no_proxy = no_proxy.replace(' ', '').split(',') ip = netloc.split(':')[0] if is_ipv4_address(ip): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(ip, proxy_ip): return True else: for host in no_proxy: if netloc.endswith(host) or netloc.split(':')[0].endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True # If the system proxy settings indicate that this URL should be bypassed, # don't proxy. # The proxy_bypass function is incredibly buggy on OS X in early versions # of Python 2.6, so allow this call to fail. Only catch the specific # exceptions we've seen, though: this call failing in other ways can reveal # legitimate problems. try: bypass = proxy_bypass(netloc) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
[ "def", "should_bypass_proxies", "(", "url", ")", ":", "get_proxy", "=", "lambda", "k", ":", "os", ".", "environ", ".", "get", "(", "k", ")", "or", "os", ".", "environ", ".", "get", "(", "k", ".", "upper", "(", ")", ")", "# First check whether no_proxy is defined. If it is, check that the URL", "# we're getting isn't in the no_proxy list.", "no_proxy", "=", "get_proxy", "(", "'no_proxy'", ")", "netloc", "=", "urlparse", "(", "url", ")", ".", "netloc", "if", "no_proxy", ":", "# We need to check whether we match here. We need to see if we match", "# the end of the netloc, both with and without the port.", "no_proxy", "=", "no_proxy", ".", "replace", "(", "' '", ",", "''", ")", ".", "split", "(", "','", ")", "ip", "=", "netloc", ".", "split", "(", "':'", ")", "[", "0", "]", "if", "is_ipv4_address", "(", "ip", ")", ":", "for", "proxy_ip", "in", "no_proxy", ":", "if", "is_valid_cidr", "(", "proxy_ip", ")", ":", "if", "address_in_network", "(", "ip", ",", "proxy_ip", ")", ":", "return", "True", "else", ":", "for", "host", "in", "no_proxy", ":", "if", "netloc", ".", "endswith", "(", "host", ")", "or", "netloc", ".", "split", "(", "':'", ")", "[", "0", "]", ".", "endswith", "(", "host", ")", ":", "# The URL does match something in no_proxy, so we don't want", "# to apply the proxies on this URL.", "return", "True", "# If the system proxy settings indicate that this URL should be bypassed,", "# don't proxy.", "# The proxy_bypass function is incredibly buggy on OS X in early versions", "# of Python 2.6, so allow this call to fail. Only catch the specific", "# exceptions we've seen, though: this call failing in other ways can reveal", "# legitimate problems.", "try", ":", "bypass", "=", "proxy_bypass", "(", "netloc", ")", "except", "(", "TypeError", ",", "socket", ".", "gaierror", ")", ":", "bypass", "=", "False", "if", "bypass", ":", "return", "True", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/utils.py#L487-L530
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/sans/algorithm_detail/batch_execution.py
python
single_reduction_for_batch
(state, use_optimizations, output_mode, plot_results, output_graph, save_can=False)
return out_scale_factors, out_shift_factors
Runs a single reduction. This function creates reduction packages which essentially contain information for a single valid reduction, run it and store the results according to the user specified setting (output_mode). Although this is considered a single reduction it can contain still several reductions since the SANSState object can at this point contain slice settings which require on reduction per time slice. :param state: a SANSState object :param use_optimizations: if true then the optimizations of child algorithms are enabled. :param output_mode: the output mode :param plot_results: bool. Whether or not workspaces should be plotted as they are reduced. Currently only works with event slice compatibility :param output_graph: The graph object for plotting workspaces. :param save_can: bool. whether or not to save out can workspaces
Runs a single reduction.
[ "Runs", "a", "single", "reduction", "." ]
def single_reduction_for_batch(state, use_optimizations, output_mode, plot_results, output_graph, save_can=False): """ Runs a single reduction. This function creates reduction packages which essentially contain information for a single valid reduction, run it and store the results according to the user specified setting (output_mode). Although this is considered a single reduction it can contain still several reductions since the SANSState object can at this point contain slice settings which require on reduction per time slice. :param state: a SANSState object :param use_optimizations: if true then the optimizations of child algorithms are enabled. :param output_mode: the output mode :param plot_results: bool. Whether or not workspaces should be plotted as they are reduced. Currently only works with event slice compatibility :param output_graph: The graph object for plotting workspaces. :param save_can: bool. whether or not to save out can workspaces """ # ------------------------------------------------------------------------------------------------------------------ # Load the data # ------------------------------------------------------------------------------------------------------------------ workspace_to_name = {SANSDataType.SAMPLE_SCATTER: "SampleScatterWorkspace", SANSDataType.SAMPLE_TRANSMISSION: "SampleTransmissionWorkspace", SANSDataType.SAMPLE_DIRECT: "SampleDirectWorkspace", SANSDataType.CAN_SCATTER: "CanScatterWorkspace", SANSDataType.CAN_TRANSMISSION: "CanTransmissionWorkspace", SANSDataType.CAN_DIRECT: "CanDirectWorkspace"} workspace_to_monitor = {SANSDataType.SAMPLE_SCATTER: "SampleScatterMonitorWorkspace", SANSDataType.CAN_SCATTER: "CanScatterMonitorWorkspace"} workspaces, monitors = provide_loaded_data(state, use_optimizations, workspace_to_name, workspace_to_monitor) # ------------------------------------------------------------------------------------------------------------------ # Get reduction settings # Split into individual bundles which can be reduced individually. We split here if we have multiple periods. # ------------------------------------------------------------------------------------------------------------------ reduction_packages = get_reduction_packages(state, workspaces, monitors) split_for_event_slices = reduction_packages_require_splitting_for_event_slices(reduction_packages) event_slice_optimisation, reduction_packages = select_reduction_alg(split_for_event_slices, state.compatibility.use_compatibility_mode, state.compatibility.use_event_slice_optimisation, reduction_packages) # ------------------------------------------------------------------------------------------------------------------ # Run reductions (one at a time) # ------------------------------------------------------------------------------------------------------------------ single_reduction_name = "SANSSingleReduction" single_reduction_options = {"UseOptimizations": use_optimizations, "SaveCan": save_can} alg_version = 2 if event_slice_optimisation else 1 reduction_alg = create_managed_non_child_algorithm(single_reduction_name, version=alg_version, **single_reduction_options) reduction_alg.setChild(False) reduction_alg.setAlwaysStoreInADS(False) # Perform the data reduction for reduction_package in reduction_packages: # ----------------------------------- # Set the properties on the algorithm # ----------------------------------- set_properties_for_reduction_algorithm(reduction_alg, reduction_package, workspace_to_name, workspace_to_monitor, event_slice_optimisation=event_slice_optimisation) # ----------------------------------- # Run the reduction # ----------------------------------- reduction_alg.execute() # ----------------------------------- # Get the output of the algorithm # ----------------------------------- _get_ws_from_alg(reduction_alg, reduction_package) set_alg_output_names(reduction_package, event_slice_optimisation) out_scale_factor, out_shift_factor = get_shift_and_scale_factors_from_algorithm(reduction_alg, event_slice_optimisation) reduction_package.out_scale_factor = out_scale_factor reduction_package.out_shift_factor = out_shift_factor if not event_slice_optimisation and plot_results: # Plot results is intended to show the result of each workspace/slice as it is reduced # as we reduce in bulk, it is not possible to plot live results while in event_slice mode plot_workspace(reduction_package, output_graph) # ----------------------------------- # The workspaces are already on the ADS, but should potentially be grouped # ----------------------------------- group_workspaces_if_required(reduction_package, output_mode, save_can, event_slice_optimisation=event_slice_optimisation) data = state.data additional_run_numbers = {"SampleTransmissionRunNumber": "" if data.sample_transmission is None else str(data.sample_transmission), "SampleDirectRunNumber": "" if data.sample_direct is None else str(data.sample_direct), "CanScatterRunNumber": "" if data.can_scatter is None else str(data.can_scatter), "CanDirectRunNumber": "" if data.can_direct is None else str(data.can_direct)} # -------------------------------- # Perform output of all workspaces # -------------------------------- # We have three options here # 1. PublishToADS: # * This means we can leave it as it is # 2. SaveToFile: # * This means we need to save out the reduced data # * Then we need to delete the reduced data from the ADS # 3. Both: # * This means that we need to save out the reduced data # * The data is already on the ADS, so do nothing if output_mode is OutputMode.SAVE_TO_FILE: save_to_file(reduction_packages, save_can, additional_run_numbers, event_slice_optimisation=event_slice_optimisation) delete_reduced_workspaces(reduction_packages) elif output_mode is OutputMode.BOTH: save_to_file(reduction_packages, save_can, additional_run_numbers, event_slice_optimisation=event_slice_optimisation) # ----------------------------------------------------------------------- # Clean up other workspaces if the optimizations have not been turned on. # ----------------------------------------------------------------------- if not use_optimizations: delete_optimization_workspaces(reduction_packages, workspaces, monitors, save_can) out_scale_factors = [] out_shift_factors = [] for reduction_package in reduction_packages: out_scale_factors.extend(reduction_package.out_scale_factor) out_shift_factors.extend(reduction_package.out_shift_factor) return out_scale_factors, out_shift_factors
[ "def", "single_reduction_for_batch", "(", "state", ",", "use_optimizations", ",", "output_mode", ",", "plot_results", ",", "output_graph", ",", "save_can", "=", "False", ")", ":", "# ------------------------------------------------------------------------------------------------------------------", "# Load the data", "# ------------------------------------------------------------------------------------------------------------------", "workspace_to_name", "=", "{", "SANSDataType", ".", "SAMPLE_SCATTER", ":", "\"SampleScatterWorkspace\"", ",", "SANSDataType", ".", "SAMPLE_TRANSMISSION", ":", "\"SampleTransmissionWorkspace\"", ",", "SANSDataType", ".", "SAMPLE_DIRECT", ":", "\"SampleDirectWorkspace\"", ",", "SANSDataType", ".", "CAN_SCATTER", ":", "\"CanScatterWorkspace\"", ",", "SANSDataType", ".", "CAN_TRANSMISSION", ":", "\"CanTransmissionWorkspace\"", ",", "SANSDataType", ".", "CAN_DIRECT", ":", "\"CanDirectWorkspace\"", "}", "workspace_to_monitor", "=", "{", "SANSDataType", ".", "SAMPLE_SCATTER", ":", "\"SampleScatterMonitorWorkspace\"", ",", "SANSDataType", ".", "CAN_SCATTER", ":", "\"CanScatterMonitorWorkspace\"", "}", "workspaces", ",", "monitors", "=", "provide_loaded_data", "(", "state", ",", "use_optimizations", ",", "workspace_to_name", ",", "workspace_to_monitor", ")", "# ------------------------------------------------------------------------------------------------------------------", "# Get reduction settings", "# Split into individual bundles which can be reduced individually. We split here if we have multiple periods.", "# ------------------------------------------------------------------------------------------------------------------", "reduction_packages", "=", "get_reduction_packages", "(", "state", ",", "workspaces", ",", "monitors", ")", "split_for_event_slices", "=", "reduction_packages_require_splitting_for_event_slices", "(", "reduction_packages", ")", "event_slice_optimisation", ",", "reduction_packages", "=", "select_reduction_alg", "(", "split_for_event_slices", ",", "state", ".", "compatibility", ".", "use_compatibility_mode", ",", "state", ".", "compatibility", ".", "use_event_slice_optimisation", ",", "reduction_packages", ")", "# ------------------------------------------------------------------------------------------------------------------", "# Run reductions (one at a time)", "# ------------------------------------------------------------------------------------------------------------------", "single_reduction_name", "=", "\"SANSSingleReduction\"", "single_reduction_options", "=", "{", "\"UseOptimizations\"", ":", "use_optimizations", ",", "\"SaveCan\"", ":", "save_can", "}", "alg_version", "=", "2", "if", "event_slice_optimisation", "else", "1", "reduction_alg", "=", "create_managed_non_child_algorithm", "(", "single_reduction_name", ",", "version", "=", "alg_version", ",", "*", "*", "single_reduction_options", ")", "reduction_alg", ".", "setChild", "(", "False", ")", "reduction_alg", ".", "setAlwaysStoreInADS", "(", "False", ")", "# Perform the data reduction", "for", "reduction_package", "in", "reduction_packages", ":", "# -----------------------------------", "# Set the properties on the algorithm", "# -----------------------------------", "set_properties_for_reduction_algorithm", "(", "reduction_alg", ",", "reduction_package", ",", "workspace_to_name", ",", "workspace_to_monitor", ",", "event_slice_optimisation", "=", "event_slice_optimisation", ")", "# -----------------------------------", "# Run the reduction", "# -----------------------------------", "reduction_alg", ".", "execute", "(", ")", "# -----------------------------------", "# Get the output of the algorithm", "# -----------------------------------", "_get_ws_from_alg", "(", "reduction_alg", ",", "reduction_package", ")", "set_alg_output_names", "(", "reduction_package", ",", "event_slice_optimisation", ")", "out_scale_factor", ",", "out_shift_factor", "=", "get_shift_and_scale_factors_from_algorithm", "(", "reduction_alg", ",", "event_slice_optimisation", ")", "reduction_package", ".", "out_scale_factor", "=", "out_scale_factor", "reduction_package", ".", "out_shift_factor", "=", "out_shift_factor", "if", "not", "event_slice_optimisation", "and", "plot_results", ":", "# Plot results is intended to show the result of each workspace/slice as it is reduced", "# as we reduce in bulk, it is not possible to plot live results while in event_slice mode", "plot_workspace", "(", "reduction_package", ",", "output_graph", ")", "# -----------------------------------", "# The workspaces are already on the ADS, but should potentially be grouped", "# -----------------------------------", "group_workspaces_if_required", "(", "reduction_package", ",", "output_mode", ",", "save_can", ",", "event_slice_optimisation", "=", "event_slice_optimisation", ")", "data", "=", "state", ".", "data", "additional_run_numbers", "=", "{", "\"SampleTransmissionRunNumber\"", ":", "\"\"", "if", "data", ".", "sample_transmission", "is", "None", "else", "str", "(", "data", ".", "sample_transmission", ")", ",", "\"SampleDirectRunNumber\"", ":", "\"\"", "if", "data", ".", "sample_direct", "is", "None", "else", "str", "(", "data", ".", "sample_direct", ")", ",", "\"CanScatterRunNumber\"", ":", "\"\"", "if", "data", ".", "can_scatter", "is", "None", "else", "str", "(", "data", ".", "can_scatter", ")", ",", "\"CanDirectRunNumber\"", ":", "\"\"", "if", "data", ".", "can_direct", "is", "None", "else", "str", "(", "data", ".", "can_direct", ")", "}", "# --------------------------------", "# Perform output of all workspaces", "# --------------------------------", "# We have three options here", "# 1. PublishToADS:", "# * This means we can leave it as it is", "# 2. SaveToFile:", "# * This means we need to save out the reduced data", "# * Then we need to delete the reduced data from the ADS", "# 3. Both:", "# * This means that we need to save out the reduced data", "# * The data is already on the ADS, so do nothing", "if", "output_mode", "is", "OutputMode", ".", "SAVE_TO_FILE", ":", "save_to_file", "(", "reduction_packages", ",", "save_can", ",", "additional_run_numbers", ",", "event_slice_optimisation", "=", "event_slice_optimisation", ")", "delete_reduced_workspaces", "(", "reduction_packages", ")", "elif", "output_mode", "is", "OutputMode", ".", "BOTH", ":", "save_to_file", "(", "reduction_packages", ",", "save_can", ",", "additional_run_numbers", ",", "event_slice_optimisation", "=", "event_slice_optimisation", ")", "# -----------------------------------------------------------------------", "# Clean up other workspaces if the optimizations have not been turned on.", "# -----------------------------------------------------------------------", "if", "not", "use_optimizations", ":", "delete_optimization_workspaces", "(", "reduction_packages", ",", "workspaces", ",", "monitors", ",", "save_can", ")", "out_scale_factors", "=", "[", "]", "out_shift_factors", "=", "[", "]", "for", "reduction_package", "in", "reduction_packages", ":", "out_scale_factors", ".", "extend", "(", "reduction_package", ".", "out_scale_factor", ")", "out_shift_factors", ".", "extend", "(", "reduction_package", ".", "out_shift_factor", ")", "return", "out_scale_factors", ",", "out_shift_factors" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/batch_execution.py#L59-L187
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/xmlreader.py
python
XMLReader.setContentHandler
(self, handler)
Registers a new object to receive document content events.
Registers a new object to receive document content events.
[ "Registers", "a", "new", "object", "to", "receive", "document", "content", "events", "." ]
def setContentHandler(self, handler): "Registers a new object to receive document content events." self._cont_handler = handler
[ "def", "setContentHandler", "(", "self", ",", "handler", ")", ":", "self", ".", "_cont_handler", "=", "handler" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/xmlreader.py#L38-L40
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/Maya_AnimationRiggingTools/ARTv1/MayaTools/General/Scripts/P4.py
python
Map.is_empty
(self)
return self.count() == 0
Returns True if this map has no entries yet, otherwise False
Returns True if this map has no entries yet, otherwise False
[ "Returns", "True", "if", "this", "map", "has", "no", "entries", "yet", "otherwise", "False" ]
def is_empty(self): """Returns True if this map has no entries yet, otherwise False""" return self.count() == 0
[ "def", "is_empty", "(", "self", ")", ":", "return", "self", ".", "count", "(", ")", "==", "0" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/Maya_AnimationRiggingTools/ARTv1/MayaTools/General/Scripts/P4.py#L1411-L1417
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
demo/VART/resnet50_mt_py/resnet50.py
python
main
(argv)
image list to be run
image list to be run
[ "image", "list", "to", "be", "run" ]
def main(argv): global threadnum listimage = os.listdir(calib_image_dir) threadAll = [] threadnum = int(argv[1]) i = 0 global runTotall runTotall = len(listimage) g = xir.Graph.deserialize(argv[2]) subgraphs = get_child_subgraph_dpu(g) assert len(subgraphs) == 1 # only one DPU kernel all_dpu_runners = [] for i in range(int(threadnum)): all_dpu_runners.append(vart.Runner.create_runner(subgraphs[0], "run")) input_fixpos = all_dpu_runners[0].get_input_tensors()[0].get_attr("fix_point") input_scale = 2**input_fixpos """image list to be run """ img = [] for i in range(runTotall): path = os.path.join(calib_image_dir, listimage[i]) img.append(preprocess_one_image_fn(path, input_scale)) """ The cnt variable is used to control the number of times a single-thread DPU runs. Users can modify the value according to actual needs. It is not recommended to use too small number when there are few input images, for example: 1. If users can only provide very few images, e.g. only 1 image, they should set a relatively large number such as 360 to measure the average performance; 2. If users provide a huge dataset, e.g. 50000 images in the directory, they can use the variable to control the test time, and no need to run the whole dataset. """ cnt = 360 """run with batch """ time_start = time.time() for i in range(int(threadnum)): t1 = threading.Thread(target=runResnet50, args=(all_dpu_runners[i], img, cnt)) threadAll.append(t1) for x in threadAll: x.start() for x in threadAll: x.join() del all_dpu_runners time_end = time.time() timetotal = time_end - time_start total_frames = cnt * int(threadnum) fps = float(total_frames / timetotal) print( "FPS=%.2f, total frames = %.2f , time=%.6f seconds" % (fps, total_frames, timetotal) )
[ "def", "main", "(", "argv", ")", ":", "global", "threadnum", "listimage", "=", "os", ".", "listdir", "(", "calib_image_dir", ")", "threadAll", "=", "[", "]", "threadnum", "=", "int", "(", "argv", "[", "1", "]", ")", "i", "=", "0", "global", "runTotall", "runTotall", "=", "len", "(", "listimage", ")", "g", "=", "xir", ".", "Graph", ".", "deserialize", "(", "argv", "[", "2", "]", ")", "subgraphs", "=", "get_child_subgraph_dpu", "(", "g", ")", "assert", "len", "(", "subgraphs", ")", "==", "1", "# only one DPU kernel", "all_dpu_runners", "=", "[", "]", "for", "i", "in", "range", "(", "int", "(", "threadnum", ")", ")", ":", "all_dpu_runners", ".", "append", "(", "vart", ".", "Runner", ".", "create_runner", "(", "subgraphs", "[", "0", "]", ",", "\"run\"", ")", ")", "input_fixpos", "=", "all_dpu_runners", "[", "0", "]", ".", "get_input_tensors", "(", ")", "[", "0", "]", ".", "get_attr", "(", "\"fix_point\"", ")", "input_scale", "=", "2", "**", "input_fixpos", "img", "=", "[", "]", "for", "i", "in", "range", "(", "runTotall", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "calib_image_dir", ",", "listimage", "[", "i", "]", ")", "img", ".", "append", "(", "preprocess_one_image_fn", "(", "path", ",", "input_scale", ")", ")", "\"\"\"\n The cnt variable is used to control the number of times a single-thread DPU runs.\n Users can modify the value according to actual needs. It is not recommended to use\n too small number when there are few input images, for example:\n 1. If users can only provide very few images, e.g. only 1 image, they should set\n a relatively large number such as 360 to measure the average performance;\n 2. If users provide a huge dataset, e.g. 50000 images in the directory, they can\n use the variable to control the test time, and no need to run the whole dataset.\n \"\"\"", "cnt", "=", "360", "\"\"\"run with batch \"\"\"", "time_start", "=", "time", ".", "time", "(", ")", "for", "i", "in", "range", "(", "int", "(", "threadnum", ")", ")", ":", "t1", "=", "threading", ".", "Thread", "(", "target", "=", "runResnet50", ",", "args", "=", "(", "all_dpu_runners", "[", "i", "]", ",", "img", ",", "cnt", ")", ")", "threadAll", ".", "append", "(", "t1", ")", "for", "x", "in", "threadAll", ":", "x", ".", "start", "(", ")", "for", "x", "in", "threadAll", ":", "x", ".", "join", "(", ")", "del", "all_dpu_runners", "time_end", "=", "time", ".", "time", "(", ")", "timetotal", "=", "time_end", "-", "time_start", "total_frames", "=", "cnt", "*", "int", "(", "threadnum", ")", "fps", "=", "float", "(", "total_frames", "/", "timetotal", ")", "print", "(", "\"FPS=%.2f, total frames = %.2f , time=%.6f seconds\"", "%", "(", "fps", ",", "total_frames", ",", "timetotal", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/demo/VART/resnet50_mt_py/resnet50.py#L167-L219
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py
python
JIRA.assign_issue
(self, issue, assignee)
return True
Assign an issue to a user. None will set it to unassigned. -1 will set it to Automatic. :param issue: the issue to assign :param assignee: the user to assign the issue to
Assign an issue to a user. None will set it to unassigned. -1 will set it to Automatic.
[ "Assign", "an", "issue", "to", "a", "user", ".", "None", "will", "set", "it", "to", "unassigned", ".", "-", "1", "will", "set", "it", "to", "Automatic", "." ]
def assign_issue(self, issue, assignee): """Assign an issue to a user. None will set it to unassigned. -1 will set it to Automatic. :param issue: the issue to assign :param assignee: the user to assign the issue to """ url = self._options['server'] + \ '/rest/api/latest/issue/' + str(issue) + '/assignee' payload = {'name': assignee} r = self._session.put( url, data=json.dumps(payload)) raise_on_error(r) return True
[ "def", "assign_issue", "(", "self", ",", "issue", ",", "assignee", ")", ":", "url", "=", "self", ".", "_options", "[", "'server'", "]", "+", "'/rest/api/latest/issue/'", "+", "str", "(", "issue", ")", "+", "'/assignee'", "payload", "=", "{", "'name'", ":", "assignee", "}", "r", "=", "self", ".", "_session", ".", "put", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "payload", ")", ")", "raise_on_error", "(", "r", ")", "return", "True" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py#L1278-L1290
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/build/android/pylib/valgrind_tools.py
python
MemcheckTool.GetTestWrapper
(self)
return ValgrindTool.VG_DIR + '/' + 'vg-chrome-wrapper.sh'
Returns a string that is to be prepended to the test command line.
Returns a string that is to be prepended to the test command line.
[ "Returns", "a", "string", "that", "is", "to", "be", "prepended", "to", "the", "test", "command", "line", "." ]
def GetTestWrapper(self): """Returns a string that is to be prepended to the test command line.""" return ValgrindTool.VG_DIR + '/' + 'vg-chrome-wrapper.sh'
[ "def", "GetTestWrapper", "(", "self", ")", ":", "return", "ValgrindTool", ".", "VG_DIR", "+", "'/'", "+", "'vg-chrome-wrapper.sh'" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/android/pylib/valgrind_tools.py#L197-L199
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py
python
Decimal.__rpow__
(self, other, context=None)
return other.__pow__(self, context=context)
Swaps self/other and returns __pow__.
Swaps self/other and returns __pow__.
[ "Swaps", "self", "/", "other", "and", "returns", "__pow__", "." ]
def __rpow__(self, other, context=None): """Swaps self/other and returns __pow__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__pow__(self, context=context)
[ "def", "__rpow__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "return", "other", ".", "__pow__", "(", "self", ",", "context", "=", "context", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L2390-L2395
0xPhoeniX/MazeWalker
4da160908419fdbf6fadf2c8b4794325f5cbcfba
MazeUI/mazeui.py
python
MazeUIPluginForm.__init__
(self)
Initialization.
Initialization.
[ "Initialization", "." ]
def __init__(self): """ Initialization. """ idaapi.PluginForm.__init__(self) self.Widgets = [] self.iconp = Config().icons_path
[ "def", "__init__", "(", "self", ")", ":", "idaapi", ".", "PluginForm", ".", "__init__", "(", "self", ")", "self", ".", "Widgets", "=", "[", "]", "self", ".", "iconp", "=", "Config", "(", ")", ".", "icons_path" ]
https://github.com/0xPhoeniX/MazeWalker/blob/4da160908419fdbf6fadf2c8b4794325f5cbcfba/MazeUI/mazeui.py#L27-L33
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/fispact.py
python
parse_spectra
(data)
return spectra
reads gamma spectra data for each timestep returns list of length 24 corresponding to 24 gamma energy groups data is in gamma/s/cc
reads gamma spectra data for each timestep returns list of length 24 corresponding to 24 gamma energy groups data is in gamma/s/cc
[ "reads", "gamma", "spectra", "data", "for", "each", "timestep", "returns", "list", "of", "length", "24", "corresponding", "to", "24", "gamma", "energy", "groups", "data", "is", "in", "gamma", "/", "s", "/", "cc" ]
def parse_spectra(data): """ reads gamma spectra data for each timestep returns list of length 24 corresponding to 24 gamma energy groups data is in gamma/s/cc """ p1 = find_ind(data, "GAMMA SPECTRUM AND ENERGIES/SECOND") data = data[p1+7:p1+31] spectra = [] for l in data: spectra.append(float(l[130:141])) return spectra
[ "def", "parse_spectra", "(", "data", ")", ":", "p1", "=", "find_ind", "(", "data", ",", "\"GAMMA SPECTRUM AND ENERGIES/SECOND\"", ")", "data", "=", "data", "[", "p1", "+", "7", ":", "p1", "+", "31", "]", "spectra", "=", "[", "]", "for", "l", "in", "data", ":", "spectra", ".", "append", "(", "float", "(", "l", "[", "130", ":", "141", "]", ")", ")", "return", "spectra" ]
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/fispact.py#L362-L372
lukasmonk/lucaschess
13e2e5cb13b38a720ccf897af649054a64bcb914
Code/SQL/DBFcache.py
python
DBFcache.buscarID
(self, xid)
return -1
Busca el recno de un ID. @param xid: numero de id.
Busca el recno de un ID.
[ "Busca", "el", "recno", "de", "un", "ID", "." ]
def buscarID(self, xid): """ Busca el recno de un ID. @param xid: numero de id. """ for r in range(self.reccount()): if self.rowid(r) == xid: return r return -1
[ "def", "buscarID", "(", "self", ",", "xid", ")", ":", "for", "r", "in", "range", "(", "self", ".", "reccount", "(", ")", ")", ":", "if", "self", ".", "rowid", "(", "r", ")", "==", "xid", ":", "return", "r", "return", "-", "1" ]
https://github.com/lukasmonk/lucaschess/blob/13e2e5cb13b38a720ccf897af649054a64bcb914/Code/SQL/DBFcache.py#L187-L196