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
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/traveltime/modelling.py
python
TravelTimeDijkstraModelling.createStartModel
(self, dataVals)
return sm
Create a starting model from data values (gradient or constant).
Create a starting model from data values (gradient or constant).
[ "Create", "a", "starting", "model", "from", "data", "values", "(", "gradient", "or", "constant", ")", "." ]
def createStartModel(self, dataVals): """Create a starting model from data values (gradient or constant).""" sm = None if self._useGradient is not None: [vTop, vBot] = self._useGradient # something strange here!!! pg.info('Create gradient starting model. {0}: {1}'.format(vTop, vBot)) sm = createGradientModel2D(self.data, self.paraDomain, vTop, vBot) else: dists = shotReceiverDistances(self.data, full=True) aSlow = 1. / (dists / dataVals) # pg._r(self.regionManager().parameterCount()) sm = pg.Vector(self.regionManager().parameterCount(), pg.math.median(aSlow)) pg.info('Create constant starting model:', sm[0]) return sm
[ "def", "createStartModel", "(", "self", ",", "dataVals", ")", ":", "sm", "=", "None", "if", "self", ".", "_useGradient", "is", "not", "None", ":", "[", "vTop", ",", "vBot", "]", "=", "self", ".", "_useGradient", "# something strange here!!!", "pg", ".", ...
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/traveltime/modelling.py#L57-L77
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vcs/__init__.py
python
VersionControl.check_destination
(self, dest, url, rev_options, rev_display)
return checkout
Prepare a location to receive a checkout/clone. Return True if the location is ready for (and requires) a checkout/clone, False otherwise.
Prepare a location to receive a checkout/clone.
[ "Prepare", "a", "location", "to", "receive", "a", "checkout", "/", "clone", "." ]
def check_destination(self, dest, url, rev_options, rev_display): """ Prepare a location to receive a checkout/clone. Return True if the location is ready for (and requires) a checkout/clone, False otherwise. """ checkout = True prompt = False if os.path.exists(dest): checkout = False if os.path.exists(os.path.join(dest, self.dirname)): existing_url = self.get_url(dest) if self.compare_urls(existing_url, url): logger.info('%s in %s exists, and has correct URL (%s)' % (self.repo_name.title(), display_path(dest), url)) logger.notify('Updating %s %s%s' % (display_path(dest), self.repo_name, rev_display)) self.update(dest, rev_options) else: logger.warn('%s %s in %s exists with URL %s' % (self.name, self.repo_name, display_path(dest), existing_url)) prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ', ('s', 'i', 'w', 'b')) else: logger.warn('Directory %s already exists, ' 'and is not a %s %s.' % (dest, self.name, self.repo_name)) prompt = ('(i)gnore, (w)ipe, (b)ackup ', ('i', 'w', 'b')) if prompt: logger.warn('The plan is to install the %s repository %s' % (self.name, url)) response = ask_path_exists('What to do? %s' % prompt[0], prompt[1]) if response == 's': logger.notify('Switching %s %s to %s%s' % (self.repo_name, display_path(dest), url, rev_display)) self.switch(dest, url, rev_options) elif response == 'i': # do nothing pass elif response == 'w': logger.warn('Deleting %s' % display_path(dest)) rmtree(dest) checkout = True elif response == 'b': dest_dir = backup_dir(dest) logger.warn('Backing up %s to %s' % (display_path(dest), dest_dir)) shutil.move(dest, dest_dir) checkout = True return checkout
[ "def", "check_destination", "(", "self", ",", "dest", ",", "url", ",", "rev_options", ",", "rev_display", ")", ":", "checkout", "=", "True", "prompt", "=", "False", "if", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "checkout", "=", "False"...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vcs/__init__.py#L179-L235
google/clif
cab24d6a105609a65c95a36a1712ae3c20c7b5df
clif/python/proto.py
python
GenerateFrom
(messages, proto_filename, clif_hdr, proto_hdr)
Traverse ast and generate output files.
Traverse ast and generate output files.
[ "Traverse", "ast", "and", "generate", "output", "files", "." ]
def GenerateFrom(messages, proto_filename, clif_hdr, proto_hdr): """Traverse ast and generate output files.""" with open(FLAGS.header_out, 'w') as hout: gen.WriteTo(hout, gen.Headlines( proto_filename, [proto_hdr, 'clif/python/postconv.h'])) gen.WriteTo(hout, _GenHeader(messages)) with open(FLAGS.ccdeps_out, 'w') as cout: gen.WriteTo(cout, gen.Headlines( proto_filename, ['clif/python/runtime.h', 'clif/python/types.h', clif_hdr])) for ns, ts in itertools.groupby(messages, types.Namespace): if ns == '::': ns = 'clif' gen.WriteTo(cout, gen.TypeConverters(ns, ts))
[ "def", "GenerateFrom", "(", "messages", ",", "proto_filename", ",", "clif_hdr", ",", "proto_hdr", ")", ":", "with", "open", "(", "FLAGS", ".", "header_out", ",", "'w'", ")", "as", "hout", ":", "gen", ".", "WriteTo", "(", "hout", ",", "gen", ".", "Headl...
https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/python/proto.py#L110-L125
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/tensor_array_grad.py
python
_TensorArraySplitGrad
(op, flow)
return [None, grad, None, flow]
Gradient for TensorArraySplit. Args: op: Forward TensorArraySplit op. flow: Gradient `Tensor` flow to TensorArraySplit. Returns: A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad.
Gradient for TensorArraySplit.
[ "Gradient", "for", "TensorArraySplit", "." ]
def _TensorArraySplitGrad(op, flow): """Gradient for TensorArraySplit. Args: op: Forward TensorArraySplit op. flow: Gradient `Tensor` flow to TensorArraySplit. Returns: A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad. """ handle = op.inputs[0] dtype = op.get_attr("T") grad_source = _GetGradSource(flow) g = tensor_array_ops.TensorArray(dtype=dtype, handle=handle).grad( source=grad_source, flow=flow) grad = g.concat() # handle, value, lengths, flow_in return [None, grad, None, flow]
[ "def", "_TensorArraySplitGrad", "(", "op", ",", "flow", ")", ":", "handle", "=", "op", ".", "inputs", "[", "0", "]", "dtype", "=", "op", ".", "get_attr", "(", "\"T\"", ")", "grad_source", "=", "_GetGradSource", "(", "flow", ")", "g", "=", "tensor_array...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/tensor_array_grad.py#L196-L213
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBLaunchInfo.__init__
(self, argv)
__init__(lldb::SBLaunchInfo self, char const ** argv) -> SBLaunchInfo
__init__(lldb::SBLaunchInfo self, char const ** argv) -> SBLaunchInfo
[ "__init__", "(", "lldb", "::", "SBLaunchInfo", "self", "char", "const", "**", "argv", ")", "-", ">", "SBLaunchInfo" ]
def __init__(self, argv): """__init__(lldb::SBLaunchInfo self, char const ** argv) -> SBLaunchInfo""" this = _lldb.new_SBLaunchInfo(argv) try: self.this.append(this) except __builtin__.Exception: self.this = this
[ "def", "__init__", "(", "self", ",", "argv", ")", ":", "this", "=", "_lldb", ".", "new_SBLaunchInfo", "(", "argv", ")", "try", ":", "self", ".", "this", ".", "append", "(", "this", ")", "except", "__builtin__", ".", "Exception", ":", "self", ".", "th...
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L6443-L6449
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/rbd_support/module.py
python
Module.perf_image_stats
(self, pool_spec: Optional[str] = None, sort_by: Optional[ImageSortBy] = None)
Retrieve current RBD IO performance stats
Retrieve current RBD IO performance stats
[ "Retrieve", "current", "RBD", "IO", "performance", "stats" ]
def perf_image_stats(self, pool_spec: Optional[str] = None, sort_by: Optional[ImageSortBy] = None) -> Tuple[int, str, str]: """ Retrieve current RBD IO performance stats """ with self.perf.lock: sort_by_name = sort_by.name if sort_by else OSD_PERF_QUERY_COUNTERS[0] return self.perf.get_perf_stats(pool_spec, sort_by_name)
[ "def", "perf_image_stats", "(", "self", ",", "pool_spec", ":", "Optional", "[", "str", "]", "=", "None", ",", "sort_by", ":", "Optional", "[", "ImageSortBy", "]", "=", "None", ")", "->", "Tuple", "[", "int", ",", "str", ",", "str", "]", ":", "with", ...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/rbd_support/module.py#L130-L138
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLAutoProcess.py
python
ReflectometryILLAutoProcess.compose_polarized_runs_list
(self, angle_index)
return run_inputs, run_names
Returns the lists of runs and names for different flipper configurations at the given angle_index
Returns the lists of runs and names for different flipper configurations at the given angle_index
[ "Returns", "the", "lists", "of", "runs", "and", "names", "for", "different", "flipper", "configurations", "at", "the", "given", "angle_index" ]
def compose_polarized_runs_list(self, angle_index): """Returns the lists of runs and names for different flipper configurations at the given angle_index""" run_inputs = [] run_names = [] if self._rb00: run00_name = self.make_name(self._rb00[angle_index]) + '_00' run00_input = self.compose_run_string(self._rb00[angle_index]) run_names.append(run00_name) run_inputs.append(run00_input) if self._rb01: run01_name = self.make_name(self._rb01[angle_index]) + '_01' run01_input = self.compose_run_string(self._rb01[angle_index]) run_names.append(run01_name) run_inputs.append(run01_input) if self._rb10: run10_name = self.make_name(self._rb10[angle_index]) + '_10' run10_input = self.compose_run_string(self._rb10[angle_index]) run_names.append(run10_name) run_inputs.append(run10_input) if self._rb11: run11_name = self.make_name(self._rb11[angle_index]) + '_11' run11_input = self.compose_run_string(self._rb11[angle_index]) run_names.append(run11_name) run_inputs.append(run11_input) return run_inputs, run_names
[ "def", "compose_polarized_runs_list", "(", "self", ",", "angle_index", ")", ":", "run_inputs", "=", "[", "]", "run_names", "=", "[", "]", "if", "self", ".", "_rb00", ":", "run00_name", "=", "self", ".", "make_name", "(", "self", ".", "_rb00", "[", "angle...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLAutoProcess.py#L792-L816
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/module.py
python
ModuleRef.name
(self)
return _decode_string(ffi.lib.LLVMPY_GetModuleName(self))
The module's identifier.
The module's identifier.
[ "The", "module", "s", "identifier", "." ]
def name(self): """ The module's identifier. """ return _decode_string(ffi.lib.LLVMPY_GetModuleName(self))
[ "def", "name", "(", "self", ")", ":", "return", "_decode_string", "(", "ffi", ".", "lib", ".", "LLVMPY_GetModuleName", "(", "self", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/module.py#L119-L123
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/layers/python/layers/layers.py
python
repeat
(inputs, repetitions, layer, *args, **kwargs)
Applies the same layer with the same arguments repeatedly. ```python y = repeat(x, 3, conv2d, 64, [3, 3], scope='conv1') # It is equivalent to: x = conv2d(x, 64, [3, 3], scope='conv1/conv1_1') x = conv2d(x, 64, [3, 3], scope='conv1/conv1_2') y = conv2d(x, 64, [3, 3], scope='conv1/conv1_3') ``` If the `scope` argument is not given in `kwargs`, it is set to `layer.__name__`, or `layer.func.__name__` (for `functools.partial` objects). If neither `__name__` nor `func.__name__` is available, the layers are called with `scope='stack'`. Args: inputs: A `Tensor` suitable for layer. repetitions: Int, number of repetitions. layer: A layer with arguments `(inputs, *args, **kwargs)` *args: Extra args for the layer. **kwargs: Extra kwargs for the layer. Returns: A tensor result of applying the layer, repetitions times. Raises: ValueError: If the op is unknown or wrong.
Applies the same layer with the same arguments repeatedly.
[ "Applies", "the", "same", "layer", "with", "the", "same", "arguments", "repeatedly", "." ]
def repeat(inputs, repetitions, layer, *args, **kwargs): """Applies the same layer with the same arguments repeatedly. ```python y = repeat(x, 3, conv2d, 64, [3, 3], scope='conv1') # It is equivalent to: x = conv2d(x, 64, [3, 3], scope='conv1/conv1_1') x = conv2d(x, 64, [3, 3], scope='conv1/conv1_2') y = conv2d(x, 64, [3, 3], scope='conv1/conv1_3') ``` If the `scope` argument is not given in `kwargs`, it is set to `layer.__name__`, or `layer.func.__name__` (for `functools.partial` objects). If neither `__name__` nor `func.__name__` is available, the layers are called with `scope='stack'`. Args: inputs: A `Tensor` suitable for layer. repetitions: Int, number of repetitions. layer: A layer with arguments `(inputs, *args, **kwargs)` *args: Extra args for the layer. **kwargs: Extra kwargs for the layer. Returns: A tensor result of applying the layer, repetitions times. Raises: ValueError: If the op is unknown or wrong. """ scope = kwargs.pop('scope', None) with variable_scope.variable_scope(scope, 'Repeat', [inputs]): inputs = ops.convert_to_tensor(inputs) if scope is None: if hasattr(layer, '__name__'): scope = layer.__name__ elif hasattr(layer, 'func') and hasattr(layer.func, '__name__'): scope = layer.func.__name__ # In case layer is a functools.partial. else: scope = 'repeat' outputs = inputs for i in range(repetitions): kwargs['scope'] = scope + '_' + str(i+1) outputs = layer(outputs, *args, **kwargs) return outputs
[ "def", "repeat", "(", "inputs", ",", "repetitions", ",", "layer", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "scope", "=", "kwargs", ".", "pop", "(", "'scope'", ",", "None", ")", "with", "variable_scope", ".", "variable_scope", "(", "scope", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/layers/python/layers/layers.py#L2320-L2363
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_cocoa/gizmos.py
python
DynamicSashUnifyEvent.__init__
(self, *args, **kwargs)
__init__(self, Object target) -> DynamicSashUnifyEvent
__init__(self, Object target) -> DynamicSashUnifyEvent
[ "__init__", "(", "self", "Object", "target", ")", "-", ">", "DynamicSashUnifyEvent" ]
def __init__(self, *args, **kwargs): """__init__(self, Object target) -> DynamicSashUnifyEvent""" _gizmos.DynamicSashUnifyEvent_swiginit(self,_gizmos.new_DynamicSashUnifyEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gizmos", ".", "DynamicSashUnifyEvent_swiginit", "(", "self", ",", "_gizmos", ".", "new_DynamicSashUnifyEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_cocoa/gizmos.py#L85-L87
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/android/loading/cloud/frontend/memory_logs.py
python
MemoryLogs.Flush
(self)
return result
Stops collecting the logs and returns the logs collected since Start() was called.
Stops collecting the logs and returns the logs collected since Start() was called.
[ "Stops", "collecting", "the", "logs", "and", "returns", "the", "logs", "collected", "since", "Start", "()", "was", "called", "." ]
def Flush(self): """Stops collecting the logs and returns the logs collected since Start() was called. """ self._logger.removeHandler(self._log_handler) self._log_handler.flush() self._log_buffer.flush() result = self._log_buffer.getvalue() self._log_buffer.truncate(0) return result
[ "def", "Flush", "(", "self", ")", ":", "self", ".", "_logger", ".", "removeHandler", "(", "self", ".", "_log_handler", ")", "self", ".", "_log_handler", ".", "flush", "(", ")", "self", ".", "_log_buffer", ".", "flush", "(", ")", "result", "=", "self", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/cloud/frontend/memory_logs.py#L24-L33
apple/swift-clang
d7403439fc6641751840b723e7165fb02f52db95
bindings/python/clang/cindex.py
python
TranslationUnit.cursor
(self)
return conf.lib.clang_getTranslationUnitCursor(self)
Retrieve the cursor that represents the given translation unit.
Retrieve the cursor that represents the given translation unit.
[ "Retrieve", "the", "cursor", "that", "represents", "the", "given", "translation", "unit", "." ]
def cursor(self): """Retrieve the cursor that represents the given translation unit.""" return conf.lib.clang_getTranslationUnitCursor(self)
[ "def", "cursor", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getTranslationUnitCursor", "(", "self", ")" ]
https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L2877-L2879
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xpathParserContext.xpathNotFunction
(self, nargs)
Implement the not() XPath function boolean not(boolean) The not function returns true if its argument is false, and false otherwise.
Implement the not() XPath function boolean not(boolean) The not function returns true if its argument is false, and false otherwise.
[ "Implement", "the", "not", "()", "XPath", "function", "boolean", "not", "(", "boolean", ")", "The", "not", "function", "returns", "true", "if", "its", "argument", "is", "false", "and", "false", "otherwise", "." ]
def xpathNotFunction(self, nargs): """Implement the not() XPath function boolean not(boolean) The not function returns true if its argument is false, and false otherwise. """ libxml2mod.xmlXPathNotFunction(self._o, nargs)
[ "def", "xpathNotFunction", "(", "self", ",", "nargs", ")", ":", "libxml2mod", ".", "xmlXPathNotFunction", "(", "self", ".", "_o", ",", "nargs", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L6990-L6994
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/expressions/leaf.py
python
Leaf.is_pwl
(self)
return True
Leaf nodes are always piecewise linear.
Leaf nodes are always piecewise linear.
[ "Leaf", "nodes", "are", "always", "piecewise", "linear", "." ]
def is_pwl(self) -> bool: """Leaf nodes are always piecewise linear. """ return True
[ "def", "is_pwl", "(", "self", ")", "->", "bool", ":", "return", "True" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/expressions/leaf.py#L458-L461
johmathe/shotdetect
1ecf93a695c96fd7601a41ab5834f1117b9d7d50
tools/cpplint.py
python
FileInfo.RepositoryName
(self)
return fullname
FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors.
FullName after removing the local path to the repository.
[ "FullName", "after", "removing", "the", "local", "path", "to", "the", "repository", "." ]
def RepositoryName(self): """FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors. """ fullname = self.FullName() if os.path.exists(fullname): project_dir = os.path.dirname(fullname) if os.path.exists(os.path.join(project_dir, ".svn")): # If there's a .svn file in the current directory, we recursively look # up the directory tree for the top of the SVN checkout root_dir = project_dir one_up_dir = os.path.dirname(root_dir) while os.path.exists(os.path.join(one_up_dir, ".svn")): root_dir = os.path.dirname(root_dir) one_up_dir = os.path.dirname(one_up_dir) prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by # searching up from the current path. root_dir = os.path.dirname(fullname) while (root_dir != os.path.dirname(root_dir) and not os.path.exists(os.path.join(root_dir, ".git")) and not os.path.exists(os.path.join(root_dir, ".hg")) and not os.path.exists(os.path.join(root_dir, ".svn"))): root_dir = os.path.dirname(root_dir) if (os.path.exists(os.path.join(root_dir, ".git")) or os.path.exists(os.path.join(root_dir, ".hg")) or os.path.exists(os.path.join(root_dir, ".svn"))): prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Don't know what to do; header guard warnings may be wrong... return fullname
[ "def", "RepositoryName", "(", "self", ")", ":", "fullname", "=", "self", ".", "FullName", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "fullname", ")", ":", "project_dir", "=", "os", ".", "path", ".", "dirname", "(", "fullname", ")", "if", ...
https://github.com/johmathe/shotdetect/blob/1ecf93a695c96fd7601a41ab5834f1117b9d7d50/tools/cpplint.py#L689-L732
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Node/FS.py
python
File._morph
(self)
Turn a file system node into a File object.
Turn a file system node into a File object.
[ "Turn", "a", "file", "system", "node", "into", "a", "File", "object", "." ]
def _morph(self): """Turn a file system node into a File object.""" self.scanner_paths = {} if not hasattr(self, '_local'): self._local = 0 if not hasattr(self, 'released_target_info'): self.released_target_info = False self.store_info = 1 self._func_exists = 4 self._func_get_contents = 3 # Initialize this Node's decider function to decide_source() because # every file is a source file until it has a Builder attached... self.changed_since_last_build = 4 # If there was already a Builder set on this entry, then # we need to make sure we call the target-decider function, # not the source-decider. Reaching in and doing this by hand # is a little bogus. We'd prefer to handle this by adding # an Entry.builder_set() method that disambiguates like the # other methods, but that starts running into problems with the # fragile way we initialize Dir Nodes with their Mkdir builders, # yet still allow them to be overridden by the user. Since it's # not clear right now how to fix that, stick with what works # until it becomes clear... if self.has_builder(): self.changed_since_last_build = 5
[ "def", "_morph", "(", "self", ")", ":", "self", ".", "scanner_paths", "=", "{", "}", "if", "not", "hasattr", "(", "self", ",", "'_local'", ")", ":", "self", ".", "_local", "=", "0", "if", "not", "hasattr", "(", "self", ",", "'released_target_info'", ...
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/FS.py#L2664-L2691
0ad/0ad
f58db82e0e925016d83f4e3fa7ca599e3866e2af
source/tools/fontbuilder2/Packer.py
python
CygonRectanglePacker.__init__
(self, packingAreaWidth, packingAreaHeight)
Initializes a new rectangle packer packingAreaWidth: Maximum width of the packing area packingAreaHeight: Maximum height of the packing area
Initializes a new rectangle packer packingAreaWidth: Maximum width of the packing area packingAreaHeight: Maximum height of the packing area
[ "Initializes", "a", "new", "rectangle", "packer", "packingAreaWidth", ":", "Maximum", "width", "of", "the", "packing", "area", "packingAreaHeight", ":", "Maximum", "height", "of", "the", "packing", "area" ]
def __init__(self, packingAreaWidth, packingAreaHeight): """Initializes a new rectangle packer packingAreaWidth: Maximum width of the packing area packingAreaHeight: Maximum height of the packing area""" RectanglePacker.__init__(self, packingAreaWidth, packingAreaHeight) # Stores the height silhouette of the rectangles self.heightSlices = [] # At the beginning, the packing area is a single slice of height 0 self.heightSlices.append(Point(0,0))
[ "def", "__init__", "(", "self", ",", "packingAreaWidth", ",", "packingAreaHeight", ")", ":", "RectanglePacker", ".", "__init__", "(", "self", ",", "packingAreaWidth", ",", "packingAreaHeight", ")", "# Stores the height silhouette of the rectangles", "self", ".", "height...
https://github.com/0ad/0ad/blob/f58db82e0e925016d83f4e3fa7ca599e3866e2af/source/tools/fontbuilder2/Packer.py#L111-L122
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
MultiChoiceDialog.SetSelections
(*args, **kwargs)
return _windows_.MultiChoiceDialog_SetSelections(*args, **kwargs)
SetSelections(List selections) Specify the items in the list that should be selected, using a list of integers. The list should specify the indexes of the items that should be selected.
SetSelections(List selections)
[ "SetSelections", "(", "List", "selections", ")" ]
def SetSelections(*args, **kwargs): """ SetSelections(List selections) Specify the items in the list that should be selected, using a list of integers. The list should specify the indexes of the items that should be selected. """ return _windows_.MultiChoiceDialog_SetSelections(*args, **kwargs)
[ "def", "SetSelections", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "MultiChoiceDialog_SetSelections", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L3303-L3311
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/error_interpolation.py
python
create_graph_debug_info_def
(func_named_operations)
return graph_debug_info_def
Construct and returns a `GraphDebugInfo` protocol buffer. Args: func_named_operations: An iterable of (func_name, op.Operation) tuples where the Operation instances have a _traceback members. The func_name should be the empty string for operations in the top-level Graph. Returns: GraphDebugInfo protocol buffer. Raises: TypeError: If the arguments are not of the correct proto buffer type.
Construct and returns a `GraphDebugInfo` protocol buffer.
[ "Construct", "and", "returns", "a", "GraphDebugInfo", "protocol", "buffer", "." ]
def create_graph_debug_info_def(func_named_operations): """Construct and returns a `GraphDebugInfo` protocol buffer. Args: func_named_operations: An iterable of (func_name, op.Operation) tuples where the Operation instances have a _traceback members. The func_name should be the empty string for operations in the top-level Graph. Returns: GraphDebugInfo protocol buffer. Raises: TypeError: If the arguments are not of the correct proto buffer type. """ # Creates an empty GraphDebugInfoDef proto. graph_debug_info_def = graph_debug_info_pb2.GraphDebugInfo() # Gets the file names and line numbers for the exported node names. Also # collects the unique file names. all_file_names = set() node_to_trace = {} for func_name, op in func_named_operations: try: op_traceback = op.traceback except AttributeError: # Some ops synthesized on as part of function or control flow definition # do not have tracebacks. continue # Gets the stack trace of the operation and then the file location. node_name = op.name + "@" + func_name node_to_trace[node_name] = _compute_useful_frames(op_traceback, 10) for frame in node_to_trace[node_name]: all_file_names.add(frame.filename) # Sets the `files` field in the GraphDebugInfo proto graph_debug_info_def.files.extend(all_file_names) # Builds a mapping between file names and index of the `files` field, so we # only store the indexes for the nodes in the GraphDebugInfo. file_to_index = dict( [(y, x) for x, y in enumerate(graph_debug_info_def.files)]) # Creates the FileLineCol proto for each node and sets the value in the # GraphDebugInfo proto. We only store the file name index for each node to # save the storage space. for node_name, frames in node_to_trace.items(): trace_def = graph_debug_info_def.traces[node_name] for frame in reversed(frames): trace_def.file_line_cols.add( file_index=file_to_index[frame.filename], line=frame.lineno) return graph_debug_info_def
[ "def", "create_graph_debug_info_def", "(", "func_named_operations", ")", ":", "# Creates an empty GraphDebugInfoDef proto.", "graph_debug_info_def", "=", "graph_debug_info_pb2", ".", "GraphDebugInfo", "(", ")", "# Gets the file names and line numbers for the exported node names. Also", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/error_interpolation.py#L295-L348
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/make_archive.py
python
make_tar_archive
(opts)
Given the parsed options, generates the 'opt.output_filename' tarball containing all the files in 'opt.input_filename' renamed according to the mappings in 'opts.transformations'. e.g. for an input file named "a/mongo/build/DISTSRC", and an existing transformation {"a/mongo/build": "release"}, the input file will be written to the tarball as "release/DISTSRC" All files to be compressed are copied into new directories as required by 'opts.transformations'. Once the tarball has been created, all temporary directory structures created for the purposes of compressing, are removed.
Given the parsed options, generates the 'opt.output_filename' tarball containing all the files in 'opt.input_filename' renamed according to the mappings in 'opts.transformations'.
[ "Given", "the", "parsed", "options", "generates", "the", "opt", ".", "output_filename", "tarball", "containing", "all", "the", "files", "in", "opt", ".", "input_filename", "renamed", "according", "to", "the", "mappings", "in", "opts", ".", "transformations", "."...
def make_tar_archive(opts): '''Given the parsed options, generates the 'opt.output_filename' tarball containing all the files in 'opt.input_filename' renamed according to the mappings in 'opts.transformations'. e.g. for an input file named "a/mongo/build/DISTSRC", and an existing transformation {"a/mongo/build": "release"}, the input file will be written to the tarball as "release/DISTSRC" All files to be compressed are copied into new directories as required by 'opts.transformations'. Once the tarball has been created, all temporary directory structures created for the purposes of compressing, are removed. ''' tar_options = "cvf" if opts.archive_format is 'tgz': tar_options += "z" # clean and create a temp directory to copy files to enclosing_archive_directory = tempfile.mkdtemp( prefix='archive_', dir=os.path.abspath('build') ) output_tarfile = os.path.join(os.getcwd(), opts.output_filename) tar_command = ["tar", tar_options, output_tarfile] for input_filename in opts.input_filenames: preferred_filename = get_preferred_filename(input_filename, opts.transformations) temp_file_location = os.path.join(enclosing_archive_directory, preferred_filename) enclosing_file_directory = os.path.dirname(temp_file_location) if not os.path.exists(enclosing_file_directory): os.makedirs(enclosing_file_directory) print "copying %s => %s" % (input_filename, temp_file_location) if os.path.isdir(input_filename): shutil.copytree(input_filename, temp_file_location) else: shutil.copy2(input_filename, temp_file_location) tar_command.append(preferred_filename) print " ".join(tar_command) # execute the full tar command run_directory = os.path.join(os.getcwd(), enclosing_archive_directory) proc = Popen(tar_command, stdout=PIPE, stderr=STDOUT, bufsize=0, cwd=run_directory) proc.wait() # delete temp directory delete_directory(enclosing_archive_directory)
[ "def", "make_tar_archive", "(", "opts", ")", ":", "tar_options", "=", "\"cvf\"", "if", "opts", ".", "archive_format", "is", "'tgz'", ":", "tar_options", "+=", "\"z\"", "# clean and create a temp directory to copy files to", "enclosing_archive_directory", "=", "tempfile", ...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/make_archive.py#L65-L112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/frame.py
python
DataFrame.lookup
(self, row_labels, col_labels)
return result
Label-based "fancy indexing" function for DataFrame. Given equal-length arrays of row and column labels, return an array of the values corresponding to each (row, col) pair. Parameters ---------- row_labels : sequence The row labels to use for lookup. col_labels : sequence The column labels to use for lookup. Returns ------- numpy.ndarray Examples -------- values : ndarray The found values
Label-based "fancy indexing" function for DataFrame.
[ "Label", "-", "based", "fancy", "indexing", "function", "for", "DataFrame", "." ]
def lookup(self, row_labels, col_labels) -> np.ndarray: """ Label-based "fancy indexing" function for DataFrame. Given equal-length arrays of row and column labels, return an array of the values corresponding to each (row, col) pair. Parameters ---------- row_labels : sequence The row labels to use for lookup. col_labels : sequence The column labels to use for lookup. Returns ------- numpy.ndarray Examples -------- values : ndarray The found values """ n = len(row_labels) if n != len(col_labels): raise ValueError("Row labels must have same size as column labels") thresh = 1000 if not self._is_mixed_type or n > thresh: values = self.values ridx = self.index.get_indexer(row_labels) cidx = self.columns.get_indexer(col_labels) if (ridx == -1).any(): raise KeyError("One or more row labels was not found") if (cidx == -1).any(): raise KeyError("One or more column labels was not found") flat_index = ridx * len(self.columns) + cidx result = values.flat[flat_index] else: result = np.empty(n, dtype="O") for i, (r, c) in enumerate(zip(row_labels, col_labels)): result[i] = self._get_value(r, c) if is_object_dtype(result): result = lib.maybe_convert_objects(result) return result
[ "def", "lookup", "(", "self", ",", "row_labels", ",", "col_labels", ")", "->", "np", ".", "ndarray", ":", "n", "=", "len", "(", "row_labels", ")", "if", "n", "!=", "len", "(", "col_labels", ")", ":", "raise", "ValueError", "(", "\"Row labels must have sa...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/frame.py#L3681-L3727
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py
python
_shorten_line_at_tokens_new
(tokens, source, indentation, max_line_length)
Shorten the line taking its length into account. The input is expected to be free of newlines except for inside multiline strings and at the end.
Shorten the line taking its length into account.
[ "Shorten", "the", "line", "taking", "its", "length", "into", "account", "." ]
def _shorten_line_at_tokens_new(tokens, source, indentation, max_line_length): """Shorten the line taking its length into account. The input is expected to be free of newlines except for inside multiline strings and at the end. """ # Yield the original source so to see if it's a better choice than the # shortened candidate lines we generate here. yield indentation + source parsed_tokens = _parse_tokens(tokens) if parsed_tokens: # Perform two reflows. The first one starts on the same line as the # prefix. The second starts on the line after the prefix. fixed = _reflow_lines(parsed_tokens, indentation, max_line_length, start_on_prefix_line=True) if fixed and check_syntax(normalize_multiline(fixed.lstrip())): yield fixed fixed = _reflow_lines(parsed_tokens, indentation, max_line_length, start_on_prefix_line=False) if fixed and check_syntax(normalize_multiline(fixed.lstrip())): yield fixed
[ "def", "_shorten_line_at_tokens_new", "(", "tokens", ",", "source", ",", "indentation", ",", "max_line_length", ")", ":", "# Yield the original source so to see if it's a better choice than the", "# shortened candidate lines we generate here.", "yield", "indentation", "+", "source"...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py#L2221-L2246
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/ops/array_ops.py
python
na_arithmetic_op
(left, right, op, str_rep: str)
return missing.dispatch_fill_zeros(op, left, right, result)
Return the result of evaluating op on the passed in values. If native types are not compatible, try coersion to object dtype. Parameters ---------- left : np.ndarray right : np.ndarray or scalar str_rep : str or None Returns ------- array-like Raises ------ TypeError : invalid operation
Return the result of evaluating op on the passed in values.
[ "Return", "the", "result", "of", "evaluating", "op", "on", "the", "passed", "in", "values", "." ]
def na_arithmetic_op(left, right, op, str_rep: str): """ Return the result of evaluating op on the passed in values. If native types are not compatible, try coersion to object dtype. Parameters ---------- left : np.ndarray right : np.ndarray or scalar str_rep : str or None Returns ------- array-like Raises ------ TypeError : invalid operation """ import pandas.core.computation.expressions as expressions try: result = expressions.evaluate(op, str_rep, left, right) except TypeError: result = masked_arith_op(left, right, op) return missing.dispatch_fill_zeros(op, left, right, result)
[ "def", "na_arithmetic_op", "(", "left", ",", "right", ",", "op", ",", "str_rep", ":", "str", ")", ":", "import", "pandas", ".", "core", ".", "computation", ".", "expressions", "as", "expressions", "try", ":", "result", "=", "expressions", ".", "evaluate", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/ops/array_ops.py#L126-L153
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/ndarray/ndarray.py
python
NDArray.arccos
(self, *args, **kwargs)
return op.arccos(self, *args, **kwargs)
Convenience fluent method for :py:func:`arccos`. The arguments are the same as for :py:func:`arccos`, with this array as data.
Convenience fluent method for :py:func:`arccos`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "arccos", "." ]
def arccos(self, *args, **kwargs): """Convenience fluent method for :py:func:`arccos`. The arguments are the same as for :py:func:`arccos`, with this array as data. """ return op.arccos(self, *args, **kwargs)
[ "def", "arccos", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "arccos", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/ndarray/ndarray.py#L1340-L1346
CanalTP/navitia
cb84ce9859070187e708818b058e6a7e0b7f891b
source/jormungandr/jormungandr/authentication.py
python
get_used_coverages
()
return the list of coverages used to generate the response
return the list of coverages used to generate the response
[ "return", "the", "list", "of", "coverages", "used", "to", "generate", "the", "response" ]
def get_used_coverages(): """ return the list of coverages used to generate the response """ if request.view_args and 'region' in request.view_args: return [request.view_args['region']] elif hasattr(g, 'used_coverages'): return g.used_coverages else: return []
[ "def", "get_used_coverages", "(", ")", ":", "if", "request", ".", "view_args", "and", "'region'", "in", "request", ".", "view_args", ":", "return", "[", "request", ".", "view_args", "[", "'region'", "]", "]", "elif", "hasattr", "(", "g", ",", "'used_covera...
https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/jormungandr/jormungandr/authentication.py#L291-L300
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/blocks.py
python
FinalBlock.__init__
(self, config)
Initialization. Args: config: tf.contrib.training.HParams object; specifies hyperparameters Raises: ValueError: Unsupported data format
Initialization.
[ "Initialization", "." ]
def __init__(self, config): """Initialization. Args: config: tf.contrib.training.HParams object; specifies hyperparameters Raises: ValueError: Unsupported data format """ super(FinalBlock, self).__init__(dtype=config.dtype) self.config = config self.axis = 1 if self.config.data_format == "channels_first" else 3 f = self.config.filters[-1] # Number of filters r = functools.reduce(operator.mul, self.config.strides, 1) # Reduce ratio r *= self.config.init_stride if self.config.init_max_pool: r *= 2 if self.config.data_format == "channels_first": w, h = self.config.input_shape[1], self.config.input_shape[2] input_shape = (f, w // r, h // r) elif self.config.data_format == "channels_last": w, h = self.config.input_shape[0], self.config.input_shape[1] input_shape = (w // r, h // r, f) else: raise ValueError("Data format should be either `channels_first`" " or `channels_last`") self.batch_norm = tf.keras.layers.BatchNormalization( axis=self.axis, input_shape=input_shape, fused=self.config.fused, dtype=self.config.dtype) self.activation = tf.keras.layers.Activation("relu", dtype=self.config.dtype) self.global_avg_pool = tf.keras.layers.GlobalAveragePooling2D( data_format=self.config.data_format, dtype=self.config.dtype) self.dense = tf.keras.layers.Dense( self.config.n_classes, dtype=self.config.dtype)
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "super", "(", "FinalBlock", ",", "self", ")", ".", "__init__", "(", "dtype", "=", "config", ".", "dtype", ")", "self", ".", "config", "=", "config", "self", ".", "axis", "=", "1", "if", "self...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/blocks.py#L459-L497
cmu-db/noisepage
79276e68fe83322f1249e8a8be96bd63c583ae56
build-support/cpplint.py
python
_SetVerboseLevel
(level)
return _cpplint_state.SetVerboseLevel(level)
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level)
[ "def", "_SetVerboseLevel", "(", "level", ")", ":", "return", "_cpplint_state", ".", "SetVerboseLevel", "(", "level", ")" ]
https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/cpplint.py#L1194-L1196
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/managers.py
python
Server.debug_info
(self, c)
Return some info --- useful to spot problems with refcounting
Return some info --- useful to spot problems with refcounting
[ "Return", "some", "info", "---", "useful", "to", "spot", "problems", "with", "refcounting" ]
def debug_info(self, c): ''' Return some info --- useful to spot problems with refcounting ''' self.mutex.acquire() try: result = [] keys = self.id_to_obj.keys() keys.sort() for ident in keys: if ident != '0': result.append(' %s: refcount=%s\n %s' % (ident, self.id_to_refcount[ident], str(self.id_to_obj[ident][0])[:75])) return '\n'.join(result) finally: self.mutex.release()
[ "def", "debug_info", "(", "self", ",", "c", ")", ":", "self", ".", "mutex", ".", "acquire", "(", ")", "try", ":", "result", "=", "[", "]", "keys", "=", "self", ".", "id_to_obj", ".", "keys", "(", ")", "keys", ".", "sort", "(", ")", "for", "iden...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/managers.py#L317-L333
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiToolBarItem.GetMinSize
(*args, **kwargs)
return _aui.AuiToolBarItem_GetMinSize(*args, **kwargs)
GetMinSize(self) -> Size
GetMinSize(self) -> Size
[ "GetMinSize", "(", "self", ")", "-", ">", "Size" ]
def GetMinSize(*args, **kwargs): """GetMinSize(self) -> Size""" return _aui.AuiToolBarItem_GetMinSize(*args, **kwargs)
[ "def", "GetMinSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiToolBarItem_GetMinSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L1821-L1823
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/calendar.py
python
Calendar.monthdatescalendar
(self, year, month)
return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values.
Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values.
[ "Return", "a", "matrix", "(", "list", "of", "lists", ")", "representing", "a", "month", "s", "calendar", ".", "Each", "row", "represents", "a", "week", ";", "week", "entries", "are", "datetime", ".", "date", "values", "." ]
def monthdatescalendar(self, year, month): """ Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values. """ dates = list(self.itermonthdates(year, month)) return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
[ "def", "monthdatescalendar", "(", "self", ",", "year", ",", "month", ")", ":", "dates", "=", "list", "(", "self", ".", "itermonthdates", "(", "year", ",", "month", ")", ")", "return", "[", "dates", "[", "i", ":", "i", "+", "7", "]", "for", "i", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/calendar.py#L195-L201
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/third_party/jinja2/parser.py
python
Parser.parse
(self)
return result
Parse the whole template into a `Template` node.
Parse the whole template into a `Template` node.
[ "Parse", "the", "whole", "template", "into", "a", "Template", "node", "." ]
def parse(self): """Parse the whole template into a `Template` node.""" result = nodes.Template(self.subparse(), lineno=1) result.set_environment(self.environment) return result
[ "def", "parse", "(", "self", ")", ":", "result", "=", "nodes", ".", "Template", "(", "self", ".", "subparse", "(", ")", ",", "lineno", "=", "1", ")", "result", ".", "set_environment", "(", "self", ".", "environment", ")", "return", "result" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/parser.py#L899-L903
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/wsgiref/simple_server.py
python
WSGIRequestHandler.handle
(self)
Handle a single HTTP request
Handle a single HTTP request
[ "Handle", "a", "single", "HTTP", "request" ]
def handle(self): """Handle a single HTTP request""" self.raw_requestline = self.rfile.readline() if not self.parse_request(): # An error code has been sent, just exit return handler = ServerHandler( self.rfile, self.wfile, self.get_stderr(), self.get_environ() ) handler.request_handler = self # backpointer for logging handler.run(self.server.get_app())
[ "def", "handle", "(", "self", ")", ":", "self", ".", "raw_requestline", "=", "self", ".", "rfile", ".", "readline", "(", ")", "if", "not", "self", ".", "parse_request", "(", ")", ":", "# An error code has been sent, just exit", "return", "handler", "=", "Ser...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/wsgiref/simple_server.py#L127-L138
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/importlib-metadata/py3/importlib_metadata/__init__.py
python
Distribution.requires
(self)
return reqs and list(reqs)
Generated requirements specified for this Distribution
Generated requirements specified for this Distribution
[ "Generated", "requirements", "specified", "for", "this", "Distribution" ]
def requires(self): """Generated requirements specified for this Distribution""" reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs() return reqs and list(reqs)
[ "def", "requires", "(", "self", ")", ":", "reqs", "=", "self", ".", "_read_dist_info_reqs", "(", ")", "or", "self", ".", "_read_egg_info_reqs", "(", ")", "return", "reqs", "and", "list", "(", "reqs", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/importlib-metadata/py3/importlib_metadata/__init__.py#L661-L664
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/_flagship.py
python
SyntaxData.GetProperties
(self)
return [FOLD]
Returns a list of Extra Properties to set
Returns a list of Extra Properties to set
[ "Returns", "a", "list", "of", "Extra", "Properties", "to", "set" ]
def GetProperties(self): """Returns a list of Extra Properties to set """ return [FOLD]
[ "def", "GetProperties", "(", "self", ")", ":", "return", "[", "FOLD", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_flagship.py#L176-L178
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
FontPickerEvent.SetFont
(*args, **kwargs)
return _controls_.FontPickerEvent_SetFont(*args, **kwargs)
SetFont(self, Font c)
SetFont(self, Font c)
[ "SetFont", "(", "self", "Font", "c", ")" ]
def SetFont(*args, **kwargs): """SetFont(self, Font c)""" return _controls_.FontPickerEvent_SetFont(*args, **kwargs)
[ "def", "SetFont", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "FontPickerEvent_SetFont", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L7197-L7199
bairdzhang/smallhardface
76fa1d87a9602d9b13d7a7fe693fc7aec91cab80
external/marcopede-face-eval-f2870fd85d48/loadData.py
python
loadDetections
(fn)
return dets
load detections from fn in the different formats
load detections from fn in the different formats
[ "load", "detections", "from", "fn", "in", "the", "different", "formats" ]
def loadDetections(fn): """ load detections from fn in the different formats """ dets = [] print ("loading ", fn) if os.path.splitext(fn)[1] == ".txt": dets = loadDetectionsPascalFormat(fn) elif os.path.splitext(fn)[1] == ".ramananmat": dets = loadDetectionsRamanan(fn) elif os.path.splitext(fn)[1] == ".shenmat": dets = loadDetectionsShen(fn) elif os.path.splitext(fn)[1] == ".mat": dets = loadDetectionsYann(fn) elif os.path.splitext(fn)[1] == ".csv": dets = loadDetectionsCSV(fn) else: print (fn) raise Exception("Detection file format not supported") return dets
[ "def", "loadDetections", "(", "fn", ")", ":", "dets", "=", "[", "]", "print", "(", "\"loading \"", ",", "fn", ")", "if", "os", ".", "path", ".", "splitext", "(", "fn", ")", "[", "1", "]", "==", "\".txt\"", ":", "dets", "=", "loadDetectionsPascalForma...
https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/external/marcopede-face-eval-f2870fd85d48/loadData.py#L13-L33
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/gyb.py
python
split_lines
(s)
return [line + '\n' for line in s.split('\n')]
Split s into a list of lines, each of which has a trailing newline If the lines are later concatenated, the result is s, possibly with a single appended newline.
Split s into a list of lines, each of which has a trailing newline
[ "Split", "s", "into", "a", "list", "of", "lines", "each", "of", "which", "has", "a", "trailing", "newline" ]
def split_lines(s): """Split s into a list of lines, each of which has a trailing newline If the lines are later concatenated, the result is s, possibly with a single appended newline. """ return [line + '\n' for line in s.split('\n')]
[ "def", "split_lines", "(", "s", ")", ":", "return", "[", "line", "+", "'\\n'", "for", "line", "in", "s", ".", "split", "(", "'\\n'", ")", "]" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/gyb.py#L49-L55
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.WordPartRightExtend
(*args, **kwargs)
return _stc.StyledTextCtrl_WordPartRightExtend(*args, **kwargs)
WordPartRightExtend(self) Move to the next change in capitalisation extending selection to new caret position.
WordPartRightExtend(self)
[ "WordPartRightExtend", "(", "self", ")" ]
def WordPartRightExtend(*args, **kwargs): """ WordPartRightExtend(self) Move to the next change in capitalisation extending selection to new caret position. """ return _stc.StyledTextCtrl_WordPartRightExtend(*args, **kwargs)
[ "def", "WordPartRightExtend", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_WordPartRightExtend", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L5128-L5135
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/hsadrv/driver.py
python
Stream.auto_synchronize
(self)
A context manager that waits for all commands in this stream to execute and commits any pending memory transfers upon exiting the context.
A context manager that waits for all commands in this stream to execute and commits any pending memory transfers upon exiting the context.
[ "A", "context", "manager", "that", "waits", "for", "all", "commands", "in", "this", "stream", "to", "execute", "and", "commits", "any", "pending", "memory", "transfers", "upon", "exiting", "the", "context", "." ]
def auto_synchronize(self): ''' A context manager that waits for all commands in this stream to execute and commits any pending memory transfers upon exiting the context. ''' yield self self.synchronize()
[ "def", "auto_synchronize", "(", "self", ")", ":", "yield", "self", "self", ".", "synchronize", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/hsadrv/driver.py#L1391-L1397
BSVino/DoubleAction
c550b168a3e919926c198c30240f506538b92e75
mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py
python
_AddInitMethod
(message_descriptor, cls)
Adds an __init__ method to cls.
Adds an __init__ method to cls.
[ "Adds", "an", "__init__", "method", "to", "cls", "." ]
def _AddInitMethod(message_descriptor, cls): """Adds an __init__ method to cls.""" fields = message_descriptor.fields def init(self, **kwargs): self._cached_byte_size = 0 self._cached_byte_size_dirty = False self._fields = {} self._is_present_in_parent = False self._listener = message_listener_mod.NullMessageListener() self._listener_for_children = _Listener(self) for field_name, field_value in kwargs.iteritems(): field = _GetFieldByName(message_descriptor, field_name) if field is None: raise TypeError("%s() got an unexpected keyword argument '%s'" % (message_descriptor.name, field_name)) if field.label == _FieldDescriptor.LABEL_REPEATED: copy = field._default_constructor(self) if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: # Composite for val in field_value: copy.add().MergeFrom(val) else: # Scalar copy.extend(field_value) self._fields[field] = copy elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: copy = field._default_constructor(self) copy.MergeFrom(field_value) self._fields[field] = copy else: self._fields[field] = field_value init.__module__ = None init.__doc__ = None cls.__init__ = init
[ "def", "_AddInitMethod", "(", "message_descriptor", ",", "cls", ")", ":", "fields", "=", "message_descriptor", ".", "fields", "def", "init", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_cached_byte_size", "=", "0", "self", ".", "_cached_b...
https://github.com/BSVino/DoubleAction/blob/c550b168a3e919926c198c30240f506538b92e75/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L359-L391
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/misc/pilutil.py
python
imfilter
(arr, ftype)
return fromimage(im.filter(_tdict[ftype]))
Simple filtering of an image. This function is only available if Python Imaging Library (PIL) is installed. .. warning:: This function uses `bytescale` under the hood to rescale images to use the full (0, 255) range if ``mode`` is one of ``None, 'L', 'P', 'l'``. It will also cast data for 2-D images to ``uint32`` for ``mode=None`` (which is the default). Parameters ---------- arr : ndarray The array of Image in which the filter is to be applied. ftype : str The filter that has to be applied. Legal values are: 'blur', 'contour', 'detail', 'edge_enhance', 'edge_enhance_more', 'emboss', 'find_edges', 'smooth', 'smooth_more', 'sharpen'. Returns ------- imfilter : ndarray The array with filter applied. Raises ------ ValueError *Unknown filter type.* If the filter you are trying to apply is unsupported.
Simple filtering of an image.
[ "Simple", "filtering", "of", "an", "image", "." ]
def imfilter(arr, ftype): """ Simple filtering of an image. This function is only available if Python Imaging Library (PIL) is installed. .. warning:: This function uses `bytescale` under the hood to rescale images to use the full (0, 255) range if ``mode`` is one of ``None, 'L', 'P', 'l'``. It will also cast data for 2-D images to ``uint32`` for ``mode=None`` (which is the default). Parameters ---------- arr : ndarray The array of Image in which the filter is to be applied. ftype : str The filter that has to be applied. Legal values are: 'blur', 'contour', 'detail', 'edge_enhance', 'edge_enhance_more', 'emboss', 'find_edges', 'smooth', 'smooth_more', 'sharpen'. Returns ------- imfilter : ndarray The array with filter applied. Raises ------ ValueError *Unknown filter type.* If the filter you are trying to apply is unsupported. """ _tdict = {'blur': ImageFilter.BLUR, 'contour': ImageFilter.CONTOUR, 'detail': ImageFilter.DETAIL, 'edge_enhance': ImageFilter.EDGE_ENHANCE, 'edge_enhance_more': ImageFilter.EDGE_ENHANCE_MORE, 'emboss': ImageFilter.EMBOSS, 'find_edges': ImageFilter.FIND_EDGES, 'smooth': ImageFilter.SMOOTH, 'smooth_more': ImageFilter.SMOOTH_MORE, 'sharpen': ImageFilter.SHARPEN } im = toimage(arr) if ftype not in _tdict: raise ValueError("Unknown filter type.") return fromimage(im.filter(_tdict[ftype]))
[ "def", "imfilter", "(", "arr", ",", "ftype", ")", ":", "_tdict", "=", "{", "'blur'", ":", "ImageFilter", ".", "BLUR", ",", "'contour'", ":", "ImageFilter", ".", "CONTOUR", ",", "'detail'", ":", "ImageFilter", ".", "DETAIL", ",", "'edge_enhance'", ":", "I...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/misc/pilutil.py#L572-L621
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/msvs.py
python
_AddActionStep
(actions_dict, inputs, outputs, description, command)
Merge action into an existing list of actions. Care must be taken so that actions which have overlapping inputs either don't get assigned to the same input, or get collapsed into one. Arguments: actions_dict: dictionary keyed on input name, which maps to a list of dicts describing the actions attached to that input file. inputs: list of inputs outputs: list of outputs description: description of the action command: command line to execute
Merge action into an existing list of actions.
[ "Merge", "action", "into", "an", "existing", "list", "of", "actions", "." ]
def _AddActionStep(actions_dict, inputs, outputs, description, command): """Merge action into an existing list of actions. Care must be taken so that actions which have overlapping inputs either don't get assigned to the same input, or get collapsed into one. Arguments: actions_dict: dictionary keyed on input name, which maps to a list of dicts describing the actions attached to that input file. inputs: list of inputs outputs: list of outputs description: description of the action command: command line to execute """ # Require there to be at least one input (call sites will ensure this). assert inputs action = { 'inputs': inputs, 'outputs': outputs, 'description': description, 'command': command, } # Pick where to stick this action. # While less than optimal in terms of build time, attach them to the first # input for now. chosen_input = inputs[0] # Add it there. if chosen_input not in actions_dict: actions_dict[chosen_input] = [] actions_dict[chosen_input].append(action)
[ "def", "_AddActionStep", "(", "actions_dict", ",", "inputs", ",", "outputs", ",", "description", ",", "command", ")", ":", "# Require there to be at least one input (call sites will ensure this).", "assert", "inputs", "action", "=", "{", "'inputs'", ":", "inputs", ",", ...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/msvs.py#L378-L410
alibaba/graph-learn
54cafee9db3054dc310a28b856be7f97c7d5aee9
examples/tf/seal/seal_link_predict.py
python
eval_hits
(y_pred_pos, y_pred_neg, k)
return {'hits@{}'.format(k): hitsK}
compute Hits@K For each positive target node, the negative target nodes are the same. y_pred_neg is an array. rank y_pred_pos[i] against y_pred_neg for each i
compute Hits
[ "compute", "Hits" ]
def eval_hits(y_pred_pos, y_pred_neg, k): ''' compute Hits@K For each positive target node, the negative target nodes are the same. y_pred_neg is an array. rank y_pred_pos[i] against y_pred_neg for each i ''' if len(y_pred_neg) < k or len(y_pred_pos) == 0: return {'hits@{}'.format(k): 1.} kth_score_in_negative_edges = np.sort(y_pred_neg)[-k] hitsK = float(np.sum(y_pred_pos > kth_score_in_negative_edges)) / len(y_pred_pos) return {'hits@{}'.format(k): hitsK}
[ "def", "eval_hits", "(", "y_pred_pos", ",", "y_pred_neg", ",", "k", ")", ":", "if", "len", "(", "y_pred_neg", ")", "<", "k", "or", "len", "(", "y_pred_pos", ")", "==", "0", ":", "return", "{", "'hits@{}'", ".", "format", "(", "k", ")", ":", "1.", ...
https://github.com/alibaba/graph-learn/blob/54cafee9db3054dc310a28b856be7f97c7d5aee9/examples/tf/seal/seal_link_predict.py#L45-L56
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/environment.py
python
Template.get_corresponding_lineno
(self, lineno)
return 1
Return the source line number of a line number in the generated bytecode as they are not in sync.
Return the source line number of a line number in the generated bytecode as they are not in sync.
[ "Return", "the", "source", "line", "number", "of", "a", "line", "number", "in", "the", "generated", "bytecode", "as", "they", "are", "not", "in", "sync", "." ]
def get_corresponding_lineno(self, lineno): """Return the source line number of a line number in the generated bytecode as they are not in sync. """ for template_line, code_line in reversed(self.debug_info): if code_line <= lineno: return template_line return 1
[ "def", "get_corresponding_lineno", "(", "self", ",", "lineno", ")", ":", "for", "template_line", ",", "code_line", "in", "reversed", "(", "self", ".", "debug_info", ")", ":", "if", "code_line", "<=", "lineno", ":", "return", "template_line", "return", "1" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/environment.py#L1108-L1115
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/decoder.py
python
BytesDecoder
(field_number, is_repeated, is_packed, key, new_default)
Returns a decoder for a bytes field.
Returns a decoder for a bytes field.
[ "Returns", "a", "decoder", "for", "a", "bytes", "field", "." ]
def BytesDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a bytes field.""" local_DecodeVarint = _DecodeVarint assert not is_packed if is_repeated: tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) def DecodeRepeatedField(buffer, pos, end, message, field_dict): value = field_dict.get(key) if value is None: value = field_dict.setdefault(key, new_default(message)) while 1: (size, pos) = local_DecodeVarint(buffer, pos) new_pos = pos + size if new_pos > end: raise _DecodeError('Truncated string.') value.append(buffer[pos:new_pos]) # Predict that the next tag is another copy of the same repeated field. pos = new_pos + tag_len if buffer[new_pos:pos] != tag_bytes or new_pos == end: # Prediction failed. Return. return new_pos return DecodeRepeatedField else: def DecodeField(buffer, pos, end, message, field_dict): (size, pos) = local_DecodeVarint(buffer, pos) new_pos = pos + size if new_pos > end: raise _DecodeError('Truncated string.') field_dict[key] = buffer[pos:new_pos] return new_pos return DecodeField
[ "def", "BytesDecoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ",", "key", ",", "new_default", ")", ":", "local_DecodeVarint", "=", "_DecodeVarint", "assert", "not", "is_packed", "if", "is_repeated", ":", "tag_bytes", "=", "encoder", ".", "Tag...
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/decoder.py#L415-L449
kevinlin311tw/Caffe-DeepBinaryCode
9eaa7662be47d49f475ecbeea2bd51be105270d2
scripts/cpp_lint.py
python
ReverseCloseExpression
(clean_lines, linenum, pos)
return (line, 0, -1)
If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ) or } or ] or >, finds the position that opens it.
[ "If", "input", "points", "to", ")", "or", "}", "or", "]", "or", ">", "finds", "the", "position", "that", "opens", "it", "." ]
def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] endchar = line[pos] if endchar not in ')}]>': return (line, 0, -1) if endchar == ')': startchar = '(' if endchar == ']': startchar = '[' if endchar == '}': startchar = '{' if endchar == '>': startchar = '<' # Check last line (start_pos, num_open) = FindStartOfExpressionInLine( line, pos, 0, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, num_open) = FindStartOfExpressionInLine( line, len(line) - 1, num_open, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Did not find startchar before beginning of file, give up return (line, 0, -1)
[ "def", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "endchar", "=", "line", "[", "pos", "]", "if", "endchar", "not", "in", "')}]>'", ":", "return", "("...
https://github.com/kevinlin311tw/Caffe-DeepBinaryCode/blob/9eaa7662be47d49f475ecbeea2bd51be105270d2/scripts/cpp_lint.py#L1327-L1369
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.GetWordChars
(*args, **kwargs)
return _stc.StyledTextCtrl_GetWordChars(*args, **kwargs)
GetWordChars(self) -> String
GetWordChars(self) -> String
[ "GetWordChars", "(", "self", ")", "-", ">", "String" ]
def GetWordChars(*args, **kwargs): """GetWordChars(self) -> String""" return _stc.StyledTextCtrl_GetWordChars(*args, **kwargs)
[ "def", "GetWordChars", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetWordChars", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L2844-L2846
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/contrib/decoder/beam_search_decoder.py
python
BeamSearchDecoder._parent_block
(self)
return parent_block
Getter of parent block. Returns: The parent block of decoder.
Getter of parent block.
[ "Getter", "of", "parent", "block", "." ]
def _parent_block(self): """ Getter of parent block. Returns: The parent block of decoder. """ program = self._helper.main_program parent_block_idx = program.current_block().parent_idx if parent_block_idx < 0: raise ValueError('Invalid block with index %d.' % parent_block_idx) parent_block = program.block(parent_block_idx) return parent_block
[ "def", "_parent_block", "(", "self", ")", ":", "program", "=", "self", ".", "_helper", ".", "main_program", "parent_block_idx", "=", "program", ".", "current_block", "(", ")", ".", "parent_idx", "if", "parent_block_idx", "<", "0", ":", "raise", "ValueError", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/decoder/beam_search_decoder.py#L827-L839
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/common.py
python
needs_i8_conversion
(arr_or_dtype)
return ( is_datetime_or_timedelta_dtype(arr_or_dtype) or is_datetime64tz_dtype(arr_or_dtype) or is_period_dtype(arr_or_dtype) )
Check whether the array or dtype should be converted to int64. An array-like or dtype "needs" such a conversion if the array-like or dtype is of a datetime-like dtype Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype should be converted to int64. Examples -------- >>> needs_i8_conversion(str) False >>> needs_i8_conversion(np.int64) False >>> needs_i8_conversion(np.datetime64) True >>> needs_i8_conversion(np.array(['a', 'b'])) False >>> needs_i8_conversion(pd.Series([1, 2])) False >>> needs_i8_conversion(pd.Series([], dtype="timedelta64[ns]")) True >>> needs_i8_conversion(pd.DatetimeIndex([1, 2, 3], tz="US/Eastern")) True
Check whether the array or dtype should be converted to int64.
[ "Check", "whether", "the", "array", "or", "dtype", "should", "be", "converted", "to", "int64", "." ]
def needs_i8_conversion(arr_or_dtype) -> bool: """ Check whether the array or dtype should be converted to int64. An array-like or dtype "needs" such a conversion if the array-like or dtype is of a datetime-like dtype Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype should be converted to int64. Examples -------- >>> needs_i8_conversion(str) False >>> needs_i8_conversion(np.int64) False >>> needs_i8_conversion(np.datetime64) True >>> needs_i8_conversion(np.array(['a', 'b'])) False >>> needs_i8_conversion(pd.Series([1, 2])) False >>> needs_i8_conversion(pd.Series([], dtype="timedelta64[ns]")) True >>> needs_i8_conversion(pd.DatetimeIndex([1, 2, 3], tz="US/Eastern")) True """ if arr_or_dtype is None: return False return ( is_datetime_or_timedelta_dtype(arr_or_dtype) or is_datetime64tz_dtype(arr_or_dtype) or is_period_dtype(arr_or_dtype) )
[ "def", "needs_i8_conversion", "(", "arr_or_dtype", ")", "->", "bool", ":", "if", "arr_or_dtype", "is", "None", ":", "return", "False", "return", "(", "is_datetime_or_timedelta_dtype", "(", "arr_or_dtype", ")", "or", "is_datetime64tz_dtype", "(", "arr_or_dtype", ")",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/common.py#L1282-L1323
Manu343726/siplasplas
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
reference/cindex.py
python
Cursor.objc_type_encoding
(self)
return self._objc_type_encoding
Return the Objective-C type encoding as a str.
Return the Objective-C type encoding as a str.
[ "Return", "the", "Objective", "-", "C", "type", "encoding", "as", "a", "str", "." ]
def objc_type_encoding(self): """Return the Objective-C type encoding as a str.""" if not hasattr(self, '_objc_type_encoding'): self._objc_type_encoding = \ conf.lib.clang_getDeclObjCTypeEncoding(self) return self._objc_type_encoding
[ "def", "objc_type_encoding", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_objc_type_encoding'", ")", ":", "self", ".", "_objc_type_encoding", "=", "conf", ".", "lib", ".", "clang_getDeclObjCTypeEncoding", "(", "self", ")", "return", "sel...
https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L1412-L1418
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
tools/coverage/pull_request.py
python
get_pull
(pull_id)
return pull
Args: pull_id (int): Pull id. Returns: github.PullRequest.PullRequest
Args: pull_id (int): Pull id.
[ "Args", ":", "pull_id", "(", "int", ")", ":", "Pull", "id", "." ]
def get_pull(pull_id): """ Args: pull_id (int): Pull id. Returns: github.PullRequest.PullRequest """ github = Github(token, timeout=60) repo = github.get_repo('PaddlePaddle/Paddle') pull = repo.get_pull(pull_id) return pull
[ "def", "get_pull", "(", "pull_id", ")", ":", "github", "=", "Github", "(", "token", ",", "timeout", "=", "60", ")", "repo", "=", "github", ".", "get_repo", "(", "'PaddlePaddle/Paddle'", ")", "pull", "=", "repo", ".", "get_pull", "(", "pull_id", ")", "r...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/coverage/pull_request.py#L30-L42
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/ssd/dataset/pycocotools/coco.py
python
COCO.loadNumpyAnnotations
(self, data)
return ann
Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class} :param data (numpy.ndarray) :return: annotations (python nested list)
Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class} :param data (numpy.ndarray) :return: annotations (python nested list)
[ "Convert", "result", "data", "from", "a", "numpy", "array", "[", "Nx7", "]", "where", "each", "row", "contains", "{", "imageID", "x1", "y1", "w", "h", "score", "class", "}", ":", "param", "data", "(", "numpy", ".", "ndarray", ")", ":", "return", ":",...
def loadNumpyAnnotations(self, data): """ Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class} :param data (numpy.ndarray) :return: annotations (python nested list) """ print('Converting ndarray to lists...') assert(type(data) == np.ndarray) print(data.shape) assert(data.shape[1] == 7) N = data.shape[0] ann = [] for i in range(N): if i % 1000000 == 0: print('{}/{}'.format(i,N)) ann += [{ 'image_id' : int(data[i, 0]), 'bbox' : [ data[i, 1], data[i, 2], data[i, 3], data[i, 4] ], 'score' : data[i, 5], 'category_id': int(data[i, 6]), }] return ann
[ "def", "loadNumpyAnnotations", "(", "self", ",", "data", ")", ":", "print", "(", "'Converting ndarray to lists...'", ")", "assert", "(", "type", "(", "data", ")", "==", "np", ".", "ndarray", ")", "print", "(", "data", ".", "shape", ")", "assert", "(", "d...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/ssd/dataset/pycocotools/coco.py#L398-L419
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/help.py
python
HelpParser.handle_starttag
(self, tag, attrs)
Handle starttags in help.html.
Handle starttags in help.html.
[ "Handle", "starttags", "in", "help", ".", "html", "." ]
def handle_starttag(self, tag, attrs): "Handle starttags in help.html." class_ = '' for a, v in attrs: if a == 'class': class_ = v s = '' if tag == 'div' and class_ == 'section': self.show = True # Start main content. elif tag == 'div' and class_ == 'sphinxsidebar': self.show = False # End main content. elif tag == 'p' and self.prevtag and not self.prevtag[0]: # Begin a new block for <p> tags after a closed tag. # Avoid extra lines, e.g. after <pre> tags. lastline = self.text.get('end-1c linestart', 'end-1c') s = '\n\n' if lastline and not lastline.isspace() else '\n' elif tag == 'span' and class_ == 'pre': self.chartags = 'pre' elif tag == 'span' and class_ == 'versionmodified': self.chartags = 'em' elif tag == 'em': self.chartags = 'em' elif tag in ['ul', 'ol']: if class_.find('simple') != -1: s = '\n' self.simplelist = True else: self.simplelist = False self.indent() elif tag == 'dl': if self.level > 0: self.nested_dl = True elif tag == 'li': s = '\n* ' if self.simplelist else '\n\n* ' elif tag == 'dt': s = '\n\n' if not self.nested_dl else '\n' # Avoid extra line. self.nested_dl = False elif tag == 'dd': self.indent() s = '\n' elif tag == 'pre': self.pre = True if self.show: self.text.insert('end', '\n\n') self.tags = 'preblock' elif tag == 'a' and class_ == 'headerlink': self.hdrlink = True elif tag == 'h1': self.tags = tag elif tag in ['h2', 'h3']: if self.show: self.header = '' self.text.insert('end', '\n\n') self.tags = tag if self.show: self.text.insert('end', s, (self.tags, self.chartags)) self.prevtag = (True, tag)
[ "def", "handle_starttag", "(", "self", ",", "tag", ",", "attrs", ")", ":", "class_", "=", "''", "for", "a", ",", "v", "in", "attrs", ":", "if", "a", "==", "'class'", ":", "class_", "=", "v", "s", "=", "''", "if", "tag", "==", "'div'", "and", "c...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/help.py#L72-L128
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextFileHandler.GetEncoding
(*args, **kwargs)
return _richtext.RichTextFileHandler_GetEncoding(*args, **kwargs)
GetEncoding(self) -> String
GetEncoding(self) -> String
[ "GetEncoding", "(", "self", ")", "-", ">", "String" ]
def GetEncoding(*args, **kwargs): """GetEncoding(self) -> String""" return _richtext.RichTextFileHandler_GetEncoding(*args, **kwargs)
[ "def", "GetEncoding", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextFileHandler_GetEncoding", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2828-L2830
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/config/win/get_msvc_config_real.py
python
VisualStudioVersion.ProjectVersion
(self)
return self.project_version
Get the version number of the vcproj or vcxproj files.
Get the version number of the vcproj or vcxproj files.
[ "Get", "the", "version", "number", "of", "the", "vcproj", "or", "vcxproj", "files", "." ]
def ProjectVersion(self): """Get the version number of the vcproj or vcxproj files.""" return self.project_version
[ "def", "ProjectVersion", "(", "self", ")", ":", "return", "self", ".", "project_version" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/config/win/get_msvc_config_real.py#L44-L46
stepcode/stepcode
2a50010e6f6b8bd4843561e48fdb0fd4e8b87f39
src/exp2python/python/SCL/Part21.py
python
Parser.p_exchange_file
(self, p)
exchange_file : check_p21_start_token header_section data_section_list check_p21_end_token
exchange_file : check_p21_start_token header_section data_section_list check_p21_end_token
[ "exchange_file", ":", "check_p21_start_token", "header_section", "data_section_list", "check_p21_end_token" ]
def p_exchange_file(self, p): """exchange_file : check_p21_start_token header_section data_section_list check_p21_end_token""" p[0] = P21File(p[2], p[3])
[ "def", "p_exchange_file", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "P21File", "(", "p", "[", "2", "]", ",", "p", "[", "3", "]", ")" ]
https://github.com/stepcode/stepcode/blob/2a50010e6f6b8bd4843561e48fdb0fd4e8b87f39/src/exp2python/python/SCL/Part21.py#L284-L286
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/wheel_builder.py
python
_build_one
( req, # type: InstallRequirement output_dir, # type: str verify, # type: bool build_options, # type: List[str] global_options, # type: List[str] )
return wheel_path
Build one wheel. :return: The filename of the built wheel, or None if the build failed.
Build one wheel.
[ "Build", "one", "wheel", "." ]
def _build_one( req, # type: InstallRequirement output_dir, # type: str verify, # type: bool build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> Optional[str] """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ try: ensure_dir(output_dir) except OSError as e: logger.warning( "Building wheel for %s failed: %s", req.name, e, ) return None # Install build deps into temporary directory (PEP 518) with req.build_env: wheel_path = _build_one_inside_env( req, output_dir, build_options, global_options ) if wheel_path and verify: try: _verify_one(req, wheel_path) except (InvalidWheelFilename, UnsupportedWheel) as e: logger.warning("Built wheel for %s is invalid: %s", req.name, e) return None return wheel_path
[ "def", "_build_one", "(", "req", ",", "# type: InstallRequirement", "output_dir", ",", "# type: str", "verify", ",", "# type: bool", "build_options", ",", "# type: List[str]", "global_options", ",", "# type: List[str]", ")", ":", "# type: (...) -> Optional[str]", "try", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/wheel_builder.py#L213-L245
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests_aws4auth/aws4auth.py
python
AWS4Auth.get_canonical_headers
(cls, req, include=None)
return (cano_headers, signed_headers)
Generate the Canonical Headers section of the Canonical Request. Return the Canonical Headers and the Signed Headers strs as a tuple (canonical_headers, signed_headers). req -- Requests PreparedRequest object include -- List of headers to include in the canonical and signed headers. It's primarily included to allow testing against specific examples from Amazon. If omitted or None it includes host, content-type and any header starting 'x-amz-' except for x-amz-client context, which appears to break mobile analytics auth if included. Except for the x-amz-client-context exclusion these defaults are per the AWS documentation.
Generate the Canonical Headers section of the Canonical Request.
[ "Generate", "the", "Canonical", "Headers", "section", "of", "the", "Canonical", "Request", "." ]
def get_canonical_headers(cls, req, include=None): """ Generate the Canonical Headers section of the Canonical Request. Return the Canonical Headers and the Signed Headers strs as a tuple (canonical_headers, signed_headers). req -- Requests PreparedRequest object include -- List of headers to include in the canonical and signed headers. It's primarily included to allow testing against specific examples from Amazon. If omitted or None it includes host, content-type and any header starting 'x-amz-' except for x-amz-client context, which appears to break mobile analytics auth if included. Except for the x-amz-client-context exclusion these defaults are per the AWS documentation. """ if include is None: include = cls.default_include_headers include = [x.lower() for x in include] headers = req.headers.copy() # Temporarily include the host header - AWS requires it to be included # in the signed headers, but Requests doesn't include it in a # PreparedRequest if 'host' not in headers: headers['host'] = urlparse(req.url).netloc.split(':')[0] # Aggregate for upper/lowercase header name collisions in header names, # AMZ requires values of colliding headers be concatenated into a # single header with lowercase name. Although this is not possible with # Requests, since it uses a case-insensitive dict to hold headers, this # is here just in case you duck type with a regular dict cano_headers_dict = {} for hdr, val in headers.items(): hdr = hdr.strip().lower() val = cls.amz_norm_whitespace(val).strip() if (hdr in include or '*' in include or ('x-amz-*' in include and hdr.startswith('x-amz-') and not hdr == 'x-amz-client-context')): vals = cano_headers_dict.setdefault(hdr, []) vals.append(val) # Flatten cano_headers dict to string and generate signed_headers cano_headers = '' signed_headers_list = [] for hdr in sorted(cano_headers_dict): vals = cano_headers_dict[hdr] val = ','.join(sorted(vals)) cano_headers += '{}:{}\n'.format(hdr, val) signed_headers_list.append(hdr) signed_headers = ';'.join(signed_headers_list) return (cano_headers, signed_headers)
[ "def", "get_canonical_headers", "(", "cls", ",", "req", ",", "include", "=", "None", ")", ":", "if", "include", "is", "None", ":", "include", "=", "cls", ".", "default_include_headers", "include", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests_aws4auth/aws4auth.py#L523-L573
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/distributions/python/ops/mvn_linear_operator.py
python
_kl_brute_force
(a, b, name=None)
Batched KL divergence `KL(a || b)` for multivariate Normals. With `X`, `Y` both multivariate Normals in `R^k` with means `mu_a`, `mu_b` and covariance `C_a`, `C_b` respectively, ``` KL(a || b) = 0.5 * ( L - k + T + Q ), L := Log[Det(C_b)] - Log[Det(C_a)] T := trace(C_b^{-1} C_a), Q := (mu_b - mu_a)^T C_b^{-1} (mu_b - mu_a), ``` This `Op` computes the trace by solving `C_b^{-1} C_a`. Although efficient methods for solving systems with `C_b` may be available, a dense version of (the square root of) `C_a` is used, so performance is `O(B s k**2)` where `B` is the batch size, and `s` is the cost of solving `C_b x = y` for vectors `x` and `y`. Args: a: Instance of `MultivariateNormalLinearOperator`. b: Instance of `MultivariateNormalLinearOperator`. name: (optional) name to use for created ops. Default "kl_mvn". Returns: Batchwise `KL(a || b)`.
Batched KL divergence `KL(a || b)` for multivariate Normals.
[ "Batched", "KL", "divergence", "KL", "(", "a", "||", "b", ")", "for", "multivariate", "Normals", "." ]
def _kl_brute_force(a, b, name=None): """Batched KL divergence `KL(a || b)` for multivariate Normals. With `X`, `Y` both multivariate Normals in `R^k` with means `mu_a`, `mu_b` and covariance `C_a`, `C_b` respectively, ``` KL(a || b) = 0.5 * ( L - k + T + Q ), L := Log[Det(C_b)] - Log[Det(C_a)] T := trace(C_b^{-1} C_a), Q := (mu_b - mu_a)^T C_b^{-1} (mu_b - mu_a), ``` This `Op` computes the trace by solving `C_b^{-1} C_a`. Although efficient methods for solving systems with `C_b` may be available, a dense version of (the square root of) `C_a` is used, so performance is `O(B s k**2)` where `B` is the batch size, and `s` is the cost of solving `C_b x = y` for vectors `x` and `y`. Args: a: Instance of `MultivariateNormalLinearOperator`. b: Instance of `MultivariateNormalLinearOperator`. name: (optional) name to use for created ops. Default "kl_mvn". Returns: Batchwise `KL(a || b)`. """ def squared_frobenius_norm(x): """Helper to make KL calculation slightly more readable.""" # http://mathworld.wolfram.com/FrobeniusNorm.html return math_ops.square(linalg_ops.norm(x, ord="fro", axis=[-2, -1])) # TODO(b/35041439): See also b/35040945. Remove this function once LinOp # supports something like: # A.inverse().solve(B).norm(order='fro', axis=[-1, -2]) def is_diagonal(x): """Helper to identify if `LinearOperator` has only a diagonal component.""" return (isinstance(x, linalg.LinearOperatorIdentity) or isinstance(x, linalg.LinearOperatorScaledIdentity) or isinstance(x, linalg.LinearOperatorDiag)) with ops.name_scope(name, "kl_mvn", values=[a.loc, b.loc] + a.scale.graph_parents + b.scale.graph_parents): # Calculation is based on: # http://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians # and, # https://en.wikipedia.org/wiki/Matrix_norm#Frobenius_norm # i.e., # If Ca = AA', Cb = BB', then # tr[inv(Cb) Ca] = tr[inv(B)' inv(B) A A'] # = tr[inv(B) A A' inv(B)'] # = tr[(inv(B) A) (inv(B) A)'] # = sum_{ij} (inv(B) A)_{ij}**2 # = ||inv(B) A||_F**2 # where ||.||_F is the Frobenius norm and the second equality follows from # the cyclic permutation property. if is_diagonal(a.scale) and is_diagonal(b.scale): # Using `stddev` because it handles expansion of Identity cases. b_inv_a = (a.stddev() / b.stddev())[..., array_ops.newaxis] else: b_inv_a = b.scale.solve(a.scale.to_dense()) kl_div = (b.scale.log_abs_determinant() - a.scale.log_abs_determinant() + 0.5 * ( - math_ops.cast(a.scale.domain_dimension_tensor(), a.dtype) + squared_frobenius_norm(b_inv_a) + squared_frobenius_norm(b.scale.solve( (b.mean() - a.mean())[..., array_ops.newaxis])))) kl_div.set_shape(array_ops.broadcast_static_shape( a.batch_shape, b.batch_shape)) return kl_div
[ "def", "_kl_brute_force", "(", "a", ",", "b", ",", "name", "=", "None", ")", ":", "def", "squared_frobenius_norm", "(", "x", ")", ":", "\"\"\"Helper to make KL calculation slightly more readable.\"\"\"", "# http://mathworld.wolfram.com/FrobeniusNorm.html", "return", "math_o...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/mvn_linear_operator.py#L271-L342
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TBool.GetPrimHashCd
(self)
return _snap.TBool_GetPrimHashCd(self)
GetPrimHashCd(TBool self) -> int Parameters: self: TBool const *
GetPrimHashCd(TBool self) -> int
[ "GetPrimHashCd", "(", "TBool", "self", ")", "-", ">", "int" ]
def GetPrimHashCd(self): """ GetPrimHashCd(TBool self) -> int Parameters: self: TBool const * """ return _snap.TBool_GetPrimHashCd(self)
[ "def", "GetPrimHashCd", "(", "self", ")", ":", "return", "_snap", ".", "TBool_GetPrimHashCd", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L12193-L12201
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py
python
EnsureDirExists
(path)
Make sure the directory for |path| exists.
Make sure the directory for |path| exists.
[ "Make", "sure", "the", "directory", "for", "|path|", "exists", "." ]
def EnsureDirExists(path): """Make sure the directory for |path| exists.""" try: os.makedirs(os.path.dirname(path)) except OSError: pass
[ "def", "EnsureDirExists", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", "except", "OSError", ":", "pass" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py#L415-L420
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/ndarray.py
python
NDArray.ndim
(self)
return len(self.shape)
Returns the number of dimensions of this array Examples -------- >>> x = mx.nd.array([1, 2, 3, 4]) >>> x.ndim 1 >>> x = mx.nd.array([[1, 2], [3, 4]]) >>> x.ndim 2
Returns the number of dimensions of this array
[ "Returns", "the", "number", "of", "dimensions", "of", "this", "array" ]
def ndim(self): """Returns the number of dimensions of this array Examples -------- >>> x = mx.nd.array([1, 2, 3, 4]) >>> x.ndim 1 >>> x = mx.nd.array([[1, 2], [3, 4]]) >>> x.ndim 2 """ return len(self.shape)
[ "def", "ndim", "(", "self", ")", ":", "return", "len", "(", "self", ".", "shape", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L2430-L2442
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/showbase/Messenger.py
python
Messenger.__methodRepr
(self, method)
return functionName
return string version of class.method or method.
return string version of class.method or method.
[ "return", "string", "version", "of", "class", ".", "method", "or", "method", "." ]
def __methodRepr(self, method): """ return string version of class.method or method. """ if isinstance(method, types.MethodType): functionName = method.__self__.__class__.__name__ + '.' + \ method.__func__.__name__ else: if hasattr(method, "__name__"): functionName = method.__name__ else: return "" return functionName
[ "def", "__methodRepr", "(", "self", ",", "method", ")", ":", "if", "isinstance", "(", "method", ",", "types", ".", "MethodType", ")", ":", "functionName", "=", "method", ".", "__self__", ".", "__class__", ".", "__name__", "+", "'.'", "+", "method", ".", ...
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/Messenger.py#L569-L581
sfzhang15/RefineDet
52b6fe23dc1a160fe710b7734576dca509bf4fae
python/caffe/pycaffe.py
python
_Net_forward_all
(self, blobs=None, **kwargs)
return all_outs
Run net forward in batches. Parameters ---------- blobs : list of blobs to extract as in forward() kwargs : Keys are input blob names and values are blob ndarrays. Refer to forward(). Returns ------- all_outs : {blob name: list of blobs} dict.
Run net forward in batches.
[ "Run", "net", "forward", "in", "batches", "." ]
def _Net_forward_all(self, blobs=None, **kwargs): """ Run net forward in batches. Parameters ---------- blobs : list of blobs to extract as in forward() kwargs : Keys are input blob names and values are blob ndarrays. Refer to forward(). Returns ------- all_outs : {blob name: list of blobs} dict. """ # Collect outputs from batches all_outs = {out: [] for out in set(self.outputs + (blobs or []))} for batch in self._batch(kwargs): outs = self.forward(blobs=blobs, **batch) for out, out_blob in six.iteritems(outs): all_outs[out].extend(out_blob.copy()) # Package in ndarray. for out in all_outs: all_outs[out] = np.asarray(all_outs[out]) # Discard padding. pad = len(six.next(six.itervalues(all_outs))) - len(six.next(six.itervalues(kwargs))) if pad: for out in all_outs: all_outs[out] = all_outs[out][:-pad] return all_outs
[ "def", "_Net_forward_all", "(", "self", ",", "blobs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Collect outputs from batches", "all_outs", "=", "{", "out", ":", "[", "]", "for", "out", "in", "set", "(", "self", ".", "outputs", "+", "(", "blobs...
https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/python/caffe/pycaffe.py#L175-L203
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pyrsistent/_field_common.py
python
_restore_seq_field_pickle
(checked_class, item_type, data)
return _restore_pickle(type_, data)
Unpickling function for auto-generated PVec/PSet field types.
Unpickling function for auto-generated PVec/PSet field types.
[ "Unpickling", "function", "for", "auto", "-", "generated", "PVec", "/", "PSet", "field", "types", "." ]
def _restore_seq_field_pickle(checked_class, item_type, data): """Unpickling function for auto-generated PVec/PSet field types.""" type_ = _seq_field_types[checked_class, item_type] return _restore_pickle(type_, data)
[ "def", "_restore_seq_field_pickle", "(", "checked_class", ",", "item_type", ",", "data", ")", ":", "type_", "=", "_seq_field_types", "[", "checked_class", ",", "item_type", "]", "return", "_restore_pickle", "(", "type_", ",", "data", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pyrsistent/_field_common.py#L186-L189
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/ndarray.py
python
NDArray.log
(self, *args, **kwargs)
return op.log(self, *args, **kwargs)
Convenience fluent method for :py:func:`log`. The arguments are the same as for :py:func:`log`, with this array as data.
Convenience fluent method for :py:func:`log`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "log", "." ]
def log(self, *args, **kwargs): """Convenience fluent method for :py:func:`log`. The arguments are the same as for :py:func:`log`, with this array as data. """ return op.log(self, *args, **kwargs)
[ "def", "log", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "log", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L2142-L2148
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/bottle/bottle.py
python
BaseResponse.delete_cookie
(self, key, **kwargs)
Delete a cookie. Be sure to use the same `domain` and `path` settings as used to create the cookie.
Delete a cookie. Be sure to use the same `domain` and `path` settings as used to create the cookie.
[ "Delete", "a", "cookie", ".", "Be", "sure", "to", "use", "the", "same", "domain", "and", "path", "settings", "as", "used", "to", "create", "the", "cookie", "." ]
def delete_cookie(self, key, **kwargs): ''' Delete a cookie. Be sure to use the same `domain` and `path` settings as used to create the cookie. ''' kwargs['max_age'] = -1 kwargs['expires'] = 0 self.set_cookie(key, '', **kwargs)
[ "def", "delete_cookie", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'max_age'", "]", "=", "-", "1", "kwargs", "[", "'expires'", "]", "=", "0", "self", ".", "set_cookie", "(", "key", ",", "''", ",", "*", "*", "kwarg...
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/bottle/bottle.py#L1613-L1618
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_basestc.py
python
EditraBaseStc.GetFileName
(self)
return self.file.GetPath()
Returns the full path name of the current file @return: full path name of document
Returns the full path name of the current file @return: full path name of document
[ "Returns", "the", "full", "path", "name", "of", "the", "current", "file", "@return", ":", "full", "path", "name", "of", "document" ]
def GetFileName(self): """Returns the full path name of the current file @return: full path name of document """ return self.file.GetPath()
[ "def", "GetFileName", "(", "self", ")", ":", "return", "self", ".", "file", ".", "GetPath", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_basestc.py#L679-L684
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/form_wrap.py
python
FormWrap.getvalue_url
(self, key, default_val=None)
return val
Gets an URL value (absolute or relative). Args: key: requested argument. default_val: a default value to return if requested argument is not present. Returns: value for requested argument.
Gets an URL value (absolute or relative).
[ "Gets", "an", "URL", "value", "(", "absolute", "or", "relative", ")", "." ]
def getvalue_url(self, key, default_val=None): """Gets an URL value (absolute or relative). Args: key: requested argument. default_val: a default value to return if requested argument is not present. Returns: value for requested argument. """ logging.debug("getvalue_url() - key: %s", key) val = self._getvalue_raw(key, default_val) if not val: return val if self._do_sanitize: val = self._sanitize_url(val) logging.debug("getvalue_url() - key: %s, val: %s", key, val) return val
[ "def", "getvalue_url", "(", "self", ",", "key", ",", "default_val", "=", "None", ")", ":", "logging", ".", "debug", "(", "\"getvalue_url() - key: %s\"", ",", "key", ")", "val", "=", "self", ".", "_getvalue_raw", "(", "key", ",", "default_val", ")", "if", ...
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/form_wrap.py#L219-L239
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/encodings/punycode.py
python
selective_find
(str, char, index, pos)
Return a pair (index, pos), indicating the next occurrence of char in str. index is the position of the character considering only ordinals up to and including char, and pos is the position in the full string. index/pos is the starting position in the full string.
Return a pair (index, pos), indicating the next occurrence of char in str. index is the position of the character considering only ordinals up to and including char, and pos is the position in the full string. index/pos is the starting position in the full string.
[ "Return", "a", "pair", "(", "index", "pos", ")", "indicating", "the", "next", "occurrence", "of", "char", "in", "str", ".", "index", "is", "the", "position", "of", "the", "character", "considering", "only", "ordinals", "up", "to", "and", "including", "char...
def selective_find(str, char, index, pos): """Return a pair (index, pos), indicating the next occurrence of char in str. index is the position of the character considering only ordinals up to and including char, and pos is the position in the full string. index/pos is the starting position in the full string.""" l = len(str) while 1: pos += 1 if pos == l: return (-1, -1) c = str[pos] if c == char: return index+1, pos elif c < char: index += 1
[ "def", "selective_find", "(", "str", ",", "char", ",", "index", ",", "pos", ")", ":", "l", "=", "len", "(", "str", ")", "while", "1", ":", "pos", "+=", "1", "if", "pos", "==", "l", ":", "return", "(", "-", "1", ",", "-", "1", ")", "c", "=",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/encodings/punycode.py#L30-L46
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/distutils/command/sdist.py
python
sdist.make_release_tree
(self, base_dir, files)
Create the directory tree that will become the source distribution archive. All directories implied by the filenames in 'files' are created under 'base_dir', and then we hard link or copy (if hard linking is unavailable) those files into place. Essentially, this duplicates the developer's source tree, but in a directory named after the distribution, containing only the files to be distributed.
Create the directory tree that will become the source distribution archive. All directories implied by the filenames in 'files' are created under 'base_dir', and then we hard link or copy (if hard linking is unavailable) those files into place. Essentially, this duplicates the developer's source tree, but in a directory named after the distribution, containing only the files to be distributed.
[ "Create", "the", "directory", "tree", "that", "will", "become", "the", "source", "distribution", "archive", ".", "All", "directories", "implied", "by", "the", "filenames", "in", "files", "are", "created", "under", "base_dir", "and", "then", "we", "hard", "link...
def make_release_tree(self, base_dir, files): """Create the directory tree that will become the source distribution archive. All directories implied by the filenames in 'files' are created under 'base_dir', and then we hard link or copy (if hard linking is unavailable) those files into place. Essentially, this duplicates the developer's source tree, but in a directory named after the distribution, containing only the files to be distributed. """ # Create all the directories under 'base_dir' necessary to # put 'files' there; the 'mkpath()' is just so we don't die # if the manifest happens to be empty. self.mkpath(base_dir) dir_util.create_tree(base_dir, files, dry_run=self.dry_run) # And walk over the list of files, either making a hard link (if # os.link exists) to each one that doesn't already exist in its # corresponding location under 'base_dir', or copying each file # that's out-of-date in 'base_dir'. (Usually, all files will be # out-of-date, because by default we blow away 'base_dir' when # we're done making the distribution archives.) if hasattr(os, 'link'): # can make hard links on this system link = 'hard' msg = "making hard links in %s..." % base_dir else: # nope, have to copy link = None msg = "copying files to %s..." % base_dir if not files: log.warn("no files to distribute -- empty manifest?") else: log.info(msg) for file in files: if not os.path.isfile(file): log.warn("'%s' not a regular file -- skipping" % file) else: dest = os.path.join(base_dir, file) self.copy_file(file, dest, link=link) self.distribution.metadata.write_pkg_info(base_dir)
[ "def", "make_release_tree", "(", "self", ",", "base_dir", ",", "files", ")", ":", "# Create all the directories under 'base_dir' necessary to", "# put 'files' there; the 'mkpath()' is just so we don't die", "# if the manifest happens to be empty.", "self", ".", "mkpath", "(", "base...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/command/sdist.py#L401-L441
bh107/bohrium
5b83e7117285fefc7779ed0e9acb0f8e74c7e068
bridge/npbackend/bohrium/masking.py
python
masked_get
(ary, bool_mask)
return ary[reorganization.nonzero(bool_mask)]
Get the elements of 'ary' specified by 'bool_mask'.
Get the elements of 'ary' specified by 'bool_mask'.
[ "Get", "the", "elements", "of", "ary", "specified", "by", "bool_mask", "." ]
def masked_get(ary, bool_mask): """ Get the elements of 'ary' specified by 'bool_mask'. """ return ary[reorganization.nonzero(bool_mask)]
[ "def", "masked_get", "(", "ary", ",", "bool_mask", ")", ":", "return", "ary", "[", "reorganization", ".", "nonzero", "(", "bool_mask", ")", "]" ]
https://github.com/bh107/bohrium/blob/5b83e7117285fefc7779ed0e9acb0f8e74c7e068/bridge/npbackend/bohrium/masking.py#L140-L145
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/mhlib.py
python
MH.__init__
(self, path = None, profile = None)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self, path = None, profile = None): """Constructor.""" if profile is None: profile = MH_PROFILE self.profile = os.path.expanduser(profile) if path is None: path = self.getprofile('Path') if not path: path = PATH if not os.path.isabs(path) and path[0] != '~': path = os.path.join('~', path) path = os.path.expanduser(path) if not os.path.isdir(path): raise Error, 'MH() path not found' self.path = path
[ "def", "__init__", "(", "self", ",", "path", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "profile", "is", "None", ":", "profile", "=", "MH_PROFILE", "self", ".", "profile", "=", "os", ".", "path", ".", "expanduser", "(", "profile", ")",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mhlib.py#L102-L112
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/datasets/species_distributions.py
python
fetch_species_distributions
(data_home=None, download_if_missing=True)
return bunch
Loader for species distribution dataset from Phillips et. al. (2006) Read more in the :ref:`User Guide <datasets>`. Parameters ---------- data_home : optional, default: None Specify another download and cache folder for the datasets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. download_if_missing : optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. Returns -------- The data is returned as a Bunch object with the following attributes: coverages : array, shape = [14, 1592, 1212] These represent the 14 features measured at each point of the map grid. The latitude/longitude values for the grid are discussed below. Missing data is represented by the value -9999. train : record array, shape = (1623,) The training points for the data. Each point has three fields: - train['species'] is the species name - train['dd long'] is the longitude, in degrees - train['dd lat'] is the latitude, in degrees test : record array, shape = (619,) The test points for the data. Same format as the training data. Nx, Ny : integers The number of longitudes (x) and latitudes (y) in the grid x_left_lower_corner, y_left_lower_corner : floats The (x,y) position of the lower-left corner, in degrees grid_size : float The spacing between points of the grid, in degrees Notes ------ This dataset represents the geographic distribution of species. The dataset is provided by Phillips et. al. (2006). The two species are: - `"Bradypus variegatus" <http://www.iucnredlist.org/details/3038/0>`_ , the Brown-throated Sloth. - `"Microryzomys minutus" <http://www.iucnredlist.org/details/13408/0>`_ , also known as the Forest Small Rice Rat, a rodent that lives in Peru, Colombia, Ecuador, Peru, and Venezuela. References ---------- * `"Maximum entropy modeling of species geographic distributions" <http://www.cs.princeton.edu/~schapire/papers/ecolmod.pdf>`_ S. J. Phillips, R. P. Anderson, R. E. Schapire - Ecological Modelling, 190:231-259, 2006. Notes ----- * See examples/applications/plot_species_distribution_modeling.py for an example of using this dataset with scikit-learn
Loader for species distribution dataset from Phillips et. al. (2006)
[ "Loader", "for", "species", "distribution", "dataset", "from", "Phillips", "et", ".", "al", ".", "(", "2006", ")" ]
def fetch_species_distributions(data_home=None, download_if_missing=True): """Loader for species distribution dataset from Phillips et. al. (2006) Read more in the :ref:`User Guide <datasets>`. Parameters ---------- data_home : optional, default: None Specify another download and cache folder for the datasets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. download_if_missing : optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. Returns -------- The data is returned as a Bunch object with the following attributes: coverages : array, shape = [14, 1592, 1212] These represent the 14 features measured at each point of the map grid. The latitude/longitude values for the grid are discussed below. Missing data is represented by the value -9999. train : record array, shape = (1623,) The training points for the data. Each point has three fields: - train['species'] is the species name - train['dd long'] is the longitude, in degrees - train['dd lat'] is the latitude, in degrees test : record array, shape = (619,) The test points for the data. Same format as the training data. Nx, Ny : integers The number of longitudes (x) and latitudes (y) in the grid x_left_lower_corner, y_left_lower_corner : floats The (x,y) position of the lower-left corner, in degrees grid_size : float The spacing between points of the grid, in degrees Notes ------ This dataset represents the geographic distribution of species. The dataset is provided by Phillips et. al. (2006). The two species are: - `"Bradypus variegatus" <http://www.iucnredlist.org/details/3038/0>`_ , the Brown-throated Sloth. - `"Microryzomys minutus" <http://www.iucnredlist.org/details/13408/0>`_ , also known as the Forest Small Rice Rat, a rodent that lives in Peru, Colombia, Ecuador, Peru, and Venezuela. References ---------- * `"Maximum entropy modeling of species geographic distributions" <http://www.cs.princeton.edu/~schapire/papers/ecolmod.pdf>`_ S. J. Phillips, R. P. Anderson, R. E. Schapire - Ecological Modelling, 190:231-259, 2006. Notes ----- * See examples/applications/plot_species_distribution_modeling.py for an example of using this dataset with scikit-learn """ data_home = get_data_home(data_home) if not exists(data_home): makedirs(data_home) # Define parameters for the data files. These should not be changed # unless the data model changes. They will be saved in the npz file # with the downloaded data. extra_params = dict(x_left_lower_corner=-94.8, Nx=1212, y_left_lower_corner=-56.05, Ny=1592, grid_size=0.05) dtype = np.int16 archive_path = _pkl_filepath(data_home, DATA_ARCHIVE_NAME) if not exists(archive_path): print('Downloading species data from %s to %s' % (SAMPLES_URL, data_home)) X = np.load(BytesIO(urlopen(SAMPLES_URL).read())) for f in X.files: fhandle = BytesIO(X[f]) if 'train' in f: train = _load_csv(fhandle) if 'test' in f: test = _load_csv(fhandle) print('Downloading coverage data from %s to %s' % (COVERAGES_URL, data_home)) X = np.load(BytesIO(urlopen(COVERAGES_URL).read())) coverages = [] for f in X.files: fhandle = BytesIO(X[f]) print(' - converting', f) coverages.append(_load_coverage(fhandle)) coverages = np.asarray(coverages, dtype=dtype) bunch = Bunch(coverages=coverages, test=test, train=train, **extra_params) joblib.dump(bunch, archive_path, compress=9) else: bunch = joblib.load(archive_path) return bunch
[ "def", "fetch_species_distributions", "(", "data_home", "=", "None", ",", "download_if_missing", "=", "True", ")", ":", "data_home", "=", "get_data_home", "(", "data_home", ")", "if", "not", "exists", "(", "data_home", ")", ":", "makedirs", "(", "data_home", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/datasets/species_distributions.py#L132-L256
isc-projects/kea
c5836c791b63f42173bb604dd5f05d7110f3e716
hammer.py
python
_configure_pgsql
(system, features)
Configure PostgreSQL DB
Configure PostgreSQL DB
[ "Configure", "PostgreSQL", "DB" ]
def _configure_pgsql(system, features): """ Configure PostgreSQL DB """ # execute() calls will set cwd='/tmp' when switching user to postgres to # avoid the error: # could not change as postgres user directory to "/home/jenkins": Permission denied if system in ['fedora', 'centos']: # https://fedoraproject.org/wiki/PostgreSQL exitcode = execute('sudo ls /var/lib/pgsql/data/postgresql.conf', raise_error=False) if exitcode != 0: if system == 'centos': execute('sudo postgresql-setup initdb') else: execute('sudo postgresql-setup --initdb --unit postgresql') elif system == 'freebsd': # Stop any hypothetical existing postgres service. execute('sudo service postgresql stop || true') # Get the path to the data directory e.g. /var/db/postgres/data11 for # FreeBSD 12 and /var/db/postgres/data13 for FreeBSD 13. _, output = execute('ls -1d /var/db/postgres/data*', capture=True) var_db_postgres_data = output.rstrip() # Create postgres internals. execute('sudo test ! -d {} && sudo /usr/local/etc/rc.d/postgresql oneinitdb || true'.format(var_db_postgres_data)) # if the file '/var/db/postgres/data*/postmaster.opts' does not exist the 'restart' of postgresql will fail with error: # pg_ctl: could not read file "/var/db/postgres/data*/postmaster.opts" # the initial start of the postgresql will create the 'postmaster.opts' file execute('sudo test ! -f {}/postmaster.opts && sudo service postgresql onestart || true'.format(var_db_postgres_data)) _enable_postgresql(system) _restart_postgresql(system) # Change auth-method to 'md5' on all connections. cmd = "sudo -u postgres psql -t -c 'SHOW hba_file' | xargs" _, output = execute(cmd, capture=True, cwd='/tmp') hba_file = output.rstrip() _change_postgresql_auth_method('host', 'md5', hba_file) _change_postgresql_auth_method('local', 'md5', hba_file) # Make sure hba file has a postgres superuser entry. It needs to be placed # before any other local auth method for higher priority. Let's simulate # that by putting it just after the auth header. if 0 != execute("sudo cat {} | grep -E '^local.*all.*postgres'".format(hba_file), raise_error=False): auth_header='# TYPE DATABASE USER ADDRESS METHOD' postgres_auth_line='local all postgres ident' # The "\\" followed by newline is for BSD support. execute("""sudo sed -i.bak '/{}/a\\ {} ' '{}'""".format(auth_header, postgres_auth_line, hba_file)) _restart_postgresql(system) cmd = """bash -c \"cat <<EOF | sudo -u postgres psql postgres DROP DATABASE IF EXISTS keatest; DROP USER IF EXISTS keatest; DROP USER IF EXISTS keatest_readonly; CREATE USER keatest WITH PASSWORD 'keatest'; CREATE USER keatest_readonly WITH PASSWORD 'keatest'; CREATE DATABASE keatest; GRANT ALL PRIVILEGES ON DATABASE keatest TO keatest; ALTER DATABASE keatest SET TIMEZONE='{}';\n""".format(_get_local_timezone()) cmd += 'EOF\n"' execute(cmd, cwd='/tmp') cmd = """bash -c \"cat <<EOF | sudo -u postgres psql -U keatest keatest ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO keatest_readonly;\n""" cmd += 'EOF\n"' env = os.environ.copy() env['PGPASSWORD'] = 'keatest' execute(cmd, cwd='/tmp', env=env) if 'forge' in features: cmd = "bash -c \"cat <<EOF | sudo -u postgres psql postgres\n" cmd += "DROP DATABASE IF EXISTS keadb;\n" cmd += "DROP USER IF EXISTS keauser;\n" cmd += "CREATE USER keauser WITH PASSWORD 'keapass';\n" cmd += "CREATE DATABASE keadb;\n" cmd += "GRANT ALL PRIVILEGES ON DATABASE keauser TO keadb;\n" cmd += "EOF\n\"" execute(cmd, cwd='/tmp') log.info('postgresql just configured')
[ "def", "_configure_pgsql", "(", "system", ",", "features", ")", ":", "# execute() calls will set cwd='/tmp' when switching user to postgres to", "# avoid the error:", "# could not change as postgres user directory to \"/home/jenkins\": Permission denied", "if", "system", "in", "[", "...
https://github.com/isc-projects/kea/blob/c5836c791b63f42173bb604dd5f05d7110f3e716/hammer.py#L1213-L1297
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/plot.py
python
PlotGraphics.getYLabel
(self)
return self.yLabel
Get y axis label string
Get y axis label string
[ "Get", "y", "axis", "label", "string" ]
def getYLabel(self): """Get y axis label string""" return self.yLabel
[ "def", "getYLabel", "(", "self", ")", ":", "return", "self", ".", "yLabel" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/plot.py#L500-L502
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBBreakpointLocation.GetQueueName
(self)
return _lldb.SBBreakpointLocation_GetQueueName(self)
GetQueueName(SBBreakpointLocation self) -> char const *
GetQueueName(SBBreakpointLocation self) -> char const *
[ "GetQueueName", "(", "SBBreakpointLocation", "self", ")", "-", ">", "char", "const", "*" ]
def GetQueueName(self): """GetQueueName(SBBreakpointLocation self) -> char const *""" return _lldb.SBBreakpointLocation_GetQueueName(self)
[ "def", "GetQueueName", "(", "self", ")", ":", "return", "_lldb", ".", "SBBreakpointLocation_GetQueueName", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L2118-L2120
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Context.py
python
Context.end_msg
(self, result, color=None)
Print the end of a 'Checking for' message. See :py:meth:`waflib.Context.Context.msg`
Print the end of a 'Checking for' message. See :py:meth:`waflib.Context.Context.msg`
[ "Print", "the", "end", "of", "a", "Checking", "for", "message", ".", "See", ":", "py", ":", "meth", ":", "waflib", ".", "Context", ".", "Context", ".", "msg" ]
def end_msg(self, result, color=None): """Print the end of a 'Checking for' message. See :py:meth:`waflib.Context.Context.msg`""" self.in_msg -= 1 if self.in_msg: return defcolor = 'GREEN' if result == True: msg = 'ok' elif result == False: msg = 'not found' defcolor = 'YELLOW' else: msg = str(result) #self.to_log(msg) Logs.pprint(color or defcolor, msg)
[ "def", "end_msg", "(", "self", ",", "result", ",", "color", "=", "None", ")", ":", "self", ".", "in_msg", "-=", "1", "if", "self", ".", "in_msg", ":", "return", "defcolor", "=", "'GREEN'", "if", "result", "==", "True", ":", "msg", "=", "'ok'", "eli...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Context.py#L570-L586
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
StaticLine.GetClassDefaultAttributes
(*args, **kwargs)
return _controls_.StaticLine_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticLine_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "StaticLine_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L935-L950
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/logging/config.py
python
_install_loggers
(cp, handlers, disable_existing)
Create and install loggers
Create and install loggers
[ "Create", "and", "install", "loggers" ]
def _install_loggers(cp, handlers, disable_existing): """Create and install loggers""" # configure the root first llist = cp["loggers"]["keys"] llist = llist.split(",") llist = list(_strip_spaces(llist)) llist.remove("root") section = cp["logger_root"] root = logging.root log = root if "level" in section: level = section["level"] log.setLevel(level) for h in root.handlers[:]: root.removeHandler(h) hlist = section["handlers"] if len(hlist): hlist = hlist.split(",") hlist = _strip_spaces(hlist) for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = list(root.manager.loggerDict.keys()) #The list needs to be sorted so that we can #avoid disabling child loggers of explicitly #named loggers. With a sorted list it is easier #to find the child loggers. existing.sort() #We'll keep the list of existing loggers #which are children of named loggers here... child_loggers = [] #now set up the new ones... for log in llist: section = cp["logger_%s" % log] qn = section["qualname"] propagate = section.getint("propagate", fallback=1) logger = logging.getLogger(qn) if qn in existing: i = existing.index(qn) + 1 # start with the entry after qn prefixed = qn + "." pflen = len(prefixed) num_existing = len(existing) while i < num_existing: if existing[i][:pflen] == prefixed: child_loggers.append(existing[i]) i += 1 existing.remove(qn) if "level" in section: level = section["level"] logger.setLevel(level) for h in logger.handlers[:]: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = section["handlers"] if len(hlist): hlist = hlist.split(",") hlist = _strip_spaces(hlist) for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. #However, don't disable children of named loggers, as that's #probably not what was intended by the user. #for log in existing: # logger = root.manager.loggerDict[log] # if log in child_loggers: # logger.level = logging.NOTSET # logger.handlers = [] # logger.propagate = 1 # elif disable_existing_loggers: # logger.disabled = 1 _handle_existing_loggers(existing, child_loggers, disable_existing)
[ "def", "_install_loggers", "(", "cp", ",", "handlers", ",", "disable_existing", ")", ":", "# configure the root first", "llist", "=", "cp", "[", "\"loggers\"", "]", "[", "\"keys\"", "]", "llist", "=", "llist", ".", "split", "(", "\",\"", ")", "llist", "=", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/config.py#L184-L268
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/MSVSVersion.py
python
VisualStudioVersion.DefaultToolset
(self)
return self.default_toolset
Returns the msbuild toolset version that will be used in the absence of a user override.
Returns the msbuild toolset version that will be used in the absence of a user override.
[ "Returns", "the", "msbuild", "toolset", "version", "that", "will", "be", "used", "in", "the", "absence", "of", "a", "user", "override", "." ]
def DefaultToolset(self): """Returns the msbuild toolset version that will be used in the absence of a user override.""" return self.default_toolset
[ "def", "DefaultToolset", "(", "self", ")", ":", "return", "self", ".", "default_toolset" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/MSVSVersion.py#L66-L69
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/socksipy-branch/socks.py
python
socksocket.connect
(self, destpair)
connect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket's connect). To select the proxy server use setproxy().
connect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket's connect). To select the proxy server use setproxy().
[ "connect", "(", "self", "despair", ")", "Connects", "to", "the", "specified", "destination", "through", "a", "proxy", ".", "destpar", "-", "A", "tuple", "of", "the", "IP", "/", "DNS", "address", "and", "the", "port", "number", ".", "(", "identical", "to"...
def connect(self, destpair): """connect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket's connect). To select the proxy server use setproxy(). """ # Do a minimal input check first if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int): raise GeneralProxyError((5, _generalerrors[5])) if self.__proxy[0] == PROXY_TYPE_SOCKS5: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self, (self.__proxy[1], portnum)) self.__negotiatesocks5(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_SOCKS4: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatesocks4(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatehttp(destpair[0], destpair[1]) elif self.__proxy[0] == None: _orgsocket.connect(self, (destpair[0], destpair[1])) else: raise GeneralProxyError((4, _generalerrors[4]))
[ "def", "connect", "(", "self", ",", "destpair", ")", ":", "# Do a minimal input check first", "if", "(", "not", "type", "(", "destpair", ")", "in", "(", "list", ",", "tuple", ")", ")", "or", "(", "len", "(", "destpair", ")", "<", "2", ")", "or", "(",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/socksipy-branch/socks.py#L353-L387
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/futures.py
python
TransferFuture.__init__
(self, meta=None, coordinator=None)
The future associated to a submitted transfer request :type meta: TransferMeta :param meta: The metadata associated to the request. This object is visible to the requester. :type coordinator: TransferCoordinator :param coordinator: The coordinator associated to the request. This object is not visible to the requester.
The future associated to a submitted transfer request
[ "The", "future", "associated", "to", "a", "submitted", "transfer", "request" ]
def __init__(self, meta=None, coordinator=None): """The future associated to a submitted transfer request :type meta: TransferMeta :param meta: The metadata associated to the request. This object is visible to the requester. :type coordinator: TransferCoordinator :param coordinator: The coordinator associated to the request. This object is not visible to the requester. """ self._meta = meta if meta is None: self._meta = TransferMeta() self._coordinator = coordinator if coordinator is None: self._coordinator = TransferCoordinator()
[ "def", "__init__", "(", "self", ",", "meta", "=", "None", ",", "coordinator", "=", "None", ")", ":", "self", ".", "_meta", "=", "meta", "if", "meta", "is", "None", ":", "self", ".", "_meta", "=", "TransferMeta", "(", ")", "self", ".", "_coordinator",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/futures.py#L75-L92
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/calendar.py
python
CalendarCtrlBase.Mark
(*args, **kwargs)
return _calendar.CalendarCtrlBase_Mark(*args, **kwargs)
Mark(self, size_t day, bool mark)
Mark(self, size_t day, bool mark)
[ "Mark", "(", "self", "size_t", "day", "bool", "mark", ")" ]
def Mark(*args, **kwargs): """Mark(self, size_t day, bool mark)""" return _calendar.CalendarCtrlBase_Mark(*args, **kwargs)
[ "def", "Mark", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_calendar", ".", "CalendarCtrlBase_Mark", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/calendar.py#L318-L320
wesnoth/wesnoth
6ccac5a5e8ff75303c9190c0da60580925cb32c0
data/tools/wesnoth/wmliterator3.py
python
isMacroCloser
(elem)
return type(elem) == type("") and elem == closeMacroType
Are we looking at a macro closer?
Are we looking at a macro closer?
[ "Are", "we", "looking", "at", "a", "macro", "closer?" ]
def isMacroCloser(elem): "Are we looking at a macro closer?" if isinstance(elem, WmlIterator): elem = elem.element return type(elem) == type("") and elem == closeMacroType
[ "def", "isMacroCloser", "(", "elem", ")", ":", "if", "isinstance", "(", "elem", ",", "WmlIterator", ")", ":", "elem", "=", "elem", ".", "element", "return", "type", "(", "elem", ")", "==", "type", "(", "\"\"", ")", "and", "elem", "==", "closeMacroType"...
https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmliterator3.py#L70-L74
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Window.SetInitialSize
(*args, **kwargs)
return _core_.Window_SetInitialSize(*args, **kwargs)
SetInitialSize(self, Size size=DefaultSize) A 'Smart' SetSize that will fill in default size components with the window's *best size* values. Also set's the minsize for use with sizers.
SetInitialSize(self, Size size=DefaultSize)
[ "SetInitialSize", "(", "self", "Size", "size", "=", "DefaultSize", ")" ]
def SetInitialSize(*args, **kwargs): """ SetInitialSize(self, Size size=DefaultSize) A 'Smart' SetSize that will fill in default size components with the window's *best size* values. Also set's the minsize for use with sizers. """ return _core_.Window_SetInitialSize(*args, **kwargs)
[ "def", "SetInitialSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_SetInitialSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L9390-L9397
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/frame.py
python
DataFrame.from_records
( cls, data, index=None, exclude=None, columns=None, coerce_float: bool = False, nrows: int | None = None, )
return cls(mgr)
Convert structured or record ndarray to DataFrame. Creates a DataFrame object from a structured ndarray, sequence of tuples or dicts, or DataFrame. Parameters ---------- data : structured ndarray, sequence of tuples or dicts, or DataFrame Structured input data. index : str, list of fields, array-like Field of array to use as the index, alternately a specific set of input labels to use. exclude : sequence, default None Columns or fields to exclude. columns : sequence, default None Column names to use. If the passed data do not have names associated with them, this argument provides names for the columns. Otherwise this argument indicates the order of the columns in the result (any names not found in the data will become all-NA columns). coerce_float : bool, default False Attempt to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets. nrows : int, default None Number of rows to read if data is an iterator. Returns ------- DataFrame See Also -------- DataFrame.from_dict : DataFrame from dict of array-like or dicts. DataFrame : DataFrame object creation using constructor. Examples -------- Data can be provided as a structured ndarray: >>> data = np.array([(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')], ... dtype=[('col_1', 'i4'), ('col_2', 'U1')]) >>> pd.DataFrame.from_records(data) col_1 col_2 0 3 a 1 2 b 2 1 c 3 0 d Data can be provided as a list of dicts: >>> data = [{'col_1': 3, 'col_2': 'a'}, ... {'col_1': 2, 'col_2': 'b'}, ... {'col_1': 1, 'col_2': 'c'}, ... {'col_1': 0, 'col_2': 'd'}] >>> pd.DataFrame.from_records(data) col_1 col_2 0 3 a 1 2 b 2 1 c 3 0 d Data can be provided as a list of tuples with corresponding columns: >>> data = [(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')] >>> pd.DataFrame.from_records(data, columns=['col_1', 'col_2']) col_1 col_2 0 3 a 1 2 b 2 1 c 3 0 d
Convert structured or record ndarray to DataFrame.
[ "Convert", "structured", "or", "record", "ndarray", "to", "DataFrame", "." ]
def from_records( cls, data, index=None, exclude=None, columns=None, coerce_float: bool = False, nrows: int | None = None, ) -> DataFrame: """ Convert structured or record ndarray to DataFrame. Creates a DataFrame object from a structured ndarray, sequence of tuples or dicts, or DataFrame. Parameters ---------- data : structured ndarray, sequence of tuples or dicts, or DataFrame Structured input data. index : str, list of fields, array-like Field of array to use as the index, alternately a specific set of input labels to use. exclude : sequence, default None Columns or fields to exclude. columns : sequence, default None Column names to use. If the passed data do not have names associated with them, this argument provides names for the columns. Otherwise this argument indicates the order of the columns in the result (any names not found in the data will become all-NA columns). coerce_float : bool, default False Attempt to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets. nrows : int, default None Number of rows to read if data is an iterator. Returns ------- DataFrame See Also -------- DataFrame.from_dict : DataFrame from dict of array-like or dicts. DataFrame : DataFrame object creation using constructor. Examples -------- Data can be provided as a structured ndarray: >>> data = np.array([(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')], ... dtype=[('col_1', 'i4'), ('col_2', 'U1')]) >>> pd.DataFrame.from_records(data) col_1 col_2 0 3 a 1 2 b 2 1 c 3 0 d Data can be provided as a list of dicts: >>> data = [{'col_1': 3, 'col_2': 'a'}, ... {'col_1': 2, 'col_2': 'b'}, ... {'col_1': 1, 'col_2': 'c'}, ... {'col_1': 0, 'col_2': 'd'}] >>> pd.DataFrame.from_records(data) col_1 col_2 0 3 a 1 2 b 2 1 c 3 0 d Data can be provided as a list of tuples with corresponding columns: >>> data = [(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')] >>> pd.DataFrame.from_records(data, columns=['col_1', 'col_2']) col_1 col_2 0 3 a 1 2 b 2 1 c 3 0 d """ # Make a copy of the input columns so we can modify it if columns is not None: columns = ensure_index(columns) if is_iterator(data): if nrows == 0: return cls() try: first_row = next(data) except StopIteration: return cls(index=index, columns=columns) dtype = None if hasattr(first_row, "dtype") and first_row.dtype.names: dtype = first_row.dtype values = [first_row] if nrows is None: values += data else: values.extend(itertools.islice(data, nrows - 1)) if dtype is not None: data = np.array(values, dtype=dtype) else: data = values if isinstance(data, dict): if columns is None: columns = arr_columns = ensure_index(sorted(data)) arrays = [data[k] for k in columns] else: arrays = [] arr_columns_list = [] for k, v in data.items(): if k in columns: arr_columns_list.append(k) arrays.append(v) arr_columns = Index(arr_columns_list) arrays, arr_columns = reorder_arrays(arrays, arr_columns, columns) elif isinstance(data, (np.ndarray, DataFrame)): arrays, columns = to_arrays(data, columns) arr_columns = columns else: arrays, arr_columns = to_arrays(data, columns) if coerce_float: for i, arr in enumerate(arrays): if arr.dtype == object: # error: Argument 1 to "maybe_convert_objects" has # incompatible type "Union[ExtensionArray, ndarray]"; # expected "ndarray" arrays[i] = lib.maybe_convert_objects( arr, # type: ignore[arg-type] try_float=True, ) arr_columns = ensure_index(arr_columns) if columns is None: columns = arr_columns if exclude is None: exclude = set() else: exclude = set(exclude) result_index = None if index is not None: if isinstance(index, str) or not hasattr(index, "__iter__"): i = columns.get_loc(index) exclude.add(index) if len(arrays) > 0: result_index = Index(arrays[i], name=index) else: result_index = Index([], name=index) else: try: index_data = [arrays[arr_columns.get_loc(field)] for field in index] except (KeyError, TypeError): # raised by get_loc, see GH#29258 result_index = index else: result_index = ensure_index_from_sequences(index_data, names=index) exclude.update(index) if any(exclude): arr_exclude = [x for x in exclude if x in arr_columns] to_remove = [arr_columns.get_loc(col) for col in arr_exclude] arrays = [v for i, v in enumerate(arrays) if i not in to_remove] arr_columns = arr_columns.drop(arr_exclude) columns = columns.drop(exclude) manager = get_option("mode.data_manager") mgr = arrays_to_mgr(arrays, arr_columns, result_index, columns, typ=manager) return cls(mgr)
[ "def", "from_records", "(", "cls", ",", "data", ",", "index", "=", "None", ",", "exclude", "=", "None", ",", "columns", "=", "None", ",", "coerce_float", ":", "bool", "=", "False", ",", "nrows", ":", "int", "|", "None", "=", "None", ",", ")", "->",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/frame.py#L1944-L2124
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pbr/packaging.py
python
override_get_script_args
( dist, executable=os.path.normpath(sys.executable), is_wininst=False)
Override entrypoints console_script.
Override entrypoints console_script.
[ "Override", "entrypoints", "console_script", "." ]
def override_get_script_args( dist, executable=os.path.normpath(sys.executable), is_wininst=False): """Override entrypoints console_script.""" header = easy_install.get_script_header("", executable, is_wininst) for group, template in ENTRY_POINTS_MAP.items(): for name, ep in dist.get_entry_map(group).items(): yield (name, generate_script(group, ep, header, template))
[ "def", "override_get_script_args", "(", "dist", ",", "executable", "=", "os", ".", "path", ".", "normpath", "(", "sys", ".", "executable", ")", ",", "is_wininst", "=", "False", ")", ":", "header", "=", "easy_install", ".", "get_script_header", "(", "\"\"", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pbr/packaging.py#L398-L404
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/numbers.py
python
Complex.imag
(self)
Retrieve the imaginary component of this number. This should subclass Real.
Retrieve the imaginary component of this number.
[ "Retrieve", "the", "imaginary", "component", "of", "this", "number", "." ]
def imag(self): """Retrieve the imaginary component of this number. This should subclass Real. """ raise NotImplementedError
[ "def", "imag", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/numbers.py#L64-L69
HyeonwooNoh/caffe
d9e8494a2832d67b25dee37194c7bcb9d52d0e42
scripts/cpp_lint.py
python
_CppLintState.ResetErrorCounts
(self)
Sets the module's error statistic back to zero.
Sets the module's error statistic back to zero.
[ "Sets", "the", "module", "s", "error", "statistic", "back", "to", "zero", "." ]
def ResetErrorCounts(self): """Sets the module's error statistic back to zero.""" self.error_count = 0 self.errors_by_category = {}
[ "def", "ResetErrorCounts", "(", "self", ")", ":", "self", ".", "error_count", "=", "0", "self", ".", "errors_by_category", "=", "{", "}" ]
https://github.com/HyeonwooNoh/caffe/blob/d9e8494a2832d67b25dee37194c7bcb9d52d0e42/scripts/cpp_lint.py#L742-L745
ablab/spades
3a754192b88540524ce6fb69eef5ea9273a38465
webvis/pydot.py
python
Dot.write
(self, path, prog=None, format='raw')
return True
Writes a graph to a file. Given a filename 'path' it will open/create and truncate such file and write on it a representation of the graph defined by the dot object and in the format specified by 'format'. The format 'raw' is used to dump the string representation of the Dot object, without further processing. The output can be processed by any of graphviz tools, defined in 'prog', which defaults to 'dot' Returns True or False according to the success of the write operation. There's also the preferred possibility of using: write_'format'(path, prog='program') which are automatically defined for all the supported formats. [write_ps(), write_gif(), write_dia(), ...]
Writes a graph to a file.
[ "Writes", "a", "graph", "to", "a", "file", "." ]
def write(self, path, prog=None, format='raw'): """Writes a graph to a file. Given a filename 'path' it will open/create and truncate such file and write on it a representation of the graph defined by the dot object and in the format specified by 'format'. The format 'raw' is used to dump the string representation of the Dot object, without further processing. The output can be processed by any of graphviz tools, defined in 'prog', which defaults to 'dot' Returns True or False according to the success of the write operation. There's also the preferred possibility of using: write_'format'(path, prog='program') which are automatically defined for all the supported formats. [write_ps(), write_gif(), write_dia(), ...] """ if prog is None: prog = self.prog dot_fd = file(path, "w+b") if format == 'raw': data = self.to_string() if isinstance(data, basestring): if not isinstance(data, unicode): try: data = unicode(data, 'utf-8') except: pass try: data = data.encode('utf-8') except: pass dot_fd.write(data) else: dot_fd.write(self.create(prog, format)) dot_fd.close() return True
[ "def", "write", "(", "self", ",", "path", ",", "prog", "=", "None", ",", "format", "=", "'raw'", ")", ":", "if", "prog", "is", "None", ":", "prog", "=", "self", ".", "prog", "dot_fd", "=", "file", "(", "path", ",", "\"w+b\"", ")", "if", "format",...
https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/webvis/pydot.py#L1870-L1914
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/Chem/ChemUtils/SDFToCSV.py
python
initParser
()
return parser
Initialize the parser for the CLI
Initialize the parser for the CLI
[ "Initialize", "the", "parser", "for", "the", "CLI" ]
def initParser(): """ Initialize the parser for the CLI """ parser = argparse.ArgumentParser(description='Convert SDF file to CSV', formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--key', '-k', metavar='keyCol', default=None, dest='keyCol') parser.add_argument('--chiral', default=False, action='store_true', dest='useChirality') parser.add_argument('--smilesCol', metavar='smilesCol', default='') parser.add_argument('inFilename', metavar='inFile.sdf', type=existingFile) parser.add_argument('outF', nargs='?', type=argparse.FileType('w'), default=sys.stdout) return parser
[ "def", "initParser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Convert SDF file to CSV'", ",", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ")", "parser", ".", "add_argument", "(", "'--key'...
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/ChemUtils/SDFToCSV.py#L57-L66
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/asyncio/events.py
python
set_event_loop_policy
(policy)
Set the current event loop policy. If policy is None, the default policy is restored.
Set the current event loop policy.
[ "Set", "the", "current", "event", "loop", "policy", "." ]
def set_event_loop_policy(policy): """Set the current event loop policy. If policy is None, the default policy is restored.""" global _event_loop_policy assert policy is None or isinstance(policy, AbstractEventLoopPolicy) _event_loop_policy = policy
[ "def", "set_event_loop_policy", "(", "policy", ")", ":", "global", "_event_loop_policy", "assert", "policy", "is", "None", "or", "isinstance", "(", "policy", ",", "AbstractEventLoopPolicy", ")", "_event_loop_policy", "=", "policy" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/asyncio/events.py#L730-L736
danxuhk/ContinuousCRF-CNN
2b6dcaf179620f118b225ed12c890414ca828e21
scripts/cpp_lint.py
python
Match
(pattern, s)
return _regexp_compile_cache[pattern].match(s)
Matches the string with the pattern, caching the compiled regexp.
Matches the string with the pattern, caching the compiled regexp.
[ "Matches", "the", "string", "with", "the", "pattern", "caching", "the", "compiled", "regexp", "." ]
def Match(pattern, s): """Matches the string with the pattern, caching the compiled regexp.""" # The regexp compilation caching is inlined in both Match and Search for # performance reasons; factoring it out into a separate function turns out # to be noticeably expensive. if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].match(s)
[ "def", "Match", "(", "pattern", ",", "s", ")", ":", "# The regexp compilation caching is inlined in both Match and Search for", "# performance reasons; factoring it out into a separate function turns out", "# to be noticeably expensive.", "if", "pattern", "not", "in", "_regexp_compile_...
https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L519-L526
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
PythonAPI/carla/agents/navigation/behavior_agent.py
python
BehaviorAgent.collision_and_car_avoid_manager
(self, waypoint)
return vehicle_state, vehicle, distance
This module is in charge of warning in case of a collision and managing possible tailgating chances. :param location: current location of the agent :param waypoint: current waypoint of the agent :return vehicle_state: True if there is a vehicle nearby, False if not :return vehicle: nearby vehicle :return distance: distance to nearby vehicle
This module is in charge of warning in case of a collision and managing possible tailgating chances.
[ "This", "module", "is", "in", "charge", "of", "warning", "in", "case", "of", "a", "collision", "and", "managing", "possible", "tailgating", "chances", "." ]
def collision_and_car_avoid_manager(self, waypoint): """ This module is in charge of warning in case of a collision and managing possible tailgating chances. :param location: current location of the agent :param waypoint: current waypoint of the agent :return vehicle_state: True if there is a vehicle nearby, False if not :return vehicle: nearby vehicle :return distance: distance to nearby vehicle """ vehicle_list = self._world.get_actors().filter("*vehicle*") def dist(v): return v.get_location().distance(waypoint.transform.location) vehicle_list = [v for v in vehicle_list if dist(v) < 45 and v.id != self._vehicle.id] if self._direction == RoadOption.CHANGELANELEFT: vehicle_state, vehicle, distance = self._vehicle_obstacle_detected( vehicle_list, max( self._behavior.min_proximity_threshold, self._speed_limit / 2), up_angle_th=180, lane_offset=-1) elif self._direction == RoadOption.CHANGELANERIGHT: vehicle_state, vehicle, distance = self._vehicle_obstacle_detected( vehicle_list, max( self._behavior.min_proximity_threshold, self._speed_limit / 2), up_angle_th=180, lane_offset=1) else: vehicle_state, vehicle, distance = self._vehicle_obstacle_detected( vehicle_list, max( self._behavior.min_proximity_threshold, self._speed_limit / 3), up_angle_th=30) # Check for tailgating if not vehicle_state and self._direction == RoadOption.LANEFOLLOW \ and not waypoint.is_junction and self._speed > 10 \ and self._behavior.tailgate_counter == 0: self._tailgating(waypoint, vehicle_list) return vehicle_state, vehicle, distance
[ "def", "collision_and_car_avoid_manager", "(", "self", ",", "waypoint", ")", ":", "vehicle_list", "=", "self", ".", "_world", ".", "get_actors", "(", ")", ".", "filter", "(", "\"*vehicle*\"", ")", "def", "dist", "(", "v", ")", ":", "return", "v", ".", "g...
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/carla/agents/navigation/behavior_agent.py#L132-L167
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/hypertreelist.py
python
TreeListColumnInfo.SetEditable
(self, edit)
return self
Sets the column as editable or non-editable. :param `edit`: ``True`` if the column should be editable, ``False`` otherwise.
Sets the column as editable or non-editable.
[ "Sets", "the", "column", "as", "editable", "or", "non", "-", "editable", "." ]
def SetEditable(self, edit): """ Sets the column as editable or non-editable. :param `edit`: ``True`` if the column should be editable, ``False`` otherwise. """ self._edit = edit return self
[ "def", "SetEditable", "(", "self", ",", "edit", ")", ":", "self", ".", "_edit", "=", "edit", "return", "self" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L556-L564
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py
python
RawTurtle._update
(self)
Perform a Turtle-data update.
Perform a Turtle-data update.
[ "Perform", "a", "Turtle", "-", "data", "update", "." ]
def _update(self): """Perform a Turtle-data update. """ screen = self.screen if screen._tracing == 0: return elif screen._tracing == 1: self._update_data() self._drawturtle() screen._update() # TurtleScreenBase screen._delay(screen._delayvalue) # TurtleScreenBase else: self._update_data() if screen._updatecounter == 0: for t in screen.turtles(): t._drawturtle() screen._update()
[ "def", "_update", "(", "self", ")", ":", "screen", "=", "self", ".", "screen", "if", "screen", ".", "_tracing", "==", "0", ":", "return", "elif", "screen", ".", "_tracing", "==", "1", ":", "self", ".", "_update_data", "(", ")", "self", ".", "_drawtur...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py#L2557-L2573
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Script/Main.py
python
_scons_syntax_error
(e)
Handle syntax errors. Print out a message and show where the error occurred.
Handle syntax errors. Print out a message and show where the error occurred.
[ "Handle", "syntax", "errors", ".", "Print", "out", "a", "message", "and", "show", "where", "the", "error", "occurred", "." ]
def _scons_syntax_error(e): """Handle syntax errors. Print out a message and show where the error occurred. """ etype, value, tb = sys.exc_info() lines = traceback.format_exception_only(etype, value) for line in lines: sys.stderr.write(line+'\n') sys.exit(2)
[ "def", "_scons_syntax_error", "(", "e", ")", ":", "etype", ",", "value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "lines", "=", "traceback", ".", "format_exception_only", "(", "etype", ",", "value", ")", "for", "line", "in", "lines", ":", "sys...
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Script/Main.py#L542-L550
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/service_reflection.py
python
GeneratedServiceType.__init__
(cls, name, bases, dictionary)
Creates a message service class. Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type.
Creates a message service class.
[ "Creates", "a", "message", "service", "class", "." ]
def __init__(cls, name, bases, dictionary): """Creates a message service class. Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type. """ # Don't do anything if this class doesn't have a descriptor. This happens # when a service class is subclassed. if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary: return descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY] service_builder = _ServiceBuilder(descriptor) service_builder.BuildService(cls)
[ "def", "__init__", "(", "cls", ",", "name", ",", "bases", ",", "dictionary", ")", ":", "# Don't do anything if this class doesn't have a descriptor. This happens", "# when a service class is subclassed.", "if", "GeneratedServiceType", ".", "_DESCRIPTOR_KEY", "not", "in", "dic...
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/service_reflection.py#L64-L81
freesurfer/freesurfer
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
python/freesurfer/surface.py
python
Surface.compute_tangents
(self)
Compute and cache vertex tangents along primary curvature direction.
Compute and cache vertex tangents along primary curvature direction.
[ "Compute", "and", "cache", "vertex", "tangents", "along", "primary", "curvature", "direction", "." ]
def compute_tangents(self): '''Compute and cache vertex tangents along primary curvature direction.''' bindings.surf.compute_tangents(self)
[ "def", "compute_tangents", "(", "self", ")", ":", "bindings", ".", "surf", ".", "compute_tangents", "(", "self", ")" ]
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/python/freesurfer/surface.py#L74-L76