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
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Wm.wm_colormapwindows
(self, *wlist)
return map(self._nametowidget, self.tk.call(args))
Store list of window names (WLIST) into WM_COLORMAPWINDOWS property of this widget. This list contains windows whose colormaps differ from their parents. Return current list of widgets if WLIST is empty.
Store list of window names (WLIST) into WM_COLORMAPWINDOWS property of this widget. This list contains windows whose colormaps differ from their parents. Return current list of widgets if WLIST is empty.
[ "Store", "list", "of", "window", "names", "(", "WLIST", ")", "into", "WM_COLORMAPWINDOWS", "property", "of", "this", "widget", ".", "This", "list", "contains", "windows", "whose", "colormaps", "differ", "from", "their", "parents", ".", "Return", "current", "li...
def wm_colormapwindows(self, *wlist): """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property of this widget. This list contains windows whose colormaps differ from their parents. Return current list of widgets if WLIST is empty.""" if len(wlist) > 1: wlist = (wlist,) # Tk needs a list of windows here args = ('wm', 'colormapwindows', self._w) + wlist return map(self._nametowidget, self.tk.call(args))
[ "def", "wm_colormapwindows", "(", "self", ",", "*", "wlist", ")", ":", "if", "len", "(", "wlist", ")", ">", "1", ":", "wlist", "=", "(", "wlist", ",", ")", "# Tk needs a list of windows here", "args", "=", "(", "'wm'", ",", "'colormapwindows'", ",", "sel...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1561-L1568
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/layer2.py
python
Layer2.update_throughput
(self, table, read_units, write_units)
Update the ProvisionedThroughput for the Amazon DynamoDB Table. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object whose throughput is being updated. :type read_units: int :param read_units: The new value for ReadCapacityUnits. :type write_units: int :param write_units: The new value for WriteCapacityUnits.
Update the ProvisionedThroughput for the Amazon DynamoDB Table.
[ "Update", "the", "ProvisionedThroughput", "for", "the", "Amazon", "DynamoDB", "Table", "." ]
def update_throughput(self, table, read_units, write_units): """ Update the ProvisionedThroughput for the Amazon DynamoDB Table. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object whose throughput is being updated. :type read_units: int :param read_units: The new value for ReadCapacityUnits. :type write_units: int :param write_units: The new value for WriteCapacityUnits. """ response = self.layer1.update_table(table.name, {'ReadCapacityUnits': read_units, 'WriteCapacityUnits': write_units}) table.update_from_response(response)
[ "def", "update_throughput", "(", "self", ",", "table", ",", "read_units", ",", "write_units", ")", ":", "response", "=", "self", ".", "layer1", ".", "update_table", "(", "table", ".", "name", ",", "{", "'ReadCapacityUnits'", ":", "read_units", ",", "'WriteCa...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/layer2.py#L392-L408
abforce/xposed_art_n
ec3fbe417d74d4664cec053d91dd4e3881176374
tools/cpplint.py
python
CheckComment
(comment, filename, linenum, error)
Checks for common mistakes in TODO comments. Args: comment: The text of the comment from the line in question. filename: The name of the current file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for common mistakes in TODO comments.
[ "Checks", "for", "common", "mistakes", "in", "TODO", "comments", "." ]
def CheckComment(comment, filename, linenum, error): """Checks for common mistakes in TODO comments. Args: comment: The text of the comment from the line in question. filename: The name of the current file. linenum: The number of the line to check. error: The function to call with any errors found. """ match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable-msg=C6403 if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space')
[ "def", "CheckComment", "(", "comment", ",", "filename", ",", "linenum", ",", "error", ")", ":", "match", "=", "_RE_PATTERN_TODO", ".", "match", "(", "comment", ")", "if", "match", ":", "# One whitespace is correct; zero whitespace is handled elsewhere.", "leading_whit...
https://github.com/abforce/xposed_art_n/blob/ec3fbe417d74d4664cec053d91dd4e3881176374/tools/cpplint.py#L2048-L2075
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/sat/samples/stop_after_n_solutions_sample_sat.py
python
StopAfterNSolutionsSampleSat
()
Showcases calling the solver to search for small number of solutions.
Showcases calling the solver to search for small number of solutions.
[ "Showcases", "calling", "the", "solver", "to", "search", "for", "small", "number", "of", "solutions", "." ]
def StopAfterNSolutionsSampleSat(): """Showcases calling the solver to search for small number of solutions.""" # Creates the model. model = cp_model.CpModel() # Creates the variables. num_vals = 3 x = model.NewIntVar(0, num_vals - 1, 'x') y = model.NewIntVar(0, num_vals - 1, 'y') z = model.NewIntVar(0, num_vals - 1, 'z') # Create a solver and solve. solver = cp_model.CpSolver() solution_printer = VarArraySolutionPrinterWithLimit([x, y, z], 5) # Enumerate all solutions. solver.parameters.enumerate_all_solutions = True # Solve. status = solver.Solve(model, solution_printer) print('Status = %s' % solver.StatusName(status)) print('Number of solutions found: %i' % solution_printer.solution_count()) assert solution_printer.solution_count() == 5
[ "def", "StopAfterNSolutionsSampleSat", "(", ")", ":", "# Creates the model.", "model", "=", "cp_model", ".", "CpModel", "(", ")", "# Creates the variables.", "num_vals", "=", "3", "x", "=", "model", ".", "NewIntVar", "(", "0", ",", "num_vals", "-", "1", ",", ...
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/samples/stop_after_n_solutions_sample_sat.py#L42-L61
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Alignment/MuonAlignment/python/svgfig.py
python
Ticks.SVG
(self, trans=None)
return output
Apply the transformation "trans" and return an SVG object.
Apply the transformation "trans" and return an SVG object.
[ "Apply", "the", "transformation", "trans", "and", "return", "an", "SVG", "object", "." ]
def SVG(self, trans=None): """Apply the transformation "trans" and return an SVG object.""" if isinstance(trans, str): trans = totrans(trans) self.last_ticks, self.last_miniticks = self.interpret() tickmarks = Path([], **self.attr) minitickmarks = Path([], **self.attr) output = SVG("g") if (self.arrow_start != False and self.arrow_start != None) or (self.arrow_end != False and self.arrow_end != None): defs = SVG("defs") if self.arrow_start != False and self.arrow_start != None: if isinstance(self.arrow_start, SVG): defs.append(self.arrow_start) elif isinstance(self.arrow_start, str): defs.append(make_marker(self.arrow_start, "arrow_start")) else: raise TypeError("arrow_start must be False/None or an id string for the new marker") if self.arrow_end != False and self.arrow_end != None: if isinstance(self.arrow_end, SVG): defs.append(self.arrow_end) elif isinstance(self.arrow_end, str): defs.append(make_marker(self.arrow_end, "arrow_end")) else: raise TypeError("arrow_end must be False/None or an id string for the new marker") output.append(defs) eps = _epsilon * (self.high - self.low) for t, label in self.last_ticks.items(): (X, Y), (xhatx, xhaty), (yhatx, yhaty), angle = self.orient_tickmark(t, trans) if (not self.arrow_start or abs(t - self.low) > eps) and (not self.arrow_end or abs(t - self.high) > eps): tickmarks.d.append(("M", X - yhatx*self.tick_start, Y - yhaty*self.tick_start, True)) tickmarks.d.append(("L", X - yhatx*self.tick_end, Y - yhaty*self.tick_end, True)) angle = (angle - math.pi/2.)*180./math.pi + self.text_angle ########### a HACK! ############ (to be removed when Inkscape handles baselines) if _hacks["inkscape-text-vertical-shift"]: if self.text_start > 0: X += math.cos(angle*math.pi/180. + math.pi/2.) * 2. Y += math.sin(angle*math.pi/180. + math.pi/2.) * 2. else: X += math.cos(angle*math.pi/180. + math.pi/2.) * 2. * 2.5 Y += math.sin(angle*math.pi/180. + math.pi/2.) * 2. * 2.5 ########### end hack ########### if label != "": output.append(SVG("text", label, transform="translate(%g, %g) rotate(%g)" % \ (X - yhatx*self.text_start, Y - yhaty*self.text_start, angle), **self.text_attr)) for t in self.last_miniticks: skip = False for tt in self.last_ticks.keys(): if abs(t - tt) < eps: skip = True break if not skip: (X, Y), (xhatx, xhaty), (yhatx, yhaty), angle = self.orient_tickmark(t, trans) if (not self.arrow_start or abs(t - self.low) > eps) and (not self.arrow_end or abs(t - self.high) > eps): minitickmarks.d.append(("M", X - yhatx*self.minitick_start, Y - yhaty*self.minitick_start, True)) minitickmarks.d.append(("L", X - yhatx*self.minitick_end, Y - yhaty*self.minitick_end, True)) output.prepend(tickmarks.SVG(trans)) output.prepend(minitickmarks.SVG(trans)) return output
[ "def", "SVG", "(", "self", ",", "trans", "=", "None", ")", ":", "if", "isinstance", "(", "trans", ",", "str", ")", ":", "trans", "=", "totrans", "(", "trans", ")", "self", ".", "last_ticks", ",", "self", ".", "last_miniticks", "=", "self", ".", "in...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/MuonAlignment/python/svgfig.py#L2436-L2506
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Node/FS.py
python
Base.__lt__
(self, other)
return str(self) < str(other)
less than operator used by sorting on py3
less than operator used by sorting on py3
[ "less", "than", "operator", "used", "by", "sorting", "on", "py3" ]
def __lt__(self, other): """ less than operator used by sorting on py3""" return str(self) < str(other)
[ "def", "__lt__", "(", "self", ",", "other", ")", ":", "return", "str", "(", "self", ")", "<", "str", "(", "other", ")" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/FS.py#L653-L655
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/command_parser.py
python
validate_slicing_string
(slicing_string)
return bool(re.search(r"^\[(\d|,|\s|:)+\]$", slicing_string))
Validate a slicing string. Check if the input string contains only brackets, digits, commas and colons that are valid characters in numpy-style array slicing. Args: slicing_string: (str) Input slicing string to be validated. Returns: (bool) True if and only if the slicing string is valid.
Validate a slicing string.
[ "Validate", "a", "slicing", "string", "." ]
def validate_slicing_string(slicing_string): """Validate a slicing string. Check if the input string contains only brackets, digits, commas and colons that are valid characters in numpy-style array slicing. Args: slicing_string: (str) Input slicing string to be validated. Returns: (bool) True if and only if the slicing string is valid. """ return bool(re.search(r"^\[(\d|,|\s|:)+\]$", slicing_string))
[ "def", "validate_slicing_string", "(", "slicing_string", ")", ":", "return", "bool", "(", "re", ".", "search", "(", "r\"^\\[(\\d|,|\\s|:)+\\]$\"", ",", "slicing_string", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/command_parser.py#L174-L187
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/base.py
python
_load_global_helpers
()
Execute once to install special symbols into the LLVM symbol table.
Execute once to install special symbols into the LLVM symbol table.
[ "Execute", "once", "to", "install", "special", "symbols", "into", "the", "LLVM", "symbol", "table", "." ]
def _load_global_helpers(): """ Execute once to install special symbols into the LLVM symbol table. """ # This is Py_None's real C name ll.add_symbol("_Py_NoneStruct", id(None)) # Add Numba C helper functions for c_helpers in (_helperlib.c_helpers, _dynfunc.c_helpers): for py_name, c_address in c_helpers.items(): c_name = "numba_" + py_name ll.add_symbol(c_name, c_address) # Add Numpy C helpers (npy_XXX) for c_name, c_address in _helperlib.npymath_exports.items(): ll.add_symbol(c_name, c_address) # Add all built-in exception classes for obj in utils.builtins.__dict__.values(): if isinstance(obj, type) and issubclass(obj, BaseException): ll.add_symbol("PyExc_%s" % (obj.__name__), id(obj))
[ "def", "_load_global_helpers", "(", ")", ":", "# This is Py_None's real C name", "ll", ".", "add_symbol", "(", "\"_Py_NoneStruct\"", ",", "id", "(", "None", ")", ")", "# Add Numba C helper functions", "for", "c_helpers", "in", "(", "_helperlib", ".", "c_helpers", ",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/base.py#L153-L173
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
Process.Kill
(*args, **kwargs)
return _misc_.Process_Kill(*args, **kwargs)
Kill(int pid, int sig=SIGTERM, int flags=KILL_NOCHILDREN) -> int
Kill(int pid, int sig=SIGTERM, int flags=KILL_NOCHILDREN) -> int
[ "Kill", "(", "int", "pid", "int", "sig", "=", "SIGTERM", "int", "flags", "=", "KILL_NOCHILDREN", ")", "-", ">", "int" ]
def Kill(*args, **kwargs): """Kill(int pid, int sig=SIGTERM, int flags=KILL_NOCHILDREN) -> int""" return _misc_.Process_Kill(*args, **kwargs)
[ "def", "Kill", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Process_Kill", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1964-L1966
johmathe/shotdetect
1ecf93a695c96fd7601a41ab5834f1117b9d7d50
tools/cpplint.py
python
_FunctionState.Begin
(self, function_name)
Start analyzing function body. Args: function_name: The name of the function being tracked.
Start analyzing function body.
[ "Start", "analyzing", "function", "body", "." ]
def Begin(self, function_name): """Start analyzing function body. Args: function_name: The name of the function being tracked. """ self.in_a_function = True self.lines_in_function = 0 self.current_function = function_name
[ "def", "Begin", "(", "self", ",", "function_name", ")", ":", "self", ".", "in_a_function", "=", "True", "self", ".", "lines_in_function", "=", "0", "self", ".", "current_function", "=", "function_name" ]
https://github.com/johmathe/shotdetect/blob/1ecf93a695c96fd7601a41ab5834f1117b9d7d50/tools/cpplint.py#L625-L633
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
sp/src/thirdparty/protobuf-2.3.0/python/mox.py
python
MockObject.__call__
(self, *params, **named_params)
return mock_method(*params, **named_params)
Provide custom logic for mocking classes that are callable.
Provide custom logic for mocking classes that are callable.
[ "Provide", "custom", "logic", "for", "mocking", "classes", "that", "are", "callable", "." ]
def __call__(self, *params, **named_params): """Provide custom logic for mocking classes that are callable.""" # Verify the class we are mocking is callable callable = self._class_to_mock.__dict__.get('__call__', None) if callable is None: raise TypeError('Not callable') # Because the call is happening directly on this object instead of a method, # the call on the mock method is made right here mock_method = self._CreateMockMethod('__call__') return mock_method(*params, **named_params)
[ "def", "__call__", "(", "self", ",", "*", "params", ",", "*", "*", "named_params", ")", ":", "# Verify the class we are mocking is callable", "callable", "=", "self", ".", "_class_to_mock", ".", "__dict__", ".", "get", "(", "'__call__'", ",", "None", ")", "if"...
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/mox.py#L490-L501
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Context.py
python
Context.execute
(self)
Execute the command. Redefine this method in subclasses.
Execute the command. Redefine this method in subclasses.
[ "Execute", "the", "command", ".", "Redefine", "this", "method", "in", "subclasses", "." ]
def execute(self): """ Execute the command. Redefine this method in subclasses. """ global g_module self.recurse([os.path.dirname(g_module.root_path)])
[ "def", "execute", "(", "self", ")", ":", "global", "g_module", "self", ".", "recurse", "(", "[", "os", ".", "path", ".", "dirname", "(", "g_module", ".", "root_path", ")", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Context.py#L220-L225
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBSymbol.GetStartAddress
(self)
return _lldb.SBSymbol_GetStartAddress(self)
GetStartAddress(self) -> SBAddress
GetStartAddress(self) -> SBAddress
[ "GetStartAddress", "(", "self", ")", "-", ">", "SBAddress" ]
def GetStartAddress(self): """GetStartAddress(self) -> SBAddress""" return _lldb.SBSymbol_GetStartAddress(self)
[ "def", "GetStartAddress", "(", "self", ")", ":", "return", "_lldb", ".", "SBSymbol_GetStartAddress", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L8115-L8117
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibar.py
python
AuiToolBar.SetMarginsSize
(self, size)
Set the values to be used as margins for the toolbar. :param Size `size`: the margin size (an instance of :class:`Size`).
Set the values to be used as margins for the toolbar.
[ "Set", "the", "values", "to", "be", "used", "as", "margins", "for", "the", "toolbar", "." ]
def SetMarginsSize(self, size): """ Set the values to be used as margins for the toolbar. :param Size `size`: the margin size (an instance of :class:`Size`). """ self.SetMargins(size.x, size.x, size.y, size.y)
[ "def", "SetMarginsSize", "(", "self", ",", "size", ")", ":", "self", ".", "SetMargins", "(", "size", ".", "x", ",", "size", ".", "x", ",", "size", ".", "y", ",", "size", ".", "y", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L2453-L2460
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/webapp2/webapp2.py
python
WSGIApplication.clear_globals
(self)
Clears global variables. See :meth:`set_globals`.
Clears global variables. See :meth:`set_globals`.
[ "Clears", "global", "variables", ".", "See", ":", "meth", ":", "set_globals", "." ]
def clear_globals(self): """Clears global variables. See :meth:`set_globals`.""" if _local is not None: # pragma: no cover _local.__release_local__() else: # pragma: no cover WSGIApplication.app = WSGIApplication.active_instance = None WSGIApplication.request = None
[ "def", "clear_globals", "(", "self", ")", ":", "if", "_local", "is", "not", "None", ":", "# pragma: no cover", "_local", ".", "__release_local__", "(", ")", "else", ":", "# pragma: no cover", "WSGIApplication", ".", "app", "=", "WSGIApplication", ".", "active_in...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2.py#L1505-L1511
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
samples/python/efficientnet/build_engine.py
python
EngineCalibrator.get_batch
(self, names)
Overrides from trt.IInt8EntropyCalibrator2. Get the next batch to use for calibration, as a list of device memory pointers. :param names: The names of the inputs, if useful to define the order of inputs. :return: A list of int-casted memory pointers.
Overrides from trt.IInt8EntropyCalibrator2. Get the next batch to use for calibration, as a list of device memory pointers. :param names: The names of the inputs, if useful to define the order of inputs. :return: A list of int-casted memory pointers.
[ "Overrides", "from", "trt", ".", "IInt8EntropyCalibrator2", ".", "Get", "the", "next", "batch", "to", "use", "for", "calibration", "as", "a", "list", "of", "device", "memory", "pointers", ".", ":", "param", "names", ":", "The", "names", "of", "the", "input...
def get_batch(self, names): """ Overrides from trt.IInt8EntropyCalibrator2. Get the next batch to use for calibration, as a list of device memory pointers. :param names: The names of the inputs, if useful to define the order of inputs. :return: A list of int-casted memory pointers. """ if not self.image_batcher: return None try: batch, _ = next(self.batch_generator) log.info("Calibrating image {} / {}".format(self.image_batcher.image_index, self.image_batcher.num_images)) cuda.memcpy_htod(self.batch_allocation, np.ascontiguousarray(batch)) return [int(self.batch_allocation)] except StopIteration: log.info("Finished calibration batches") return None
[ "def", "get_batch", "(", "self", ",", "names", ")", ":", "if", "not", "self", ".", "image_batcher", ":", "return", "None", "try", ":", "batch", ",", "_", "=", "next", "(", "self", ".", "batch_generator", ")", "log", ".", "info", "(", "\"Calibrating ima...
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/efficientnet/build_engine.py#L70-L86
brave/brave-core
ceaa3de4735789d355b6fa80c21d4709e2c1d0e8
script/lib/transifex.py
python
get_auth
()
return auth
Creates an HTTPBasicAuth object given the Transifex information
Creates an HTTPBasicAuth object given the Transifex information
[ "Creates", "an", "HTTPBasicAuth", "object", "given", "the", "Transifex", "information" ]
def get_auth(): """Creates an HTTPBasicAuth object given the Transifex information""" username = get_env_var('TRANSIFEX_USERNAME') password = get_env_var('TRANSIFEX_PASSWORD') transifex_api_key = get_env_var('TRANSIFEX_API_KEY') auth = None if transifex_api_key: api_key_username = "api:" + transifex_api_key auth = requests.auth.HTTPBasicAuth(api_key_username, '') else: auth = requests.auth.HTTPBasicAuth(username, password) return auth
[ "def", "get_auth", "(", ")", ":", "username", "=", "get_env_var", "(", "'TRANSIFEX_USERNAME'", ")", "password", "=", "get_env_var", "(", "'TRANSIFEX_PASSWORD'", ")", "transifex_api_key", "=", "get_env_var", "(", "'TRANSIFEX_API_KEY'", ")", "auth", "=", "None", "if...
https://github.com/brave/brave-core/blob/ceaa3de4735789d355b6fa80c21d4709e2c1d0e8/script/lib/transifex.py#L104-L115
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
lldb/packages/Python/lldbsuite/support/seven.py
python
hexlify
(data)
return bitcast_to_string(binascii.hexlify(bitcast_to_bytes(data)))
Hex-encode string data. The result if always a string.
Hex-encode string data. The result if always a string.
[ "Hex", "-", "encode", "string", "data", ".", "The", "result", "if", "always", "a", "string", "." ]
def hexlify(data): """Hex-encode string data. The result if always a string.""" return bitcast_to_string(binascii.hexlify(bitcast_to_bytes(data)))
[ "def", "hexlify", "(", "data", ")", ":", "return", "bitcast_to_string", "(", "binascii", ".", "hexlify", "(", "bitcast_to_bytes", "(", "data", ")", ")", ")" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/packages/Python/lldbsuite/support/seven.py#L49-L51
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/input.py
python
ProcessVariablesAndConditionsInDict
(the_dict, phase, variables_in, build_file, the_dict_key=None)
Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. The variables_in dictionary will not be modified by this function.
Handle all variable and command expansion and conditional evaluation.
[ "Handle", "all", "variable", "and", "command", "expansion", "and", "conditional", "evaluation", "." ]
def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in, build_file, the_dict_key=None): """Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. The variables_in dictionary will not be modified by this function. """ # Make a copy of the variables_in dict that can be modified during the # loading of automatics and the loading of the variables dict. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) if 'variables' in the_dict: # Make sure all the local variables are added to the variables # list before we process them so that you can reference one # variable from another. They will be fully expanded by recursion # in ExpandVariables. for key, value in the_dict['variables'].iteritems(): variables[key] = value # Handle the associated variables dict first, so that any variable # references within can be resolved prior to using them as variables. # Pass a copy of the variables dict to avoid having it be tainted. # Otherwise, it would have extra automatics added for everything that # should just be an ordinary variable in this scope. ProcessVariablesAndConditionsInDict(the_dict['variables'], phase, variables, build_file, 'variables') LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) for key, value in the_dict.iteritems(): # Skip "variables", which was already processed if present. if key != 'variables' and type(value) is str: expanded = ExpandVariables(value, phase, variables, build_file) if type(expanded) not in (str, int): raise ValueError( 'Variable expansion in this context permits str and int ' + \ 'only, found ' + expanded.__class__.__name__ + ' for ' + key) the_dict[key] = expanded # Variable expansion may have resulted in changes to automatics. Reload. # TODO(mark): Optimization: only reload if no changes were made. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Process conditions in this dict. This is done after variable expansion # so that conditions may take advantage of expanded variables. For example, # if the_dict contains: # {'type': '<(library_type)', # 'conditions': [['_type=="static_library"', { ... }]]}, # _type, as used in the condition, will only be set to the value of # library_type if variable expansion is performed before condition # processing. However, condition processing should occur prior to recursion # so that variables (both automatic and "variables" dict type) may be # adjusted by conditions sections, merged into the_dict, and have the # intended impact on contained dicts. # # This arrangement means that a "conditions" section containing a "variables" # section will only have those variables effective in subdicts, not in # the_dict. The workaround is to put a "conditions" section within a # "variables" section. For example: # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]], # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will not result in "IS_MAC" being appended to the "defines" list in the # current scope but would result in it being appended to the "defines" list # within "my_subdict". By comparison: # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]}, # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will append "IS_MAC" to both "defines" lists. # Evaluate conditions sections, allowing variable expansions within them # as well as nested conditionals. This will process a 'conditions' or # 'target_conditions' section, perform appropriate merging and recursive # conditional and variable processing, and then remove the conditions section # from the_dict if it is present. ProcessConditionsInDict(the_dict, phase, variables, build_file) # Conditional processing may have resulted in changes to automatics or the # variables dict. Reload. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Recurse into child dicts, or process child lists which may result in # further recursion into descendant dicts. for key, value in the_dict.iteritems(): # Skip "variables" and string values, which were already processed if # present. if key == 'variables' or type(value) is str: continue if type(value) is dict: # Pass a copy of the variables dict so that subdicts can't influence # parents. ProcessVariablesAndConditionsInDict(value, phase, variables, build_file, key) elif type(value) is list: # The list itself can't influence the variables dict, and # ProcessVariablesAndConditionsInList will make copies of the variables # dict if it needs to pass it to something that can influence it. No # copy is necessary here. ProcessVariablesAndConditionsInList(value, phase, variables, build_file) elif type(value) is not int: raise TypeError('Unknown type ' + value.__class__.__name__ + \ ' for ' + key)
[ "def", "ProcessVariablesAndConditionsInDict", "(", "the_dict", ",", "phase", ",", "variables_in", ",", "build_file", ",", "the_dict_key", "=", "None", ")", ":", "# Make a copy of the variables_in dict that can be modified during the", "# loading of automatics and the loading of the...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/input.py#L1187-L1296
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/processor/conversion/ror/processor.py
python
RoRProcessor.create_entity_lines
(gamespec, full_data_set)
Sort units/buildings into lines, based on information from techs and civs. :param full_data_set: GenieObjectContainer instance that contains all relevant data for the conversion process. :type full_data_set: class: ...dataformat.aoc.genie_object_container.GenieObjectContainer
Sort units/buildings into lines, based on information from techs and civs.
[ "Sort", "units", "/", "buildings", "into", "lines", "based", "on", "information", "from", "techs", "and", "civs", "." ]
def create_entity_lines(gamespec, full_data_set): """ Sort units/buildings into lines, based on information from techs and civs. :param full_data_set: GenieObjectContainer instance that contains all relevant data for the conversion process. :type full_data_set: class: ...dataformat.aoc.genie_object_container.GenieObjectContainer """ # Search a player civ (egyptians) for the starting units player_civ_units = gamespec[0]["civs"][1]["units"].get_value() task_group_ids = set() villager_unit_ids = set() for raw_unit in player_civ_units.values(): unit_id = raw_unit["id0"].get_value() enabled = raw_unit["enabled"].get_value() entity = full_data_set.genie_units[unit_id] if not enabled: # Unlocked by tech continue unit_type = entity["unit_type"].get_value() if unit_type == 70: if entity.has_member("task_group") and\ entity["task_group"].get_value() > 0: task_group_id = entity["task_group"].get_value() villager_unit_ids.add(unit_id) if task_group_id in task_group_ids: task_group = full_data_set.task_groups[task_group_id] task_group.add_unit(entity) else: if task_group_id == 1: line_id = RoRUnitTaskGroup.male_line_id task_group = RoRUnitTaskGroup(line_id, task_group_id, -1, full_data_set) task_group.add_unit(entity) task_group_ids.add(task_group_id) full_data_set.task_groups.update({task_group_id: task_group}) else: unit_line = RoRUnitLineGroup(unit_id, -1, full_data_set) unit_line.add_unit(entity) full_data_set.unit_lines.update({unit_line.get_id(): unit_line}) full_data_set.unit_ref.update({unit_id: unit_line}) elif unit_type == 80: building_line = RoRBuildingLineGroup(unit_id, -1, full_data_set) building_line.add_unit(entity) full_data_set.building_lines.update({building_line.get_id(): building_line}) full_data_set.unit_ref.update({unit_id: building_line}) # Create the villager task group villager = RoRVillagerGroup(118, task_group_ids, full_data_set) full_data_set.unit_lines.update({villager.get_id(): villager}) full_data_set.villager_groups.update({villager.get_id(): villager}) for unit_id in villager_unit_ids: full_data_set.unit_ref.update({unit_id: villager}) # Other units unlocks through techs unit_unlocks = full_data_set.unit_unlocks for unit_unlock in unit_unlocks.values(): line_id = unit_unlock.get_line_id() unit = full_data_set.genie_units[line_id] unit_line = RoRUnitLineGroup(line_id, unit_unlock.get_id(), full_data_set) unit_line.add_unit(unit) full_data_set.unit_lines.update({unit_line.get_id(): unit_line}) full_data_set.unit_ref.update({line_id: unit_line}) # Check if the tech unlocks other lines # TODO: Make this cleaner unlock_effects = unit_unlock.get_effects(effect_type=2) for unlock_effect in unlock_effects: line_id = unlock_effect["attr_a"].get_value() unit = full_data_set.genie_units[line_id] if line_id not in full_data_set.unit_lines.keys(): unit_line = RoRUnitLineGroup(line_id, unit_unlock.get_id(), full_data_set) unit_line.add_unit(unit) full_data_set.unit_lines.update({unit_line.get_id(): unit_line}) full_data_set.unit_ref.update({line_id: unit_line}) # Upgraded units in a line unit_upgrades = full_data_set.unit_upgrades for unit_upgrade in unit_upgrades.values(): line_id = unit_upgrade.get_line_id() target_id = unit_upgrade.get_upgrade_target_id() unit = full_data_set.genie_units[target_id] # Find the previous unit in the line required_techs = unit_upgrade.tech["required_techs"].get_value() for required_tech in required_techs: required_tech_id = required_tech.get_value() if required_tech_id in full_data_set.unit_unlocks.keys(): source_id = full_data_set.unit_unlocks[required_tech_id].get_line_id() break if required_tech_id in full_data_set.unit_upgrades.keys(): source_id = full_data_set.unit_upgrades[required_tech_id].get_upgrade_target_id() break unit_line = full_data_set.unit_lines[line_id] unit_line.add_unit(unit, after=source_id) full_data_set.unit_ref.update({target_id: unit_line}) # Other buildings unlocks through techs building_unlocks = full_data_set.building_unlocks for building_unlock in building_unlocks.values(): line_id = building_unlock.get_line_id() building = full_data_set.genie_units[line_id] building_line = RoRBuildingLineGroup(line_id, building_unlock.get_id(), full_data_set) building_line.add_unit(building) full_data_set.building_lines.update({building_line.get_id(): building_line}) full_data_set.unit_ref.update({line_id: building_line}) # Upgraded buildings through techs building_upgrades = full_data_set.building_upgrades for building_upgrade in building_upgrades.values(): line_id = building_upgrade.get_line_id() target_id = building_upgrade.get_upgrade_target_id() unit = full_data_set.genie_units[target_id] # Find the previous unit in the line required_techs = building_upgrade.tech["required_techs"].get_value() for required_tech in required_techs: required_tech_id = required_tech.get_value() if required_tech_id in full_data_set.building_unlocks.keys(): source_id = full_data_set.building_unlocks[required_tech_id].get_line_id() break if required_tech_id in full_data_set.building_upgrades.keys(): source_id = full_data_set.building_upgrades[required_tech_id].get_upgrade_target_id() break building_line = full_data_set.building_lines[line_id] building_line.add_unit(unit, after=source_id) full_data_set.unit_ref.update({target_id: building_line}) # Upgraded units/buildings through age ups age_ups = full_data_set.age_upgrades for age_up in age_ups.values(): effects = age_up.get_effects(effect_type=3) for effect in effects: source_id = effect["attr_a"].get_value() target_id = effect["attr_b"].get_value() unit = full_data_set.genie_units[target_id] if source_id in full_data_set.building_lines.keys(): building_line = full_data_set.building_lines[source_id] building_line.add_unit(unit, after=source_id) full_data_set.unit_ref.update({target_id: building_line}) elif source_id in full_data_set.unit_lines.keys(): unit_line = full_data_set.unit_lines[source_id] unit_line.add_unit(unit, after=source_id) full_data_set.unit_ref.update({target_id: unit_line})
[ "def", "create_entity_lines", "(", "gamespec", ",", "full_data_set", ")", ":", "# Search a player civ (egyptians) for the starting units", "player_civ_units", "=", "gamespec", "[", "0", "]", "[", "\"civs\"", "]", "[", "1", "]", "[", "\"units\"", "]", ".", "get_value...
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/ror/processor.py#L222-L383
liulei01/DRBox
b5c76e033c555c9009590ab384e1f7bd3c66c237
python/caffe/io.py
python
resize_image
(im, new_dims, interp_order=1)
return resized_im.astype(np.float32)
Resize an image array with interpolation. Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. interp_order : interpolation order, default is linear. Returns ------- im : resized ndarray with shape (new_dims[0], new_dims[1], K)
Resize an image array with interpolation.
[ "Resize", "an", "image", "array", "with", "interpolation", "." ]
def resize_image(im, new_dims, interp_order=1): """ Resize an image array with interpolation. Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. interp_order : interpolation order, default is linear. Returns ------- im : resized ndarray with shape (new_dims[0], new_dims[1], K) """ if im.shape[-1] == 1 or im.shape[-1] == 3: im_min, im_max = im.min(), im.max() if im_max > im_min: # skimage is fast but only understands {1,3} channel images # in [0, 1]. im_std = (im - im_min) / (im_max - im_min) resized_std = resize(im_std, new_dims, order=interp_order) resized_im = resized_std * (im_max - im_min) + im_min else: # the image is a constant -- avoid divide by 0 ret = np.empty((new_dims[0], new_dims[1], im.shape[-1]), dtype=np.float32) ret.fill(im_min) return ret else: # ndimage interpolates anything but more slowly. scale = tuple(np.array(new_dims, dtype=float) / np.array(im.shape[:2])) resized_im = zoom(im, scale + (1,), order=interp_order) return resized_im.astype(np.float32)
[ "def", "resize_image", "(", "im", ",", "new_dims", ",", "interp_order", "=", "1", ")", ":", "if", "im", ".", "shape", "[", "-", "1", "]", "==", "1", "or", "im", ".", "shape", "[", "-", "1", "]", "==", "3", ":", "im_min", ",", "im_max", "=", "...
https://github.com/liulei01/DRBox/blob/b5c76e033c555c9009590ab384e1f7bd3c66c237/python/caffe/io.py#L306-L338
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/packaging/version.py
python
_parse_local_version
(local)
return None
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
[ "Takes", "a", "string", "like", "abc", ".", "1", ".", "twelve", "and", "turns", "it", "into", "(", "abc", "1", "twelve", ")", "." ]
def _parse_local_version(local): # type: (str) -> Optional[LocalType] """ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) for part in _local_version_separators.split(local) ) return None
[ "def", "_parse_local_version", "(", "local", ")", ":", "# type: (str) -> Optional[LocalType]", "if", "local", "is", "not", "None", ":", "return", "tuple", "(", "part", ".", "lower", "(", ")", "if", "not", "part", ".", "isdigit", "(", ")", "else", "int", "(...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/packaging/version.py#L482-L492
tum-vision/fusenet
a1451be2971b348a01b0f525c2a3a7a0e215a591
scripts/cpp_lint.py
python
_NamespaceInfo.CheckEnd
(self, filename, clean_lines, linenum, error)
Check end of namespace comments.
Check end of namespace comments.
[ "Check", "end", "of", "namespace", "comments", "." ]
def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace"')
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "raw_lines", "[", "linenum", "]", "# Check how many lines is enclosed in this namespace. Don't issue", "# warning for missing n...
https://github.com/tum-vision/fusenet/blob/a1451be2971b348a01b0f525c2a3a7a0e215a591/scripts/cpp_lint.py#L1856-L1899
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/lite/python/tflite_keras_util.py
python
create_pseudo_output_names
(outputs)
return _create_pseudo_names(outputs, prefix='output_')
Create pseudo output names for a subclassed Model.
Create pseudo output names for a subclassed Model.
[ "Create", "pseudo", "output", "names", "for", "a", "subclassed", "Model", "." ]
def create_pseudo_output_names(outputs): """Create pseudo output names for a subclassed Model.""" return _create_pseudo_names(outputs, prefix='output_')
[ "def", "create_pseudo_output_names", "(", "outputs", ")", ":", "return", "_create_pseudo_names", "(", "outputs", ",", "prefix", "=", "'output_'", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/tflite_keras_util.py#L152-L154
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
python/mxnet/ndarray.py
python
_init_ndarray_module
()
List and add all the ndarray functions to current module.
List and add all the ndarray functions to current module.
[ "List", "and", "add", "all", "the", "ndarray", "functions", "to", "current", "module", "." ]
def _init_ndarray_module(): """List and add all the ndarray functions to current module.""" plist = ctypes.POINTER(FunctionHandle)() size = ctypes.c_uint() check_call(_LIB.MXListFunctions(ctypes.byref(size), ctypes.byref(plist))) module_obj = sys.modules[__name__] for i in range(size.value): hdl = FunctionHandle(plist[i]) function = _make_ndarray_function(hdl) # if function name starts with underscore, register as static method of NDArray if function.__name__.startswith('_'): setattr(NDArray, function.__name__, staticmethod(function)) else: fname = function.__name__ fn_obj = getattr(module_obj, fname, None) if fn_obj is None: setattr(module_obj, fname, function) else: setattr(module_obj, fname + '_internal', function)
[ "def", "_init_ndarray_module", "(", ")", ":", "plist", "=", "ctypes", ".", "POINTER", "(", "FunctionHandle", ")", "(", ")", "size", "=", "ctypes", ".", "c_uint", "(", ")", "check_call", "(", "_LIB", ".", "MXListFunctions", "(", "ctypes", ".", "byref", "(...
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/mxnet/ndarray.py#L1084-L1104
baidu/bigflow
449245016c0df7d1252e85581e588bfc60cefad3
bigflow_python/python/bigflow/util/utils.py
python
is_ptype
(obj)
return isinstance(obj, ptype.PType)
Return if an object is a PType Args: obj (object): object Returns: bool: True if the object is a PType, False otherwise
Return if an object is a PType
[ "Return", "if", "an", "object", "is", "a", "PType" ]
def is_ptype(obj): """ Return if an object is a PType Args: obj (object): object Returns: bool: True if the object is a PType, False otherwise """ return isinstance(obj, ptype.PType)
[ "def", "is_ptype", "(", "obj", ")", ":", "return", "isinstance", "(", "obj", ",", "ptype", ".", "PType", ")" ]
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/util/utils.py#L31-L41
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/externals/joblib/pool.py
python
delete_folder
(folder_path)
Utility function to cleanup a temporary folder if still existing.
Utility function to cleanup a temporary folder if still existing.
[ "Utility", "function", "to", "cleanup", "a", "temporary", "folder", "if", "still", "existing", "." ]
def delete_folder(folder_path): """Utility function to cleanup a temporary folder if still existing.""" try: if os.path.exists(folder_path): shutil.rmtree(folder_path) except WindowsError: warnings.warn("Failed to clean temporary folder: %s" % folder_path)
[ "def", "delete_folder", "(", "folder_path", ")", ":", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "folder_path", ")", ":", "shutil", ".", "rmtree", "(", "folder_path", ")", "except", "WindowsError", ":", "warnings", ".", "warn", "(", "\"Fail...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/joblib/pool.py#L432-L438
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/android_platform/development/scripts/symbol.py
python
FindToolchain
()
Look for the latest available toolchain Args: None Returns: A pair of strings containing toolchain label and target prefix.
Look for the latest available toolchain
[ "Look", "for", "the", "latest", "available", "toolchain" ]
def FindToolchain(): """Look for the latest available toolchain Args: None Returns: A pair of strings containing toolchain label and target prefix. """ global TOOLCHAIN_INFO if TOOLCHAIN_INFO is not None: return TOOLCHAIN_INFO ## Known toolchains, newer ones in the front. if ARCH == "arm": known_toolchains = [ ("arm-linux-androideabi-4.6", "arm", "arm-linux-androideabi"), ] elif ARCH =="x86": known_toolchains = [ ("i686-android-linux-4.4.3", "x86", "i686-android-linux") ] else: known_toolchains = [] # Look for addr2line to check for valid toolchain path. for (label, platform, target) in known_toolchains: toolchain_info = (label, platform, target); if os.path.exists(ToolPath("addr2line", toolchain_info)): TOOLCHAIN_INFO = toolchain_info return toolchain_info raise Exception("Could not find tool chain")
[ "def", "FindToolchain", "(", ")", ":", "global", "TOOLCHAIN_INFO", "if", "TOOLCHAIN_INFO", "is", "not", "None", ":", "return", "TOOLCHAIN_INFO", "## Known toolchains, newer ones in the front.", "if", "ARCH", "==", "\"arm\"", ":", "known_toolchains", "=", "[", "(", "...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/android_platform/development/scripts/symbol.py#L67-L99
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/SANSUtility.py
python
delete_zero_error_free_workspace
(input_workspace_name)
return message, complete
Deletes the zero-error free workspace @param ws :: The input workspace
Deletes the zero-error free workspace
[ "Deletes", "the", "zero", "-", "error", "free", "workspace" ]
def delete_zero_error_free_workspace(input_workspace_name): ''' Deletes the zero-error free workspace @param ws :: The input workspace ''' complete = False message = "" if input_workspace_name in mtd: DeleteWorkspace(Workspace=input_workspace_name) complete = True else: message = 'Failed to delete a zero-error free workspace' return message, complete
[ "def", "delete_zero_error_free_workspace", "(", "input_workspace_name", ")", ":", "complete", "=", "False", "message", "=", "\"\"", "if", "input_workspace_name", "in", "mtd", ":", "DeleteWorkspace", "(", "Workspace", "=", "input_workspace_name", ")", "complete", "=", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/SANSUtility.py#L926-L938
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/excel/_odfreader.py
python
ODFReader._get_row_repeat
(self, row)
return int(row.attributes.get((TABLENS, "number-rows-repeated"), 1))
Return number of times this row was repeated Repeating an empty row appeared to be a common way of representing sparse rows in the table.
Return number of times this row was repeated Repeating an empty row appeared to be a common way of representing sparse rows in the table.
[ "Return", "number", "of", "times", "this", "row", "was", "repeated", "Repeating", "an", "empty", "row", "appeared", "to", "be", "a", "common", "way", "of", "representing", "sparse", "rows", "in", "the", "table", "." ]
def _get_row_repeat(self, row) -> int: """ Return number of times this row was repeated Repeating an empty row appeared to be a common way of representing sparse rows in the table. """ from odf.namespaces import TABLENS return int(row.attributes.get((TABLENS, "number-rows-repeated"), 1))
[ "def", "_get_row_repeat", "(", "self", ",", "row", ")", "->", "int", ":", "from", "odf", ".", "namespaces", "import", "TABLENS", "return", "int", "(", "row", ".", "attributes", ".", "get", "(", "(", "TABLENS", ",", "\"number-rows-repeated\"", ")", ",", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/excel/_odfreader.py#L142-L150
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distro.py
python
LinuxDistribution._parse_distro_release_content
(line)
return distro_info
Parse a line from a distro release file. Parameters: * line: Line from the distro release file. Must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items.
Parse a line from a distro release file.
[ "Parse", "a", "line", "from", "a", "distro", "release", "file", "." ]
def _parse_distro_release_content(line): """ Parse a line from a distro release file. Parameters: * line: Line from the distro release file. Must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items. """ if isinstance(line, bytes): line = line.decode('utf-8') matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match( line.strip()[::-1]) distro_info = {} if matches: # regexp ensures non-None distro_info['name'] = matches.group(3)[::-1] if matches.group(2): distro_info['version_id'] = matches.group(2)[::-1] if matches.group(1): distro_info['codename'] = matches.group(1)[::-1] elif line: distro_info['name'] = line.strip() return distro_info
[ "def", "_parse_distro_release_content", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "bytes", ")", ":", "line", "=", "line", ".", "decode", "(", "'utf-8'", ")", "matches", "=", "_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN", ".", "match", "(", "lin...
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distro.py#L1142-L1167
tensorflow/ngraph-bridge
ea6422491ec75504e78a63db029e7f74ec3479a5
examples/retrain_ngraph.py
python
export_model
(module_spec, class_count, saved_model_dir)
Exports model for serving. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: The number of classes. saved_model_dir: Directory in which to save exported model and variables.
Exports model for serving.
[ "Exports", "model", "for", "serving", "." ]
def export_model(module_spec, class_count, saved_model_dir): """Exports model for serving. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: The number of classes. saved_model_dir: Directory in which to save exported model and variables. """ # The SavedModel should hold the eval graph. sess, in_image, _, _, _, _ = build_eval_session(module_spec, class_count) with sess.graph.as_default() as graph: tf.saved_model.simple_save( sess, saved_model_dir, inputs={'image': in_image}, outputs={'prediction': graph.get_tensor_by_name('final_result:0')}, legacy_init_op=tf.group( tf.tables_initializer(), name='legacy_init_op'))
[ "def", "export_model", "(", "module_spec", ",", "class_count", ",", "saved_model_dir", ")", ":", "# The SavedModel should hold the eval graph.", "sess", ",", "in_image", ",", "_", ",", "_", ",", "_", ",", "_", "=", "build_eval_session", "(", "module_spec", ",", ...
https://github.com/tensorflow/ngraph-bridge/blob/ea6422491ec75504e78a63db029e7f74ec3479a5/examples/retrain_ngraph.py#L986-L1003
osrf/gazebo
f570338107862253229a0514ffea10deab4f4517
tools/cpplint.py
python
GetHeaderGuardCPPVariable
(filename)
return re.sub(r'[-./\s]', '_', fileinfo.RepositoryName()).upper() + '_'
Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file.
Returns the CPP variable that should be used as a header guard.
[ "Returns", "the", "CPP", "variable", "that", "should", "be", "used", "as", "a", "header", "guard", "." ]
def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) fileinfo = FileInfo(filename) return re.sub(r'[-./\s]', '_', fileinfo.RepositoryName()).upper() + '_'
[ "def", "GetHeaderGuardCPPVariable", "(", "filename", ")", ":", "# Restores original filename in case that cpplint is invoked from Emacs's", "# flymake.", "filename", "=", "re", ".", "sub", "(", "r'_flymake\\.h$'", ",", "'.h'", ",", "filename", ")", "fileinfo", "=", "FileI...
https://github.com/osrf/gazebo/blob/f570338107862253229a0514ffea10deab4f4517/tools/cpplint.py#L1017-L1034
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/pyami/installers/ubuntu/installer.py
python
Installer.install
(self)
This is the only method you need to override
This is the only method you need to override
[ "This", "is", "the", "only", "method", "you", "need", "to", "override" ]
def install(self): """ This is the only method you need to override """ raise NotImplementedError
[ "def", "install", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/pyami/installers/ubuntu/installer.py#L90-L94
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/descriptor/descriptor.py
python
Descriptor.get_feed_dict
(self, coord_: tf.Tensor, atype_: tf.Tensor, natoms: tf.Tensor, box: tf.Tensor, mesh: tf.Tensor )
return feed_dict
Generate the feed_dict for current descriptor Parameters ---------- coord_ : tf.Tensor The coordinate of atoms atype_ : tf.Tensor The type of atoms natoms : tf.Tensor The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms box : tf.Tensor The box. Can be generated by deepmd.model.make_stat_input mesh : tf.Tensor For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed. Returns ------- feed_dict : dict[str, tf.Tensor] The output feed_dict of current descriptor
Generate the feed_dict for current descriptor
[ "Generate", "the", "feed_dict", "for", "current", "descriptor" ]
def get_feed_dict(self, coord_: tf.Tensor, atype_: tf.Tensor, natoms: tf.Tensor, box: tf.Tensor, mesh: tf.Tensor ) -> Dict[str, tf.Tensor]: """ Generate the feed_dict for current descriptor Parameters ---------- coord_ : tf.Tensor The coordinate of atoms atype_ : tf.Tensor The type of atoms natoms : tf.Tensor The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms box : tf.Tensor The box. Can be generated by deepmd.model.make_stat_input mesh : tf.Tensor For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed. Returns ------- feed_dict : dict[str, tf.Tensor] The output feed_dict of current descriptor """ feed_dict = { 't_coord:0' :coord_, 't_type:0' :atype_, 't_natoms:0' :natoms, 't_box:0' :box, 't_mesh:0' :mesh } return feed_dict
[ "def", "get_feed_dict", "(", "self", ",", "coord_", ":", "tf", ".", "Tensor", ",", "atype_", ":", "tf", ".", "Tensor", ",", "natoms", ":", "tf", ".", "Tensor", ",", "box", ":", "tf", ".", "Tensor", ",", "mesh", ":", "tf", ".", "Tensor", ")", "->"...
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/descriptor/descriptor.py#L293-L333
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PropertyGridInterface.SetPropertyValues
(self,dict_)
Sets property values from dict_, which can be either\ndictionary
Sets property values from dict_, which can be either\ndictionary
[ "Sets", "property", "values", "from", "dict_", "which", "can", "be", "either", "\\", "ndictionary" ]
def SetPropertyValues(self,dict_): "Sets property values from dict_, which can be either\ndictionary " "or an object with __dict__ attribute." "" "autofill: If true, keys with not relevant properties" " are auto-created. For more info, see AutoFill." "" "Notes:" " * Keys starting with underscore are ignored." " * Attributes can be set with entries named @<propname>@<attr>." "" autofill = False if dict_ is None: dict_ = {} elif hasattr(dict_,'__dict__'): dict_ = dict_.__dict__ attr_dicts = [] def set_sub_obj(k0,dict_): for k,v in dict_.iteritems(): if k[0] != '_': if k.endswith('@attr'): attr_dicts.append((k[1:-5],v)) else: try: self.SetPropertyValue(k,v) except: try: if autofill: self._AutoFillOne(k0,k,v) continue except: if isinstance(v,dict): set_sub_obj(k,v) elif hasattr(v,'__dict__'): set_sub_obj(k,v.__dict__) for k,v in attr_dicts: p = GetPropertyByName(k) if not p: raise AssertionError("No such property: '%s'"%k) for an,av in v.iteritems(): p.SetAttribute(an, av) cur_page = False is_manager = isinstance(self,PropertyGridManager) try: set_sub_obj(self.GetGrid().GetRoot(),dict_) except: import traceback traceback.print_exc() self.Refresh()
[ "def", "SetPropertyValues", "(", "self", ",", "dict_", ")", ":", "\"or an object with __dict__ attribute.\"", "\"\"", "\"autofill: If true, keys with not relevant properties\"", "\" are auto-created. For more info, see AutoFill.\"", "\"\"", "\"Notes:\"", "\" * Keys starting with unders...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L1575-L1633
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rospy/src/rospy/topics.py
python
_TopicImpl.close
(self)
close I/O
close I/O
[ "close", "I", "/", "O" ]
def close(self): """close I/O""" if self.closed: return self.closed = True if self.c_lock is not None: with self.c_lock: for c in self.connections: try: if c is not None: c.close() except: # seems more logger.error internal than external logerr _logger.error(traceback.format_exc()) del self.connections[:] self.handler = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "closed", ":", "return", "self", ".", "closed", "=", "True", "if", "self", ".", "c_lock", "is", "not", "None", ":", "with", "self", ".", "c_lock", ":", "for", "c", "in", "self", ".", "conn...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/topics.py#L310-L325
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/lonely-pixel-i.py
python
Solution2.findLonelyPixel
(self, picture)
return sum(col.count('B') == 1 == picture[col.index('B')].count('B') \ for col in zip(*picture))
:type picture: List[List[str]] :type N: int :rtype: int
:type picture: List[List[str]] :type N: int :rtype: int
[ ":", "type", "picture", ":", "List", "[", "List", "[", "str", "]]", ":", "type", "N", ":", "int", ":", "rtype", ":", "int" ]
def findLonelyPixel(self, picture): """ :type picture: List[List[str]] :type N: int :rtype: int """ return sum(col.count('B') == 1 == picture[col.index('B')].count('B') \ for col in zip(*picture))
[ "def", "findLonelyPixel", "(", "self", ",", "picture", ")", ":", "return", "sum", "(", "col", ".", "count", "(", "'B'", ")", "==", "1", "==", "picture", "[", "col", ".", "index", "(", "'B'", ")", "]", ".", "count", "(", "'B'", ")", "for", "col", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/lonely-pixel-i.py#L26-L33
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/run.py
python
MyHandler.exithook
(self)
override SocketIO method - wait for MainThread to shut us down
override SocketIO method - wait for MainThread to shut us down
[ "override", "SocketIO", "method", "-", "wait", "for", "MainThread", "to", "shut", "us", "down" ]
def exithook(self): "override SocketIO method - wait for MainThread to shut us down" time.sleep(10)
[ "def", "exithook", "(", "self", ")", ":", "time", ".", "sleep", "(", "10", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/run.py#L517-L519
NicknineTheEagle/TF2-Base
20459c5a7fbc995b6bf54fa85c2f62a101e9fb64
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/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L359-L391
may0324/DeepCompression-caffe
0aff6c1287bda4cfc7f378ed8a16524e1afabd8c
scripts/cpp_lint.py
python
FindEndOfExpressionInLine
(line, startpos, depth, startchar, endchar)
return (-1, depth)
Find the position just after the matching endchar. Args: line: a CleansedLines line. startpos: start searching at this position. depth: nesting level at startpos. startchar: expression opening character. endchar: expression closing character. Returns: On finding matching endchar: (index just after matching endchar, 0) Otherwise: (-1, new depth at end of this line)
Find the position just after the matching endchar.
[ "Find", "the", "position", "just", "after", "the", "matching", "endchar", "." ]
def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar): """Find the position just after the matching endchar. Args: line: a CleansedLines line. startpos: start searching at this position. depth: nesting level at startpos. startchar: expression opening character. endchar: expression closing character. Returns: On finding matching endchar: (index just after matching endchar, 0) Otherwise: (-1, new depth at end of this line) """ for i in xrange(startpos, len(line)): if line[i] == startchar: depth += 1 elif line[i] == endchar: depth -= 1 if depth == 0: return (i + 1, 0) return (-1, depth)
[ "def", "FindEndOfExpressionInLine", "(", "line", ",", "startpos", ",", "depth", ",", "startchar", ",", "endchar", ")", ":", "for", "i", "in", "xrange", "(", "startpos", ",", "len", "(", "line", ")", ")", ":", "if", "line", "[", "i", "]", "==", "start...
https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/scripts/cpp_lint.py#L1230-L1251
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/python_gflags/gflags.py
python
NumericParser.Convert
(self, argument)
return argument
Default implementation: always returns its argument unmodified.
Default implementation: always returns its argument unmodified.
[ "Default", "implementation", ":", "always", "returns", "its", "argument", "unmodified", "." ]
def Convert(self, argument): """Default implementation: always returns its argument unmodified.""" return argument
[ "def", "Convert", "(", "self", ",", "argument", ")", ":", "return", "argument" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/python_gflags/gflags.py#L2462-L2464
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/importlib-metadata/py2/importlib_metadata/__init__.py
python
Distribution.from_name
(cls, name)
Return the Distribution for the given package name. :param name: The name of the distribution package to search for. :return: The Distribution instance (or subclass thereof) for the named package, if found. :raises PackageNotFoundError: When the named package's distribution metadata cannot be found.
Return the Distribution for the given package name.
[ "Return", "the", "Distribution", "for", "the", "given", "package", "name", "." ]
def from_name(cls, name): """Return the Distribution for the given package name. :param name: The name of the distribution package to search for. :return: The Distribution instance (or subclass thereof) for the named package, if found. :raises PackageNotFoundError: When the named package's distribution metadata cannot be found. """ for resolver in cls._discover_resolvers(): dists = resolver(DistributionFinder.Context(name=name)) dist = next(iter(dists), None) if dist is not None: return dist else: raise PackageNotFoundError(name)
[ "def", "from_name", "(", "cls", ",", "name", ")", ":", "for", "resolver", "in", "cls", ".", "_discover_resolvers", "(", ")", ":", "dists", "=", "resolver", "(", "DistributionFinder", ".", "Context", "(", "name", "=", "name", ")", ")", "dist", "=", "nex...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/importlib-metadata/py2/importlib_metadata/__init__.py#L204-L219
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/summary/impl/reservoir.py
python
Reservoir.__init__
(self, size, seed=0)
Creates a new reservoir. Args: size: The number of values to keep in the reservoir for each tag. If 0, all values will be kept. seed: The seed of the random number generator to use when sampling. Different values for |seed| will produce different samples from the same input items. Raises: ValueError: If size is negative or not an integer.
Creates a new reservoir.
[ "Creates", "a", "new", "reservoir", "." ]
def __init__(self, size, seed=0): """Creates a new reservoir. Args: size: The number of values to keep in the reservoir for each tag. If 0, all values will be kept. seed: The seed of the random number generator to use when sampling. Different values for |seed| will produce different samples from the same input items. Raises: ValueError: If size is negative or not an integer. """ if size < 0 or size != round(size): raise ValueError('size must be nonegative integer, was %s' % size) self._buckets = collections.defaultdict( lambda: _ReservoirBucket(size, random.Random(seed))) # _mutex guards the keys - creating new keys, retreiving by key, etc # the internal items are guarded by the ReservoirBuckets' internal mutexes self._mutex = threading.Lock()
[ "def", "__init__", "(", "self", ",", "size", ",", "seed", "=", "0", ")", ":", "if", "size", "<", "0", "or", "size", "!=", "round", "(", "size", ")", ":", "raise", "ValueError", "(", "'size must be nonegative integer, was %s'", "%", "size", ")", "self", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/summary/impl/reservoir.py#L58-L77
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_2_0_3.py
python
MiroInterpreter.do_mythtv_getunwatched
(self, line)
Process MythTV get all un-watched video details
Process MythTV get all un-watched video details
[ "Process", "MythTV", "get", "all", "un", "-", "watched", "video", "details" ]
def do_mythtv_getunwatched(self, line): """Process MythTV get all un-watched video details""" if self.verbose: print print u"Getting details on un-watched Miro videos" self.videofiles = [] if len(views.watchableItems): if self.verbose: print u"%-20s %-10s %s" % (u"State", u"Size", u"Name") print u"-" * 70 for item in views.watchableItems: # Skip any audio file as MythTV Internal player may abort the MythTV Frontend on a MP3 if not item.isVideo: continue state = item.get_state() if not state == u'newly-downloaded': continue # Skip any bittorrent video downloads for legal concerns if filetypes.is_torrent_filename(item.getURL()): continue self.printItems(item) self.videofiles.append(self._get_item_dict(item)) if self.verbose: print if not len(self.videofiles): logging.info(u"No un-watched Miro videos")
[ "def", "do_mythtv_getunwatched", "(", "self", ",", "line", ")", ":", "if", "self", ".", "verbose", ":", "print", "print", "u\"Getting details on un-watched Miro videos\"", "self", ".", "videofiles", "=", "[", "]", "if", "len", "(", "views", ".", "watchableItems"...
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_2_0_3.py#L257-L283
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
Geometry3D.getCollisionMargin
(self)
return _robotsim.Geometry3D_getCollisionMargin(self)
r""" Returns the padding around the base geometry. Default 0.
r""" Returns the padding around the base geometry. Default 0.
[ "r", "Returns", "the", "padding", "around", "the", "base", "geometry", ".", "Default", "0", "." ]
def getCollisionMargin(self) ->float: r""" Returns the padding around the base geometry. Default 0. """ return _robotsim.Geometry3D_getCollisionMargin(self)
[ "def", "getCollisionMargin", "(", "self", ")", "->", "float", ":", "return", "_robotsim", ".", "Geometry3D_getCollisionMargin", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L2320-L2325
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal.py
python
Normal.std
(self, name="std")
Standard deviation of this distribution.
Standard deviation of this distribution.
[ "Standard", "deviation", "of", "this", "distribution", "." ]
def std(self, name="std"): """Standard deviation of this distribution.""" with ops.name_scope(self.name): with ops.op_scope([self._sigma, self._mu], name): return self._sigma * array_ops.ones_like(self._mu)
[ "def", "std", "(", "self", ",", "name", "=", "\"std\"", ")", ":", "with", "ops", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "self", ".", "_sigma", ",", "self", ".", "_mu", "]", ",", "name", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal.py#L211-L215
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiGenericTabArt.__init__
(self, *args, **kwargs)
__init__(self) -> AuiGenericTabArt
__init__(self) -> AuiGenericTabArt
[ "__init__", "(", "self", ")", "-", ">", "AuiGenericTabArt" ]
def __init__(self, *args, **kwargs): """__init__(self) -> AuiGenericTabArt""" _aui.AuiGenericTabArt_swiginit(self,_aui.new_AuiGenericTabArt(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_aui", ".", "AuiGenericTabArt_swiginit", "(", "self", ",", "_aui", ".", "new_AuiGenericTabArt", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L2369-L2371
NVIDIA/thrust
627dccb359a635afdd69e95a6cc59698f23f70e2
internal/benchmark/compare_benchmark_results.py
python
store_false_multiple
(*destinations)
return store_const_multiple(False, *destinations)
Returns an `argument_action` class that sets multiple argument destinations (`destinations`) to `False`.
Returns an `argument_action` class that sets multiple argument destinations (`destinations`) to `False`.
[ "Returns", "an", "argument_action", "class", "that", "sets", "multiple", "argument", "destinations", "(", "destinations", ")", "to", "False", "." ]
def store_false_multiple(*destinations): """Returns an `argument_action` class that sets multiple argument destinations (`destinations`) to `False`.""" return store_const_multiple(False, *destinations)
[ "def", "store_false_multiple", "(", "*", "destinations", ")", ":", "return", "store_const_multiple", "(", "False", ",", "*", "destinations", ")" ]
https://github.com/NVIDIA/thrust/blob/627dccb359a635afdd69e95a6cc59698f23f70e2/internal/benchmark/compare_benchmark_results.py#L516-L519
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ToolBarToolBase.GetShortHelp
(*args, **kwargs)
return _controls_.ToolBarToolBase_GetShortHelp(*args, **kwargs)
GetShortHelp(self) -> String
GetShortHelp(self) -> String
[ "GetShortHelp", "(", "self", ")", "-", ">", "String" ]
def GetShortHelp(*args, **kwargs): """GetShortHelp(self) -> String""" return _controls_.ToolBarToolBase_GetShortHelp(*args, **kwargs)
[ "def", "GetShortHelp", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ToolBarToolBase_GetShortHelp", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L3505-L3507
casadi/casadi
8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff
docs/api/extra/doxy2swigX.py
python
Doxy2SWIG_X.generic_parse
(self, node, pad=0)
A Generic parser for arbitrary tags in a node. Parameters: - node: A node in the DOM. - pad: `int` (default: 0) If 0 the node data is not padded with newlines. If 1 it appends a newline after parsing the childNodes. If 2 it pads before and after the nodes are processed. Defaults to 0.
A Generic parser for arbitrary tags in a node.
[ "A", "Generic", "parser", "for", "arbitrary", "tags", "in", "a", "node", "." ]
def generic_parse(self, node, pad=0): """A Generic parser for arbitrary tags in a node. Parameters: - node: A node in the DOM. - pad: `int` (default: 0) If 0 the node data is not padded with newlines. If 1 it appends a newline after parsing the childNodes. If 2 it pads before and after the nodes are processed. Defaults to 0. """ npiece = 0 if pad: npiece = self.add_text_counter if pad == 2: self.add_text('\n') for n in node.childNodes: self.parse(n) if pad: if self.add_text_counter > npiece: self.add_text('\n')
[ "def", "generic_parse", "(", "self", ",", "node", ",", "pad", "=", "0", ")", ":", "npiece", "=", "0", "if", "pad", ":", "npiece", "=", "self", ".", "add_text_counter", "if", "pad", "==", "2", ":", "self", ".", "add_text", "(", "'\\n'", ")", "for", ...
https://github.com/casadi/casadi/blob/8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff/docs/api/extra/doxy2swigX.py#L107-L130
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
Font.GetDefaultEncoding
(*args, **kwargs)
return _gdi_.Font_GetDefaultEncoding(*args, **kwargs)
GetDefaultEncoding() -> int Returns the encoding used for all fonts created with an encoding of ``wx.FONTENCODING_DEFAULT``.
GetDefaultEncoding() -> int
[ "GetDefaultEncoding", "()", "-", ">", "int" ]
def GetDefaultEncoding(*args, **kwargs): """ GetDefaultEncoding() -> int Returns the encoding used for all fonts created with an encoding of ``wx.FONTENCODING_DEFAULT``. """ return _gdi_.Font_GetDefaultEncoding(*args, **kwargs)
[ "def", "GetDefaultEncoding", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Font_GetDefaultEncoding", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L2500-L2507
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py
python
screen.cursor_force_position
(self, r, c)
Identical to Cursor Home.
Identical to Cursor Home.
[ "Identical", "to", "Cursor", "Home", "." ]
def cursor_force_position (self, r, c): # <ESC>[{ROW};{COLUMN}f '''Identical to Cursor Home.''' self.cursor_home (r, c)
[ "def", "cursor_force_position", "(", "self", ",", "r", ",", "c", ")", ":", "# <ESC>[{ROW};{COLUMN}f", "self", ".", "cursor_home", "(", "r", ",", "c", ")" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L313-L316
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/extras/dcc.py
python
options
(opt)
Add the ``--with-diab-bindir`` command-line options.
Add the ``--with-diab-bindir`` command-line options.
[ "Add", "the", "--", "with", "-", "diab", "-", "bindir", "command", "-", "line", "options", "." ]
def options(opt): """ Add the ``--with-diab-bindir`` command-line options. """ opt.add_option('--with-diab-bindir', type='string', dest='diabbindir', help = 'Specify alternate diab bin folder', default="")
[ "def", "options", "(", "opt", ")", ":", "opt", ".", "add_option", "(", "'--with-diab-bindir'", ",", "type", "=", "'string'", ",", "dest", "=", "'diabbindir'", ",", "help", "=", "'Specify alternate diab bin folder'", ",", "default", "=", "\"\"", ")" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/dcc.py#L67-L71
bristolcrypto/SPDZ-2
721abfae849625a02ea49aabc534f9cf41ca643f
Compiler/path_oram.py
python
PathORAM.get_children
(self, i, l)
return self.buckets[2*j+1], self.buckets[2*j+2]
Get children of the i-th bucket on level l
Get children of the i-th bucket on level l
[ "Get", "children", "of", "the", "i", "-", "th", "bucket", "on", "level", "l" ]
def get_children(self, i, l): """ Get children of the i-th bucket on level l """ j = 2**l + i - 1 return self.buckets[2*j+1], self.buckets[2*j+2]
[ "def", "get_children", "(", "self", ",", "i", ",", "l", ")", ":", "j", "=", "2", "**", "l", "+", "i", "-", "1", "return", "self", ".", "buckets", "[", "2", "*", "j", "+", "1", "]", ",", "self", ".", "buckets", "[", "2", "*", "j", "+", "2"...
https://github.com/bristolcrypto/SPDZ-2/blob/721abfae849625a02ea49aabc534f9cf41ca643f/Compiler/path_oram.py#L566-L569
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/tweet-counts-per-frequency.py
python
TweetCounts.recordTweet
(self, tweetName, time)
:type tweetName: str :type time: int :rtype: None
:type tweetName: str :type time: int :rtype: None
[ ":", "type", "tweetName", ":", "str", ":", "type", "time", ":", "int", ":", "rtype", ":", "None" ]
def recordTweet(self, tweetName, time): """ :type tweetName: str :type time: int :rtype: None """ self.__records[tweetName].add(time)
[ "def", "recordTweet", "(", "self", ",", "tweetName", ",", "time", ")", ":", "self", ".", "__records", "[", "tweetName", "]", ".", "add", "(", "time", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/tweet-counts-per-frequency.py#L113-L119
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
bindings/python/rad_util.py
python
gcf
(a, b, epsilon=1e-16)
return abs(result)
Return the greatest common factor of a and b, using Euclidean algorithm. Arguments: a, b -- two numbers If both numbers are integers return an integer result, otherwise return a float result. epsilon -- floats less than this magnitude are considered to be zero (default: 1e-16) Examples: >>> gcf(12, 34) 2 >>> gcf(13.5, 4) 0.5 >>> gcf(-2, 4) 2 >>> gcf(5, 0) 5 By (a convenient) definition: >>> gcf(0, 0) 0
Return the greatest common factor of a and b, using Euclidean algorithm.
[ "Return", "the", "greatest", "common", "factor", "of", "a", "and", "b", "using", "Euclidean", "algorithm", "." ]
def gcf(a, b, epsilon=1e-16): """Return the greatest common factor of a and b, using Euclidean algorithm. Arguments: a, b -- two numbers If both numbers are integers return an integer result, otherwise return a float result. epsilon -- floats less than this magnitude are considered to be zero (default: 1e-16) Examples: >>> gcf(12, 34) 2 >>> gcf(13.5, 4) 0.5 >>> gcf(-2, 4) 2 >>> gcf(5, 0) 5 By (a convenient) definition: >>> gcf(0, 0) 0 """ result = max(a, b) remainder = min(a, b) while remainder and abs(remainder) > epsilon: new_remainder = result % remainder result = remainder remainder = new_remainder return abs(result)
[ "def", "gcf", "(", "a", ",", "b", ",", "epsilon", "=", "1e-16", ")", ":", "result", "=", "max", "(", "a", ",", "b", ")", "remainder", "=", "min", "(", "a", ",", "b", ")", "while", "remainder", "and", "abs", "(", "remainder", ")", ">", "epsilon"...
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/bindings/python/rad_util.py#L223-L258
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
File.name
(self)
return conf.lib.clang_getCString(conf.lib.clang_getFileName(self))
Return the complete file and path name of the file.
Return the complete file and path name of the file.
[ "Return", "the", "complete", "file", "and", "path", "name", "of", "the", "file", "." ]
def name(self): """Return the complete file and path name of the file.""" return conf.lib.clang_getCString(conf.lib.clang_getFileName(self))
[ "def", "name", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getCString", "(", "conf", ".", "lib", ".", "clang_getFileName", "(", "self", ")", ")" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L2320-L2322
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/gui/StateCache.py
python
StateCache.save_new_state
(self, state)
Save a new state. Place the new state at the next index and add one to the number of previous states. Args: state: the new state
Save a new state. Place the new state at the next index and add one to the number of previous states.
[ "Save", "a", "new", "state", ".", "Place", "the", "new", "state", "at", "the", "next", "index", "and", "add", "one", "to", "the", "number", "of", "previous", "states", "." ]
def save_new_state(self, state): """ Save a new state. Place the new state at the next index and add one to the number of previous states. Args: state: the new state """ self.current_state_index = ( self.current_state_index + 1) % STATE_CACHE_SIZE self.states[self.current_state_index] = state self.num_prev_states = self.num_prev_states + 1 if self.num_prev_states == STATE_CACHE_SIZE: self.num_prev_states = STATE_CACHE_SIZE - 1 self.num_next_states = 0 self.update_actions()
[ "def", "save_new_state", "(", "self", ",", "state", ")", ":", "self", ".", "current_state_index", "=", "(", "self", ".", "current_state_index", "+", "1", ")", "%", "STATE_CACHE_SIZE", "self", ".", "states", "[", "self", ".", "current_state_index", "]", "=", ...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/gui/StateCache.py#L34-L49
PlatformLab/NanoLog
2a94d70f9d1db4da416053b1b926387fa068a59b
preprocessor/docopt.py
python
parse_expr
(tokens, options)
return [Either(*result)] if len(result) > 1 else result
expr ::= seq ( '|' seq )* ;
expr ::= seq ( '|' seq )* ;
[ "expr", "::", "=", "seq", "(", "|", "seq", ")", "*", ";" ]
def parse_expr(tokens, options): """expr ::= seq ( '|' seq )* ;""" seq = parse_seq(tokens, options) if tokens.current() != '|': return seq result = [Required(*seq)] if len(seq) > 1 else seq while tokens.current() == '|': tokens.move() seq = parse_seq(tokens, options) result += [Required(*seq)] if len(seq) > 1 else seq return [Either(*result)] if len(result) > 1 else result
[ "def", "parse_expr", "(", "tokens", ",", "options", ")", ":", "seq", "=", "parse_seq", "(", "tokens", ",", "options", ")", "if", "tokens", ".", "current", "(", ")", "!=", "'|'", ":", "return", "seq", "result", "=", "[", "Required", "(", "*", "seq", ...
https://github.com/PlatformLab/NanoLog/blob/2a94d70f9d1db4da416053b1b926387fa068a59b/preprocessor/docopt.py#L377-L387
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/utils/_mask.py
python
_get_mask
(X, value_to_mask)
Compute the boolean mask X == missing_values.
Compute the boolean mask X == missing_values.
[ "Compute", "the", "boolean", "mask", "X", "==", "missing_values", "." ]
def _get_mask(X, value_to_mask): """Compute the boolean mask X == missing_values.""" if is_scalar_nan(value_to_mask): if X.dtype.kind == "f": return np.isnan(X) elif X.dtype.kind in ("i", "u"): # can't have NaNs in integer array. return np.zeros(X.shape, dtype=bool) else: # np.isnan does not work on object dtypes. return _object_dtype_isnan(X) else: # X == value_to_mask with object dtypes does not always perform # element-wise for old versions of numpy return np.equal(X, value_to_mask)
[ "def", "_get_mask", "(", "X", ",", "value_to_mask", ")", ":", "if", "is_scalar_nan", "(", "value_to_mask", ")", ":", "if", "X", ".", "dtype", ".", "kind", "==", "\"f\"", ":", "return", "np", ".", "isnan", "(", "X", ")", "elif", "X", ".", "dtype", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/_mask.py#L7-L21
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/cygprofile/symbolize.py
python
FindFunctions
(addr, unique_addrs, address_map)
return address_map[BinarySearchAddresses(addr, 0, len(unique_addrs) - 1, unique_addrs)]
Find function symbol names at address addr.
Find function symbol names at address addr.
[ "Find", "function", "symbol", "names", "at", "address", "addr", "." ]
def FindFunctions(addr, unique_addrs, address_map): """Find function symbol names at address addr.""" return address_map[BinarySearchAddresses(addr, 0, len(unique_addrs) - 1, unique_addrs)]
[ "def", "FindFunctions", "(", "addr", ",", "unique_addrs", ",", "address_map", ")", ":", "return", "address_map", "[", "BinarySearchAddresses", "(", "addr", ",", "0", ",", "len", "(", "unique_addrs", ")", "-", "1", ",", "unique_addrs", ")", "]" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/cygprofile/symbolize.py#L164-L167
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/image/image.py
python
ImageIter.check_valid_image
(self, data)
Checks if the input data is valid
Checks if the input data is valid
[ "Checks", "if", "the", "input", "data", "is", "valid" ]
def check_valid_image(self, data): """Checks if the input data is valid""" if len(data[0].shape) == 0: raise RuntimeError('Data shape is wrong')
[ "def", "check_valid_image", "(", "self", ",", "data", ")", ":", "if", "len", "(", "data", "[", "0", "]", ".", "shape", ")", "==", "0", ":", "raise", "RuntimeError", "(", "'Data shape is wrong'", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/image/image.py#L1199-L1202
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/debugger_cli_common.py
python
CommandHandlerRegistry.get_help
(self, cmd_prefix=None)
Compile help information into a RichTextLines object. Args: cmd_prefix: Optional command prefix. As the prefix itself or one of its aliases. Returns: A RichTextLines object containing the help information. If cmd_prefix is None, the return value will be the full command-line help. Otherwise, it will be the help information for the specified command.
Compile help information into a RichTextLines object.
[ "Compile", "help", "information", "into", "a", "RichTextLines", "object", "." ]
def get_help(self, cmd_prefix=None): """Compile help information into a RichTextLines object. Args: cmd_prefix: Optional command prefix. As the prefix itself or one of its aliases. Returns: A RichTextLines object containing the help information. If cmd_prefix is None, the return value will be the full command-line help. Otherwise, it will be the help information for the specified command. """ if not cmd_prefix: # Print full help information, in sorted order of the command prefixes. help_info = RichTextLines([]) if self._help_intro: # If help intro is available, show it at the beginning. help_info.extend(self._help_intro) sorted_prefixes = sorted(self._handlers) for cmd_prefix in sorted_prefixes: lines = self._get_help_for_command_prefix(cmd_prefix) lines.append("") lines.append("") help_info.extend(RichTextLines(lines)) return help_info else: return RichTextLines(self._get_help_for_command_prefix(cmd_prefix))
[ "def", "get_help", "(", "self", ",", "cmd_prefix", "=", "None", ")", ":", "if", "not", "cmd_prefix", ":", "# Print full help information, in sorted order of the command prefixes.", "help_info", "=", "RichTextLines", "(", "[", "]", ")", "if", "self", ".", "_help_intr...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/debugger_cli_common.py#L729-L757
lmb-freiburg/ogn
974f72ef4bf840d6f6693d22d1843a79223e77ce
scripts/cpp_lint.py
python
PrintCategories
()
Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter.
Prints a list of all the error-categories used by error messages.
[ "Prints", "a", "list", "of", "all", "the", "error", "-", "categories", "used", "by", "error", "messages", "." ]
def PrintCategories(): """Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter. """ sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) sys.exit(0)
[ "def", "PrintCategories", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "''", ".", "join", "(", "' %s\\n'", "%", "cat", "for", "cat", "in", "_ERROR_CATEGORIES", ")", ")", "sys", ".", "exit", "(", "0", ")" ]
https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/scripts/cpp_lint.py#L4770-L4776
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py
python
DNNLinearCombinedEstimator.__init__
(self, # _joint_linear_weights pylint: disable=invalid-name head, model_dir=None, linear_feature_columns=None, linear_optimizer=None, _joint_linear_weights=False, dnn_feature_columns=None, dnn_optimizer=None, dnn_hidden_units=None, dnn_activation_fn=None, dnn_dropout=None, gradient_clip_norm=None, config=None, feature_engineering_fn=None, embedding_lr_multipliers=None, fix_global_step_increment_bug=False, input_layer_partitioner=None)
Initializes a DNNLinearCombinedEstimator instance. Note: New users must set `fix_global_step_increment_bug=True` when creating an estimator. Args: head: A _Head object. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. linear_feature_columns: An iterable containing all the feature columns used by linear part of the model. All items in the set should be instances of classes derived from `FeatureColumn`. linear_optimizer: An instance of `tf.Optimizer` used to apply gradients to the linear part of the model. If `None`, will use a FTRL optimizer. _joint_linear_weights: If True will use a single (possibly partitioned) variable to store all weights for the linear model. More efficient if there are many columns, however requires all columns are sparse and have the 'sum' combiner. dnn_feature_columns: An iterable containing all the feature columns used by deep part of the model. All items in the set should be instances of classes derived from `FeatureColumn`. dnn_optimizer: An instance of `tf.Optimizer` used to apply gradients to the deep part of the model. If `None`, will use an Adagrad optimizer. dnn_hidden_units: List of hidden units per layer. All layers are fully connected. dnn_activation_fn: Activation function applied to each layer. If `None`, will use `tf.nn.relu`. dnn_dropout: When not None, the probability we will drop out a given coordinate. gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See tf.clip_by_global_norm for more details. config: RunConfig object to configure the runtime settings. feature_engineering_fn: Feature engineering function. Takes features and labels which are the output of `input_fn` and returns features and labels which will be fed into the model. embedding_lr_multipliers: Optional. A dictionary from `EmbeddingColumn` to a `float` multiplier. Multiplier will be used to multiply with learning rate for the embedding variables. fix_global_step_increment_bug: If `False`, the estimator needs two fit steps to optimize both linear and dnn parts. If `True`, this bug is fixed. New users must set this to `True`, but the default value is `False` for backwards compatibility. input_layer_partitioner: Optional. Partitioner for input layer. Raises: ValueError: If both linear_feature_columns and dnn_features_columns are empty at the same time.
Initializes a DNNLinearCombinedEstimator instance.
[ "Initializes", "a", "DNNLinearCombinedEstimator", "instance", "." ]
def __init__(self, # _joint_linear_weights pylint: disable=invalid-name head, model_dir=None, linear_feature_columns=None, linear_optimizer=None, _joint_linear_weights=False, dnn_feature_columns=None, dnn_optimizer=None, dnn_hidden_units=None, dnn_activation_fn=None, dnn_dropout=None, gradient_clip_norm=None, config=None, feature_engineering_fn=None, embedding_lr_multipliers=None, fix_global_step_increment_bug=False, input_layer_partitioner=None): """Initializes a DNNLinearCombinedEstimator instance. Note: New users must set `fix_global_step_increment_bug=True` when creating an estimator. Args: head: A _Head object. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. linear_feature_columns: An iterable containing all the feature columns used by linear part of the model. All items in the set should be instances of classes derived from `FeatureColumn`. linear_optimizer: An instance of `tf.Optimizer` used to apply gradients to the linear part of the model. If `None`, will use a FTRL optimizer. _joint_linear_weights: If True will use a single (possibly partitioned) variable to store all weights for the linear model. More efficient if there are many columns, however requires all columns are sparse and have the 'sum' combiner. dnn_feature_columns: An iterable containing all the feature columns used by deep part of the model. All items in the set should be instances of classes derived from `FeatureColumn`. dnn_optimizer: An instance of `tf.Optimizer` used to apply gradients to the deep part of the model. If `None`, will use an Adagrad optimizer. dnn_hidden_units: List of hidden units per layer. All layers are fully connected. dnn_activation_fn: Activation function applied to each layer. If `None`, will use `tf.nn.relu`. dnn_dropout: When not None, the probability we will drop out a given coordinate. gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See tf.clip_by_global_norm for more details. config: RunConfig object to configure the runtime settings. feature_engineering_fn: Feature engineering function. Takes features and labels which are the output of `input_fn` and returns features and labels which will be fed into the model. embedding_lr_multipliers: Optional. A dictionary from `EmbeddingColumn` to a `float` multiplier. Multiplier will be used to multiply with learning rate for the embedding variables. fix_global_step_increment_bug: If `False`, the estimator needs two fit steps to optimize both linear and dnn parts. If `True`, this bug is fixed. New users must set this to `True`, but the default value is `False` for backwards compatibility. input_layer_partitioner: Optional. Partitioner for input layer. Raises: ValueError: If both linear_feature_columns and dnn_features_columns are empty at the same time. """ linear_feature_columns = tuple(linear_feature_columns or []) dnn_feature_columns = tuple(dnn_feature_columns or []) if not linear_feature_columns + dnn_feature_columns: raise ValueError("Either linear_feature_columns or dnn_feature_columns " "must be defined.") super(DNNLinearCombinedEstimator, self).__init__( model_fn=_dnn_linear_combined_model_fn, model_dir=model_dir, config=config, params={ "head": head, "linear_feature_columns": linear_feature_columns, "linear_optimizer": linear_optimizer, "joint_linear_weights": _joint_linear_weights, "dnn_feature_columns": dnn_feature_columns, "dnn_optimizer": dnn_optimizer, "dnn_hidden_units": dnn_hidden_units, "dnn_activation_fn": dnn_activation_fn, "dnn_dropout": dnn_dropout, "gradient_clip_norm": gradient_clip_norm, "embedding_lr_multipliers": embedding_lr_multipliers, "fix_global_step_increment_bug": fix_global_step_increment_bug, "input_layer_partitioner": input_layer_partitioner }, feature_engineering_fn=feature_engineering_fn)
[ "def", "__init__", "(", "self", ",", "# _joint_linear_weights pylint: disable=invalid-name", "head", ",", "model_dir", "=", "None", ",", "linear_feature_columns", "=", "None", ",", "linear_optimizer", "=", "None", ",", "_joint_linear_weights", "=", "False", ",", "dnn_...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py#L396-L487
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/ao/quantization/fx/_equalize.py
python
scale_input_observer
(node: Node, modules: Dict[str, nn.Module])
Scales the following input quantization observer's min/max values by updating the values with the scaled min/max values calculated by the input equalization observer
Scales the following input quantization observer's min/max values by updating the values with the scaled min/max values calculated by the input equalization observer
[ "Scales", "the", "following", "input", "quantization", "observer", "s", "min", "/", "max", "values", "by", "updating", "the", "values", "with", "the", "scaled", "min", "/", "max", "values", "calculated", "by", "the", "input", "equalization", "observer" ]
def scale_input_observer(node: Node, modules: Dict[str, nn.Module]) -> None: """ Scales the following input quantization observer's min/max values by updating the values with the scaled min/max values calculated by the input equalization observer """ input_eq_obs = modules[str(node.target)] assert(isinstance(input_eq_obs, _InputEqualizationObserver)) input_quant_obs_node = node.args[0] assert(isinstance(input_quant_obs_node, Node)) input_quant_obs = modules[str(input_quant_obs_node.target)] if not isinstance(input_quant_obs, ObserverBase): return min_input_scaled, max_input_scaled = input_eq_obs.calculate_scaled_minmax() if min_input_scaled is None and max_input_scaled is None: return input_quant_obs.min_val = min_input_scaled input_quant_obs.max_val = max_input_scaled
[ "def", "scale_input_observer", "(", "node", ":", "Node", ",", "modules", ":", "Dict", "[", "str", ",", "nn", ".", "Module", "]", ")", "->", "None", ":", "input_eq_obs", "=", "modules", "[", "str", "(", "node", ".", "target", ")", "]", "assert", "(", ...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/fx/_equalize.py#L373-L392
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/protobuf/python/google/protobuf/internal/cpp_message.py
python
NewCMessage
(full_message_name)
return _net_proto2___python.NewCMessage(full_message_name)
Creates a new C++ protocol message by its name.
Creates a new C++ protocol message by its name.
[ "Creates", "a", "new", "C", "++", "protocol", "message", "by", "its", "name", "." ]
def NewCMessage(full_message_name): """Creates a new C++ protocol message by its name.""" return _net_proto2___python.NewCMessage(full_message_name)
[ "def", "NewCMessage", "(", "full_message_name", ")", ":", "return", "_net_proto2___python", ".", "NewCMessage", "(", "full_message_name", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/protobuf/python/google/protobuf/internal/cpp_message.py#L71-L73
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/sessions.py
python
Session.get_adapter
(self, url)
Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter
Returns the appropriate connection adapter for the given URL.
[ "Returns", "the", "appropriate", "connection", "adapter", "for", "the", "given", "URL", "." ]
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for {!r}".format(url))
[ "def", "get_adapter", "(", "self", ",", "url", ")", ":", "for", "(", "prefix", ",", "adapter", ")", "in", "self", ".", "adapters", ".", "items", "(", ")", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "prefix", ".", "lower", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/sessions.py#L716-L728
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
NotifyEvent.Allow
(*args, **kwargs)
return _core_.NotifyEvent_Allow(*args, **kwargs)
Allow(self) This is the opposite of `Veto`: it explicitly allows the event to be processed. For most events it is not necessary to call this method as the events are allowed anyhow but some are forbidden by default (this will be mentioned in the corresponding event description).
Allow(self)
[ "Allow", "(", "self", ")" ]
def Allow(*args, **kwargs): """ Allow(self) This is the opposite of `Veto`: it explicitly allows the event to be processed. For most events it is not necessary to call this method as the events are allowed anyhow but some are forbidden by default (this will be mentioned in the corresponding event description). """ return _core_.NotifyEvent_Allow(*args, **kwargs)
[ "def", "Allow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "NotifyEvent_Allow", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L5351-L5360
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
Statistics.get_key_value
(self, key)
Return the value of a particular statistical counter. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.get_key_value('nlsat propagations') 2
Return the value of a particular statistical counter.
[ "Return", "the", "value", "of", "a", "particular", "statistical", "counter", "." ]
def get_key_value(self, key): """Return the value of a particular statistical counter. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.get_key_value('nlsat propagations') 2 """ for idx in range(len(self)): if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx): if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) else: return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) raise Z3Exception("unknown key")
[ "def", "get_key_value", "(", "self", ",", "key", ")", ":", "for", "idx", "in", "range", "(", "len", "(", "self", ")", ")", ":", "if", "key", "==", "Z3_stats_get_key", "(", "self", ".", "ctx", ".", "ref", "(", ")", ",", "self", ".", "stats", ",", ...
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L6725-L6743
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
rlpytorch/model_loader.py
python
load_env
(envs, num_models=None, overrides=dict(), defaults=dict(), **kwargs)
return env, all_args
Load envs. envs will be specified as environment variables, more specifically, ``game``, ``model_file`` and ``model`` are required. Returns: env: dict of ``game`` : game module ``method``: Learning method used ``model_loaders``: loaders for model all_args: loaded arguments from `ArgsPrivider`
Load envs. envs will be specified as environment variables, more specifically, ``game``, ``model_file`` and ``model`` are required.
[ "Load", "envs", ".", "envs", "will", "be", "specified", "as", "environment", "variables", "more", "specifically", "game", "model_file", "and", "model", "are", "required", "." ]
def load_env(envs, num_models=None, overrides=dict(), defaults=dict(), **kwargs): ''' Load envs. envs will be specified as environment variables, more specifically, ``game``, ``model_file`` and ``model`` are required. Returns: env: dict of ``game`` : game module ``method``: Learning method used ``model_loaders``: loaders for model all_args: loaded arguments from `ArgsPrivider` ''' game = load_module(envs["game"]).Loader() model_file = load_module(envs["model_file"]) # TODO This is not good, need to fix. if len(model_file.Models[envs["model"]]) == 2: model_class, method_class = model_file.Models[envs["model"]] sampler_class = Sampler else: model_class, method_class, sampler_class = model_file.Models[envs["model"]] defaults.update(getattr(model_file, "Defaults", dict())) overrides.update(getattr(model_file, "Overrides", dict())) method = method_class() sampler = sampler_class() mi = ModelInterface() # You might want multiple models loaded. if num_models is None: model_loaders = [ ModelLoader(model_class) ] else: model_loaders = [ ModelLoader(model_class, model_idx=i) for i in range(num_models) ] env = dict(game=game, method=method, sampler=sampler, model_loaders=model_loaders, mi=mi) env.update(kwargs) parser = argparse.ArgumentParser() all_args = ArgsProvider.Load(parser, env, global_defaults=defaults, global_overrides=overrides) return env, all_args
[ "def", "load_env", "(", "envs", ",", "num_models", "=", "None", ",", "overrides", "=", "dict", "(", ")", ",", "defaults", "=", "dict", "(", ")", ",", "*", "*", "kwargs", ")", ":", "game", "=", "load_module", "(", "envs", "[", "\"game\"", "]", ")", ...
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/rlpytorch/model_loader.py#L99-L136
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/ao/ns/fx/graph_matcher.py
python
_get_name_for_subgraph
( subgraph_a: NSSubgraph, gm_a: GraphModule, base_name_to_sets_of_related_ops: Dict[str, Set[NSNodeTargetType]], existing_names: Set[str], )
return proposed_name
Returns a unique name for a subgraph. This name is based on two things: 1. the name of the set containing the underlying type of the base op in the subgraph (i.e. 'torch.nn.functional.linear' if this is related to a linear op) 2. the number of previous subgraphs with related underlying type of the base op For example, in the graph linear0 -> relu0 -> linear1 -> relu1 The subgraphs are (linear0, relu0) and (linear1, relu1). If we iterate from the output node backwards, the name given to (linear1, relu1) will be `base_op_torch.nn.functional.linear_0`, and the name given to (linear0, relu0) will be `base_op_torch.nn.functional.linear_1`. Why are we not just using the node name? Answer: because of two requirements: A. fusions must be supported B. some Numeric Suite APIs can be called without having all of the models in memory For example, let's say we need to match nodes of (1) ... -> linear0 -> relu0 -> ... And (2) ... -> linear_relu0 -> ... Without being able to inspect them together. With the current naming scheme, if we iterate through both of these graphs in the same order, and assuming the rest of the graphs match, both of these subgraphs will get the same name without (1) and (2) knowing anything about each other.
Returns a unique name for a subgraph. This name is based on two things: 1. the name of the set containing the underlying type of the base op in the subgraph (i.e. 'torch.nn.functional.linear' if this is related to a linear op) 2. the number of previous subgraphs with related underlying type of the base op
[ "Returns", "a", "unique", "name", "for", "a", "subgraph", ".", "This", "name", "is", "based", "on", "two", "things", ":", "1", ".", "the", "name", "of", "the", "set", "containing", "the", "underlying", "type", "of", "the", "base", "op", "in", "the", ...
def _get_name_for_subgraph( subgraph_a: NSSubgraph, gm_a: GraphModule, base_name_to_sets_of_related_ops: Dict[str, Set[NSNodeTargetType]], existing_names: Set[str], ) -> str: """ Returns a unique name for a subgraph. This name is based on two things: 1. the name of the set containing the underlying type of the base op in the subgraph (i.e. 'torch.nn.functional.linear' if this is related to a linear op) 2. the number of previous subgraphs with related underlying type of the base op For example, in the graph linear0 -> relu0 -> linear1 -> relu1 The subgraphs are (linear0, relu0) and (linear1, relu1). If we iterate from the output node backwards, the name given to (linear1, relu1) will be `base_op_torch.nn.functional.linear_0`, and the name given to (linear0, relu0) will be `base_op_torch.nn.functional.linear_1`. Why are we not just using the node name? Answer: because of two requirements: A. fusions must be supported B. some Numeric Suite APIs can be called without having all of the models in memory For example, let's say we need to match nodes of (1) ... -> linear0 -> relu0 -> ... And (2) ... -> linear_relu0 -> ... Without being able to inspect them together. With the current naming scheme, if we iterate through both of these graphs in the same order, and assuming the rest of the graphs match, both of these subgraphs will get the same name without (1) and (2) knowing anything about each other. """ target_type = _get_node_target_type(subgraph_a.base_op_node, gm_a) target_base_type = None for base_name, sets_of_related_ops in base_name_to_sets_of_related_ops.items(): if target_type in sets_of_related_ops: target_base_type = base_name target_base_name = 'base_op_' + str(target_base_type) counter = 0 proposed_name = target_base_name + '_' + str(counter) while proposed_name in existing_names: counter += 1 proposed_name = target_base_name + '_' + str(counter) existing_names.add(proposed_name) return proposed_name
[ "def", "_get_name_for_subgraph", "(", "subgraph_a", ":", "NSSubgraph", ",", "gm_a", ":", "GraphModule", ",", "base_name_to_sets_of_related_ops", ":", "Dict", "[", "str", ",", "Set", "[", "NSNodeTargetType", "]", "]", ",", "existing_names", ":", "Set", "[", "str"...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/ns/fx/graph_matcher.py#L242-L292
tensorflow/serving
3b29e18ab57c68604f599d0b3e1f8df417d22427
tensorflow_serving/apis/prediction_service_pb2_grpc.py
python
PredictionServiceServicer.Classify
(self, request, context)
Classify.
Classify.
[ "Classify", "." ]
def Classify(self, request, context): """Classify. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
[ "def", "Classify", "(", "self", ",", "request", ",", "context", ")", ":", "context", ".", "set_code", "(", "grpc", ".", "StatusCode", ".", "UNIMPLEMENTED", ")", "context", ".", "set_details", "(", "'Method not implemented!'", ")", "raise", "NotImplementedError",...
https://github.com/tensorflow/serving/blob/3b29e18ab57c68604f599d0b3e1f8df417d22427/tensorflow_serving/apis/prediction_service_pb2_grpc.py#L73-L78
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
UpdateUIEvent.GetShown
(*args, **kwargs)
return _core_.UpdateUIEvent_GetShown(*args, **kwargs)
GetShown(self) -> bool Returns ``True`` if the UI element should be shown.
GetShown(self) -> bool
[ "GetShown", "(", "self", ")", "-", ">", "bool" ]
def GetShown(*args, **kwargs): """ GetShown(self) -> bool Returns ``True`` if the UI element should be shown. """ return _core_.UpdateUIEvent_GetShown(*args, **kwargs)
[ "def", "GetShown", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "UpdateUIEvent_GetShown", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L6765-L6771
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/utils/checkpoint.py
python
checkpoint_sequential
(functions, segments, input, **kwargs)
return run_function(end + 1, len(functions) - 1, functions)(input)
r"""A helper function for checkpointing sequential models. Sequential models execute a list of modules/functions in order (sequentially). Therefore, we can divide such a model in various segments and checkpoint each segment. All segments except the last will run in :func:`torch.no_grad` manner, i.e., not storing the intermediate activations. The inputs of each checkpointed segment will be saved for re-running the segment in the backward pass. See :func:`~torch.utils.checkpoint.checkpoint` on how checkpointing works. .. warning:: Checkpointing currently only supports :func:`torch.autograd.backward` and only if its `inputs` argument is not passed. :func:`torch.autograd.grad` is not supported. .. warning: At least one of the inputs needs to have :code:`requires_grad=True` if grads are needed for model inputs, otherwise the checkpointed part of the model won't have gradients. .. warning: Since PyTorch 1.4, it allows only one Tensor as the input and intermediate outputs, just like :class:`torch.nn.Sequential`. Args: functions: A :class:`torch.nn.Sequential` or the list of modules or functions (comprising the model) to run sequentially. segments: Number of chunks to create in the model input: A Tensor that is input to :attr:`functions` preserve_rng_state(bool, optional, default=True): Omit stashing and restoring the RNG state during each checkpoint. Returns: Output of running :attr:`functions` sequentially on :attr:`*inputs` Example: >>> model = nn.Sequential(...) >>> input_var = checkpoint_sequential(model, chunks, input_var)
r"""A helper function for checkpointing sequential models.
[ "r", "A", "helper", "function", "for", "checkpointing", "sequential", "models", "." ]
def checkpoint_sequential(functions, segments, input, **kwargs): r"""A helper function for checkpointing sequential models. Sequential models execute a list of modules/functions in order (sequentially). Therefore, we can divide such a model in various segments and checkpoint each segment. All segments except the last will run in :func:`torch.no_grad` manner, i.e., not storing the intermediate activations. The inputs of each checkpointed segment will be saved for re-running the segment in the backward pass. See :func:`~torch.utils.checkpoint.checkpoint` on how checkpointing works. .. warning:: Checkpointing currently only supports :func:`torch.autograd.backward` and only if its `inputs` argument is not passed. :func:`torch.autograd.grad` is not supported. .. warning: At least one of the inputs needs to have :code:`requires_grad=True` if grads are needed for model inputs, otherwise the checkpointed part of the model won't have gradients. .. warning: Since PyTorch 1.4, it allows only one Tensor as the input and intermediate outputs, just like :class:`torch.nn.Sequential`. Args: functions: A :class:`torch.nn.Sequential` or the list of modules or functions (comprising the model) to run sequentially. segments: Number of chunks to create in the model input: A Tensor that is input to :attr:`functions` preserve_rng_state(bool, optional, default=True): Omit stashing and restoring the RNG state during each checkpoint. Returns: Output of running :attr:`functions` sequentially on :attr:`*inputs` Example: >>> model = nn.Sequential(...) >>> input_var = checkpoint_sequential(model, chunks, input_var) """ # Hack for keyword-only parameter in a python 2.7-compliant way preserve = kwargs.pop('preserve_rng_state', True) if kwargs: raise ValueError("Unexpected keyword arguments: " + ",".join(arg for arg in kwargs)) def run_function(start, end, functions): def forward(input): for j in range(start, end + 1): input = functions[j](input) return input return forward if isinstance(functions, torch.nn.Sequential): functions = list(functions.children()) segment_size = len(functions) // segments # the last chunk has to be non-volatile end = -1 for start in range(0, segment_size * (segments - 1), segment_size): end = start + segment_size - 1 input = checkpoint(run_function(start, end, functions), input, preserve_rng_state=preserve) return run_function(end + 1, len(functions) - 1, functions)(input)
[ "def", "checkpoint_sequential", "(", "functions", ",", "segments", ",", "input", ",", "*", "*", "kwargs", ")", ":", "# Hack for keyword-only parameter in a python 2.7-compliant way", "preserve", "=", "kwargs", ".", "pop", "(", "'preserve_rng_state'", ",", "True", ")",...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/utils/checkpoint.py#L244-L307
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py
python
Dir.File
(self, name)
return self.fs.File(name, self)
Looks up or creates a file node named 'name' relative to this directory.
Looks up or creates a file node named 'name' relative to this directory.
[ "Looks", "up", "or", "creates", "a", "file", "node", "named", "name", "relative", "to", "this", "directory", "." ]
def File(self, name): """ Looks up or creates a file node named 'name' relative to this directory. """ return self.fs.File(name, self)
[ "def", "File", "(", "self", ",", "name", ")", ":", "return", "self", ".", "fs", ".", "File", "(", "name", ",", "self", ")" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py#L1649-L1654
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
samples/pubsub/advanced/kwargs_topics.py
python
topic_2.msgDataSpec
(msg=None)
- msg: a text string
- msg: a text string
[ "-", "msg", ":", "a", "text", "string" ]
def msgDataSpec(msg=None): """ - msg: a text string """
[ "def", "msgDataSpec", "(", "msg", "=", "None", ")", ":" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/pubsub/advanced/kwargs_topics.py#L36-L39
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py
python
_format_mapdict
(mapdict, script=False)
return _flatten(opts)
Formats mapdict to pass it to tk.call. E.g. (script=False): {'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]} returns: ('-expand', '{active selected} grey focus {1, 2, 3, 4}')
Formats mapdict to pass it to tk.call.
[ "Formats", "mapdict", "to", "pass", "it", "to", "tk", ".", "call", "." ]
def _format_mapdict(mapdict, script=False): """Formats mapdict to pass it to tk.call. E.g. (script=False): {'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]} returns: ('-expand', '{active selected} grey focus {1, 2, 3, 4}')""" opts = [] for opt, value in mapdict.iteritems(): opts.extend(("-%s" % opt, _format_optvalue(_mapdict_values(value), script))) return _flatten(opts)
[ "def", "_format_mapdict", "(", "mapdict", ",", "script", "=", "False", ")", ":", "opts", "=", "[", "]", "for", "opt", ",", "value", "in", "mapdict", ".", "iteritems", "(", ")", ":", "opts", ".", "extend", "(", "(", "\"-%s\"", "%", "opt", ",", "_for...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py#L100-L115
greearb/xorp.ct
b8942f69e9cb69a35adcaa58f3dd6b9a16629e6a
xorp/libxorp/callback-gen.py
python
starting_csv
(l, comma = ", ")
return s
Starts a comma separated list. Last element is follow by comma on the assumption that the list will continue after l.
Starts a comma separated list. Last element is follow by comma on the assumption that the list will continue after l.
[ "Starts", "a", "comma", "separated", "list", ".", "Last", "element", "is", "follow", "by", "comma", "on", "the", "assumption", "that", "the", "list", "will", "continue", "after", "l", "." ]
def starting_csv(l, comma = ", "): """ Starts a comma separated list. Last element is follow by comma on the assumption that the list will continue after l. """ s = '' n = len(l) for i in range(0,n): s += "%s%s" % (l[i], comma) return s;
[ "def", "starting_csv", "(", "l", ",", "comma", "=", "\", \"", ")", ":", "s", "=", "''", "n", "=", "len", "(", "l", ")", "for", "i", "in", "range", "(", "0", ",", "n", ")", ":", "s", "+=", "\"%s%s\"", "%", "(", "l", "[", "i", "]", ",", "co...
https://github.com/greearb/xorp.ct/blob/b8942f69e9cb69a35adcaa58f3dd6b9a16629e6a/xorp/libxorp/callback-gen.py#L101-L111
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/config/find_OOM_errors.py
python
count_lines
()
Keep track of the amount of times individual lines occur, in order to prioritize the errors which occur most frequently.
Keep track of the amount of times individual lines occur, in order to prioritize the errors which occur most frequently.
[ "Keep", "track", "of", "the", "amount", "of", "times", "individual", "lines", "occur", "in", "order", "to", "prioritize", "the", "errors", "which", "occur", "most", "frequently", "." ]
def count_lines(): """Keep track of the amount of times individual lines occur, in order to prioritize the errors which occur most frequently.""" counts = {} for string,count in blacklist.items(): for line in string.split("\n"): counts[line] = counts.get(line, 0) + count lines = [] for k,v in counts.items(): lines.append("{0:6}: {1}".format(v, k)) lines.sort() countlog = file("../OOM_count_log", "w") countlog.write("\n".join(lines)) countlog.flush() countlog.close()
[ "def", "count_lines", "(", ")", ":", "counts", "=", "{", "}", "for", "string", ",", "count", "in", "blacklist", ".", "items", "(", ")", ":", "for", "line", "in", "string", ".", "split", "(", "\"\\n\"", ")", ":", "counts", "[", "line", "]", "=", "...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/config/find_OOM_errors.py#L94-L111
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/attrs/attr/_make.py
python
_get_annotations
(cls)
return {}
Get annotations for *cls*.
Get annotations for *cls*.
[ "Get", "annotations", "for", "*", "cls", "*", "." ]
def _get_annotations(cls): """ Get annotations for *cls*. """ if _has_own_attribute(cls, "__annotations__"): return cls.__annotations__ return {}
[ "def", "_get_annotations", "(", "cls", ")", ":", "if", "_has_own_attribute", "(", "cls", ",", "\"__annotations__\"", ")", ":", "return", "cls", ".", "__annotations__", "return", "{", "}" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/attrs/attr/_make.py#L421-L428
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
amalgamation/python/mxnet_predict.py
python
Predictor.reshape
(self, input_shapes)
Change the input shape of the predictor. Parameters ---------- input_shapes : dict of str to tuple The new shape of input data. Examples -------- >>> predictor.reshape({'data':data_shape_tuple})
Change the input shape of the predictor.
[ "Change", "the", "input", "shape", "of", "the", "predictor", "." ]
def reshape(self, input_shapes): """Change the input shape of the predictor. Parameters ---------- input_shapes : dict of str to tuple The new shape of input data. Examples -------- >>> predictor.reshape({'data':data_shape_tuple}) """ indptr = [0] sdata = [] keys = [] for k, v in input_shapes.items(): if not isinstance(v, tuple): raise ValueError("Expect input_shapes to be dict str->tuple") keys.append(c_str(k)) sdata.extend(v) indptr.append(len(sdata)) new_handle = PredictorHandle() _check_call(_LIB.MXPredReshape( mx_uint(len(indptr) - 1), c_array(ctypes.c_char_p, keys), c_array(mx_uint, indptr), c_array(mx_uint, sdata), self.handle, ctypes.byref(new_handle))) _check_call(_LIB.MXPredFree(self.handle)) self.handle = new_handle
[ "def", "reshape", "(", "self", ",", "input_shapes", ")", ":", "indptr", "=", "[", "0", "]", "sdata", "=", "[", "]", "keys", "=", "[", "]", "for", "k", ",", "v", "in", "input_shapes", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", ...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/amalgamation/python/mxnet_predict.py#L173-L204
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/release/common_includes.py
python
MakeChangeLogBugReference
(body)
Grep for "BUG=xxxx" lines in the commit message and convert them to "(issue xxxx)".
Grep for "BUG=xxxx" lines in the commit message and convert them to "(issue xxxx)".
[ "Grep", "for", "BUG", "=", "xxxx", "lines", "in", "the", "commit", "message", "and", "convert", "them", "to", "(", "issue", "xxxx", ")", "." ]
def MakeChangeLogBugReference(body): """Grep for "BUG=xxxx" lines in the commit message and convert them to "(issue xxxx)". """ crbugs = [] v8bugs = [] def AddIssues(text): ref = re.match(r"^BUG[ \t]*=[ \t]*(.+)$", text.strip()) if not ref: return for bug in ref.group(1).split(","): bug = bug.strip() match = re.match(r"^v8:(\d+)$", bug) if match: v8bugs.append(int(match.group(1))) else: match = re.match(r"^(?:chromium:)?(\d+)$", bug) if match: crbugs.append(int(match.group(1))) # Add issues to crbugs and v8bugs. map(AddIssues, body.splitlines()) # Filter duplicates, sort, stringify. crbugs = map(str, sorted(set(crbugs))) v8bugs = map(str, sorted(set(v8bugs))) bug_groups = [] def FormatIssues(prefix, bugs): if len(bugs) > 0: plural = "s" if len(bugs) > 1 else "" bug_groups.append("%sissue%s %s" % (prefix, plural, ", ".join(bugs))) FormatIssues("", v8bugs) FormatIssues("Chromium ", crbugs) if len(bug_groups) > 0: return "(%s)" % ", ".join(bug_groups) else: return ""
[ "def", "MakeChangeLogBugReference", "(", "body", ")", ":", "crbugs", "=", "[", "]", "v8bugs", "=", "[", "]", "def", "AddIssues", "(", "text", ")", ":", "ref", "=", "re", ".", "match", "(", "r\"^BUG[ \\t]*=[ \\t]*(.+)$\"", ",", "text", ".", "strip", "(", ...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/release/common_includes.py#L137-L175
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plistlib.py
python
readPlist
(pathOrFile)
return rootObject
Read a .plist file. 'pathOrFile' may either be a file name or a (readable) file object. Return the unpacked root object (which usually is a dictionary).
Read a .plist file. 'pathOrFile' may either be a file name or a (readable) file object. Return the unpacked root object (which usually is a dictionary).
[ "Read", "a", ".", "plist", "file", ".", "pathOrFile", "may", "either", "be", "a", "file", "name", "or", "a", "(", "readable", ")", "file", "object", ".", "Return", "the", "unpacked", "root", "object", "(", "which", "usually", "is", "a", "dictionary", "...
def readPlist(pathOrFile): """Read a .plist file. 'pathOrFile' may either be a file name or a (readable) file object. Return the unpacked root object (which usually is a dictionary). """ didOpen = 0 if isinstance(pathOrFile, (str, unicode)): pathOrFile = open(pathOrFile) didOpen = 1 p = PlistParser() rootObject = p.parse(pathOrFile) if didOpen: pathOrFile.close() return rootObject
[ "def", "readPlist", "(", "pathOrFile", ")", ":", "didOpen", "=", "0", "if", "isinstance", "(", "pathOrFile", ",", "(", "str", ",", "unicode", ")", ")", ":", "pathOrFile", "=", "open", "(", "pathOrFile", ")", "didOpen", "=", "1", "p", "=", "PlistParser"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plistlib.py#L68-L81
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py
python
BabylMessage._explain_to
(self, message)
Copy Babyl-specific state to message insofar as possible.
Copy Babyl-specific state to message insofar as possible.
[ "Copy", "Babyl", "-", "specific", "state", "to", "message", "insofar", "as", "possible", "." ]
def _explain_to(self, message): """Copy Babyl-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): labels = set(self.get_labels()) if 'unseen' in labels: message.set_subdir('cur') else: message.set_subdir('cur') message.add_flag('S') if 'forwarded' in labels or 'resent' in labels: message.add_flag('P') if 'answered' in labels: message.add_flag('R') if 'deleted' in labels: message.add_flag('T') elif isinstance(message, _mboxMMDFMessage): labels = set(self.get_labels()) if 'unseen' not in labels: message.add_flag('RO') else: message.add_flag('O') if 'deleted' in labels: message.add_flag('D') if 'answered' in labels: message.add_flag('A') elif isinstance(message, MHMessage): labels = set(self.get_labels()) if 'unseen' in labels: message.add_sequence('unseen') if 'answered' in labels: message.add_sequence('replied') elif isinstance(message, BabylMessage): message.set_visible(self.get_visible()) for label in self.get_labels(): message.add_label(label) elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message))
[ "def", "_explain_to", "(", "self", ",", "message", ")", ":", "if", "isinstance", "(", "message", ",", "MaildirMessage", ")", ":", "labels", "=", "set", "(", "self", ".", "get_labels", "(", ")", ")", "if", "'unseen'", "in", "labels", ":", "message", "."...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py#L1874-L1913
googlearchive/tango-examples-c
b57d8c173664de569a7fec703091ff82684a2db5
third_party/libfreetype/src/tools/docmaker/tohtml.py
python
HtmlFormatter.make_html_items
( self, items )
return string.join( lines, '\n' )
convert a field's content into some valid HTML
convert a field's content into some valid HTML
[ "convert", "a", "field", "s", "content", "into", "some", "valid", "HTML" ]
def make_html_items( self, items ): """ convert a field's content into some valid HTML """ lines = [] for item in items: if item.lines: lines.append( self.make_html_code( item.lines ) ) else: lines.append( self.make_html_para( item.words ) ) return string.join( lines, '\n' )
[ "def", "make_html_items", "(", "self", ",", "items", ")", ":", "lines", "=", "[", "]", "for", "item", "in", "items", ":", "if", "item", ".", "lines", ":", "lines", ".", "append", "(", "self", ".", "make_html_code", "(", "item", ".", "lines", ")", "...
https://github.com/googlearchive/tango-examples-c/blob/b57d8c173664de569a7fec703091ff82684a2db5/third_party/libfreetype/src/tools/docmaker/tohtml.py#L311-L320
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/graph_editor/edit.py
python
bypass
(sgv)
return sgv, detached_inputs
Bypass the given subgraph by connecting its inputs to its outputs. Args: sgv: the subgraph view to be bypassed. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. Returns: A new subgraph view of the bypassed subgraph. Note that sgv is also modified in place. Raises: StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view.
Bypass the given subgraph by connecting its inputs to its outputs.
[ "Bypass", "the", "given", "subgraph", "by", "connecting", "its", "inputs", "to", "its", "outputs", "." ]
def bypass(sgv): """Bypass the given subgraph by connecting its inputs to its outputs. Args: sgv: the subgraph view to be bypassed. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. Returns: A new subgraph view of the bypassed subgraph. Note that sgv is also modified in place. Raises: StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ # TODO(fkp): allows to plug sgv.inputs to individual sgv.outputs consumers sgv = subgraph.make_view(sgv) sgv_inputs = list(sgv.inputs) sgv, detached_inputs = detach_inputs(sgv) reroute.reroute_a2b_ts(sgv_inputs, sgv.outputs) return sgv, detached_inputs
[ "def", "bypass", "(", "sgv", ")", ":", "# TODO(fkp): allows to plug sgv.inputs to individual sgv.outputs consumers", "sgv", "=", "subgraph", ".", "make_view", "(", "sgv", ")", "sgv_inputs", "=", "list", "(", "sgv", ".", "inputs", ")", "sgv", ",", "detached_inputs", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/graph_editor/edit.py#L183-L201
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.SetRectangularSelectionModifier
(*args, **kwargs)
return _stc.StyledTextCtrl_SetRectangularSelectionModifier(*args, **kwargs)
SetRectangularSelectionModifier(self, int modifier) On GTK+, allow selecting the modifier key to use for mouse-based rectangular selection. Often the window manager requires Alt+Mouse Drag for moving windows. Valid values are SCMOD_CTRL(default), SCMOD_ALT, or SCMOD_SUPER.
SetRectangularSelectionModifier(self, int modifier)
[ "SetRectangularSelectionModifier", "(", "self", "int", "modifier", ")" ]
def SetRectangularSelectionModifier(*args, **kwargs): """ SetRectangularSelectionModifier(self, int modifier) On GTK+, allow selecting the modifier key to use for mouse-based rectangular selection. Often the window manager requires Alt+Mouse Drag for moving windows. Valid values are SCMOD_CTRL(default), SCMOD_ALT, or SCMOD_SUPER. """ return _stc.StyledTextCtrl_SetRectangularSelectionModifier(*args, **kwargs)
[ "def", "SetRectangularSelectionModifier", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetRectangularSelectionModifier", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L6248-L6257
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/html.py
python
HtmlCell.GetDepth
(*args, **kwargs)
return _html.HtmlCell_GetDepth(*args, **kwargs)
GetDepth(self) -> unsigned int
GetDepth(self) -> unsigned int
[ "GetDepth", "(", "self", ")", "-", ">", "unsigned", "int" ]
def GetDepth(*args, **kwargs): """GetDepth(self) -> unsigned int""" return _html.HtmlCell_GetDepth(*args, **kwargs)
[ "def", "GetDepth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlCell_GetDepth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L734-L736
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/msvc9compiler.py
python
query_vcvarsall
(version, arch="x86")
return result
Launch vcvarsall.bat and read the settings from its environment
Launch vcvarsall.bat and read the settings from its environment
[ "Launch", "vcvarsall", ".", "bat", "and", "read", "the", "settings", "from", "its", "environment" ]
def query_vcvarsall(version, arch="x86"): """Launch vcvarsall.bat and read the settings from its environment """ vcvarsall = find_vcvarsall(version) interesting = set(("include", "lib", "libpath", "path")) result = {} if vcvarsall is None: raise DistutilsPlatformError("Unable to find vcvarsall.bat") log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version) popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch), stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: stdout, stderr = popen.communicate() if popen.wait() != 0: raise DistutilsPlatformError(stderr.decode("mbcs")) stdout = stdout.decode("mbcs") for line in stdout.split("\n"): line = Reg.convert_mbcs(line) if '=' not in line: continue line = line.strip() key, value = line.split('=', 1) key = key.lower() if key in interesting: if value.endswith(os.pathsep): value = value[:-1] result[key] = removeDuplicates(value) finally: popen.stdout.close() popen.stderr.close() if len(result) != len(interesting): raise ValueError(str(list(result.keys()))) return result
[ "def", "query_vcvarsall", "(", "version", ",", "arch", "=", "\"x86\"", ")", ":", "vcvarsall", "=", "find_vcvarsall", "(", "version", ")", "interesting", "=", "set", "(", "(", "\"include\"", ",", "\"lib\"", ",", "\"libpath\"", ",", "\"path\"", ")", ")", "re...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/msvc9compiler.py#L263-L301
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_trustregion_constr/canonical_constraint.py
python
CanonicalConstraint.from_PreparedConstraint
(cls, constraint)
Create an instance from `PreparedConstrained` object.
Create an instance from `PreparedConstrained` object.
[ "Create", "an", "instance", "from", "PreparedConstrained", "object", "." ]
def from_PreparedConstraint(cls, constraint): """Create an instance from `PreparedConstrained` object.""" lb, ub = constraint.bounds cfun = constraint.fun keep_feasible = constraint.keep_feasible if np.all(lb == -np.inf) and np.all(ub == np.inf): return cls.empty(cfun.n) if np.all(lb == -np.inf) and np.all(ub == np.inf): return cls.empty(cfun.n) elif np.all(lb == ub): return cls._equal_to_canonical(cfun, lb) elif np.all(lb == -np.inf): return cls._less_to_canonical(cfun, ub, keep_feasible) elif np.all(ub == np.inf): return cls._greater_to_canonical(cfun, lb, keep_feasible) else: return cls._interval_to_canonical(cfun, lb, ub, keep_feasible)
[ "def", "from_PreparedConstraint", "(", "cls", ",", "constraint", ")", ":", "lb", ",", "ub", "=", "constraint", ".", "bounds", "cfun", "=", "constraint", ".", "fun", "keep_feasible", "=", "constraint", ".", "keep_feasible", "if", "np", ".", "all", "(", "lb"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_trustregion_constr/canonical_constraint.py#L51-L69
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/third_party/jinja2/compiler.py
python
generate
(node, environment, name, filename, stream=None, defer_init=False)
Generate the python source for a node tree.
Generate the python source for a node tree.
[ "Generate", "the", "python", "source", "for", "a", "node", "tree", "." ]
def generate(node, environment, name, filename, stream=None, defer_init=False): """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') generator = environment.code_generator_class(environment, name, filename, stream, defer_init) generator.visit(node) if stream is None: return generator.stream.getvalue()
[ "def", "generate", "(", "node", ",", "environment", ",", "name", ",", "filename", ",", "stream", "=", "None", ",", "defer_init", "=", "False", ")", ":", "if", "not", "isinstance", "(", "node", ",", "nodes", ".", "Template", ")", ":", "raise", "TypeErro...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/compiler.py#L55-L64
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PropertyGridInterface.SetPropertyHelpString
(*args, **kwargs)
return _propgrid.PropertyGridInterface_SetPropertyHelpString(*args, **kwargs)
SetPropertyHelpString(self, PGPropArg id, String helpString)
SetPropertyHelpString(self, PGPropArg id, String helpString)
[ "SetPropertyHelpString", "(", "self", "PGPropArg", "id", "String", "helpString", ")" ]
def SetPropertyHelpString(*args, **kwargs): """SetPropertyHelpString(self, PGPropArg id, String helpString)""" return _propgrid.PropertyGridInterface_SetPropertyHelpString(*args, **kwargs)
[ "def", "SetPropertyHelpString", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_SetPropertyHelpString", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L1434-L1436
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/model/calibrate.py
python
RobotExtrinsicCalibration.executeTrajectory
(self, controller : RobotInterfaceBase, traj : RobotTrajectory, camera_fn : Callable, detect_fn : Callable=None, speed=1.0, wait=0.0)
Executes a trajectory on a controller, optionally taking images along the way. TODO: specify times to actually stop.
Executes a trajectory on a controller, optionally taking images along the way.
[ "Executes", "a", "trajectory", "on", "a", "controller", "optionally", "taking", "images", "along", "the", "way", "." ]
def executeTrajectory(self, controller : RobotInterfaceBase, traj : RobotTrajectory, camera_fn : Callable, detect_fn : Callable=None, speed=1.0, wait=0.0) -> None: """Executes a trajectory on a controller, optionally taking images along the way. TODO: specify times to actually stop. """ import time def wait_for_move(): moving = True while moving: controller.beginStep() moving = controller.isMoving() controller.endStep() time.sleep(0.1) for i in range(len(traj.milestones)): print("Moving to milestone",i) controller.beginStep() controller.moveToPosition(traj.milestones[0],speed) controller.endStep() wait_for_move() if wait != 0: print("Waiting for",wait,"s") time.sleep(wait*0.5) if camera_fn: print("Taking pictures") if isinstance(camera_fn,dict): for (k,fn) in camera_fn.items(): image = fn() self.add_frame(image,controller.sensedPosition(),camera_id=k,detect_fn=detect_fn) else: image = camera_fn() self.add_frame(image,controller.sensedPosition(),detect_fn=detect_fn) time.sleep(wait*0.5)
[ "def", "executeTrajectory", "(", "self", ",", "controller", ":", "RobotInterfaceBase", ",", "traj", ":", "RobotTrajectory", ",", "camera_fn", ":", "Callable", ",", "detect_fn", ":", "Callable", "=", "None", ",", "speed", "=", "1.0", ",", "wait", "=", "0.0", ...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/calibrate.py#L281-L321
google/iree
1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76
integrations/tensorflow/python_projects/iree_tf/iree/tf/support/module_utils.py
python
_IreeFunctionWrapper.get_serialized_values
(self)
Get cxx serialized inputs and outputs for this function.
Get cxx serialized inputs and outputs for this function.
[ "Get", "cxx", "serialized", "inputs", "and", "outputs", "for", "this", "function", "." ]
def get_serialized_values(self) -> Tuple[Tuple[str], Tuple[str]]: """Get cxx serialized inputs and outputs for this function.""" if hasattr(self._f, "get_serialized_values"): # TODO: The native ABI does not implement this, and if still needed, # it should not be implemented this way (maybe a thread local trace # listener). return self._f.get_serialized_values() else: return ("",), ("",)
[ "def", "get_serialized_values", "(", "self", ")", "->", "Tuple", "[", "Tuple", "[", "str", "]", ",", "Tuple", "[", "str", "]", "]", ":", "if", "hasattr", "(", "self", ".", "_f", ",", "\"get_serialized_values\"", ")", ":", "# TODO: The native ABI does not imp...
https://github.com/google/iree/blob/1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76/integrations/tensorflow/python_projects/iree_tf/iree/tf/support/module_utils.py#L299-L307
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/tensor_move.py
python
_tensor_move_tbe
()
return
TensorMove TBE register
TensorMove TBE register
[ "TensorMove", "TBE", "register" ]
def _tensor_move_tbe(): """TensorMove TBE register""" return
[ "def", "_tensor_move_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/tensor_move.py#L39-L41
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/ma/core.py
python
is_mask
(m)
Return True if m is a valid, standard mask. This function does not check the contents of the input, only that the type is MaskType. In particular, this function returns False if the mask has a flexible dtype. Parameters ---------- m : array_like Array to test. Returns ------- result : bool True if `m.dtype.type` is MaskType, False otherwise. See Also -------- isMaskedArray : Test whether input is an instance of MaskedArray. Examples -------- >>> import numpy.ma as ma >>> m = ma.masked_equal([0, 1, 0, 2, 3], 0) >>> m masked_array(data = [-- 1 -- 2 3], mask = [ True False True False False], fill_value=999999) >>> ma.is_mask(m) False >>> ma.is_mask(m.mask) True Input must be an ndarray (or have similar attributes) for it to be considered a valid mask. >>> m = [False, True, False] >>> ma.is_mask(m) False >>> m = np.array([False, True, False]) >>> m array([False, True, False]) >>> ma.is_mask(m) True Arrays with complex dtypes don't return True. >>> dtype = np.dtype({'names':['monty', 'pithon'], 'formats':[bool, bool]}) >>> dtype dtype([('monty', '|b1'), ('pithon', '|b1')]) >>> m = np.array([(True, False), (False, True), (True, False)], dtype=dtype) >>> m array([(True, False), (False, True), (True, False)], dtype=[('monty', '|b1'), ('pithon', '|b1')]) >>> ma.is_mask(m) False
Return True if m is a valid, standard mask.
[ "Return", "True", "if", "m", "is", "a", "valid", "standard", "mask", "." ]
def is_mask(m): """ Return True if m is a valid, standard mask. This function does not check the contents of the input, only that the type is MaskType. In particular, this function returns False if the mask has a flexible dtype. Parameters ---------- m : array_like Array to test. Returns ------- result : bool True if `m.dtype.type` is MaskType, False otherwise. See Also -------- isMaskedArray : Test whether input is an instance of MaskedArray. Examples -------- >>> import numpy.ma as ma >>> m = ma.masked_equal([0, 1, 0, 2, 3], 0) >>> m masked_array(data = [-- 1 -- 2 3], mask = [ True False True False False], fill_value=999999) >>> ma.is_mask(m) False >>> ma.is_mask(m.mask) True Input must be an ndarray (or have similar attributes) for it to be considered a valid mask. >>> m = [False, True, False] >>> ma.is_mask(m) False >>> m = np.array([False, True, False]) >>> m array([False, True, False]) >>> ma.is_mask(m) True Arrays with complex dtypes don't return True. >>> dtype = np.dtype({'names':['monty', 'pithon'], 'formats':[bool, bool]}) >>> dtype dtype([('monty', '|b1'), ('pithon', '|b1')]) >>> m = np.array([(True, False), (False, True), (True, False)], dtype=dtype) >>> m array([(True, False), (False, True), (True, False)], dtype=[('monty', '|b1'), ('pithon', '|b1')]) >>> ma.is_mask(m) False """ try: return m.dtype.type is MaskType except AttributeError: return False
[ "def", "is_mask", "(", "m", ")", ":", "try", ":", "return", "m", ".", "dtype", ".", "type", "is", "MaskType", "except", "AttributeError", ":", "return", "False" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/core.py#L1480-L1545
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/RemoteConsole/ly_remote_console/ly_remote_console/remote_console_commands.py
python
RemoteConsole.pump
(self)
Pump function that is used by the pump_thread. Listens to receive messages from the socket and disconnects during an exception.
Pump function that is used by the pump_thread. Listens to receive messages from the socket and disconnects during an exception.
[ "Pump", "function", "that", "is", "used", "by", "the", "pump_thread", ".", "Listens", "to", "receive", "messages", "from", "the", "socket", "and", "disconnects", "during", "an", "exception", "." ]
def pump(self): # type: () -> None """ Pump function that is used by the pump_thread. Listens to receive messages from the socket and disconnects during an exception. """ while not self.stop_pump.is_set(): # Sending a NOOP message in order to get log lines self._send_message(self._create_message(CONSOLE_MESSAGE_MAP['NOOP'])) try: self._handle_message(self.socket.recv(4096)) except: self.on_disconnect() self.stop_pump.set()
[ "def", "pump", "(", "self", ")", ":", "# type: () -> None", "while", "not", "self", ".", "stop_pump", ".", "is_set", "(", ")", ":", "# Sending a NOOP message in order to get log lines", "self", ".", "_send_message", "(", "self", ".", "_create_message", "(", "CONSO...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/RemoteConsole/ly_remote_console/ly_remote_console/remote_console_commands.py#L184-L197
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListMainWindow.TileBackground
(self, dc)
Tiles the background image to fill all the available area. :param `dc`: an instance of :class:`DC`. .. todo:: Support background images also in stretch and centered modes.
Tiles the background image to fill all the available area.
[ "Tiles", "the", "background", "image", "to", "fill", "all", "the", "available", "area", "." ]
def TileBackground(self, dc): """ Tiles the background image to fill all the available area. :param `dc`: an instance of :class:`DC`. .. todo:: Support background images also in stretch and centered modes. """ if not self._backgroundImage: return if self._imageStretchStyle != _StyleTile: # Can we actually do something here (or in OnPaint()) To Handle # background images that are stretchable or always centered? # I tried but I get enormous flickering... return sz = self.GetClientSize() w = self._backgroundImage.GetWidth() h = self._backgroundImage.GetHeight() x = 0 while x < sz.width: y = 0 while y < sz.height: dc.DrawBitmap(self._backgroundImage, x, y, True) y = y + h x = x + w
[ "def", "TileBackground", "(", "self", ",", "dc", ")", ":", "if", "not", "self", ".", "_backgroundImage", ":", "return", "if", "self", ".", "_imageStretchStyle", "!=", "_StyleTile", ":", "# Can we actually do something here (or in OnPaint()) To Handle", "# background ima...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L7202-L7233